source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"ru.stackoverflow",
"0000570072.txt"
] | Q:
Создать папку на яндекс диск
Вот так загружаю файл на яндекс диск.
system ("curl --user $yadisk_email:$yadisk_pass -T $file
https://webdav.yandex.ru/$yadisc_dir");
Можно ли также просто создать папку на яндекс диск?
Если нет, то какой самый простой способ подскажите?
A:
Попробуй вот так
system ("curl -X MKCOL --user $yadisk_email:$yadisk_pass https://webdav.yandex.ru/$new_dir");
Подробнее здесь.
|
[
"ja.stackoverflow",
"0000036346.txt"
] | Q:
_Layout.cshtmlの状態を変化させたい
_Layout.cshtmlにリンクを作成しいます。
下図の場合、ホーム、詳細、連絡先それぞれをクリックしたとき、下図赤枠部分を現在表示しているページの文字を太字、サイズ変更等したいと考えています。
html.ActionLink時にclassの追加等試したのですがうまく反映されません。
ご教示願います。
A:
通常のリンクで別のページに移動した場合、すべてのDOM要素が再読み込みされますので遷移直前にJavaScriptで設定したスタイルは反映されません。
ですので_Layout.cshtmlで現在表示中のアクションを判定して@classの値を制御してください。
コントローラー名およびアクション名はViewContext.RouteData.Values["controller"]やViewContext.RouteData.Values["action"]で参照できますし、コントローラーから明示的にモデルに指定すれば確実に判定できます。
|
[
"stackoverflow",
"0046311353.txt"
] | Q:
Eta conversion tactics?
Is there a tactic which I can use instead of replace in the example below to simplify this expression?
Require Import Vector.
Goal forall (n b:nat) (x:t nat n), (map (fun a => plus b a) x) = x.
Proof.
intros n b x.
replace (fun a => plus b a) with (plus b) by auto.
...
A:
You are probably looking for something along the following lines:
repeat change (fun x => ?h x) with h.
which allows you to eta-reduce functions of arbitrary arity. This solution uses change's ability to work with patterns (?h in the above piece of code).
Let's give this tactic a more suggestive name like so:
(* h is a dummy argument to make Coq happy, it gets shadowed with `?h` *)
Ltac eta_reduce_all_private h := repeat change (fun x => ?h x) with h.
Ltac eta_reduce_all := eta_reduce_all_private idtac.
If we try to define eta_reduce_all as follows
Ltac eta_reduce_all := repeat change (fun x => ?h x) with h.
Coq will complain about "unbounded" h.
|
[
"math.stackexchange",
"0003653892.txt"
] | Q:
Why are all functions $\{0,1\}^t \rightarrow \{0,1\}$ expressable as polynomials?
Siegelmann, Neural Networks and Analog Computation, p. 41, considers an arbitrary function $\beta(d_1,\ldots,d_t)$ : $\{0,1\}^t \rightarrow \{0,1\}$, and assumes that it can be expressed as a polynomial--a linear combination of products of zero or more $d_i$'s:
$$\beta(d_1,\ldots,d_t) = c_1 + c_2d_1 + \cdots + c_{t+1}d_t + c_{t+2}d_1d_2 + \cdots + c_{2t}d_1d_2\cdots d_t$$
I don't yet understand why every such function $\beta$ can be expressed in this way. Why does this follow merely from the fact that $\beta$ is a map from $\{0,1\}^t$ to $\{0,1\}$?
A:
One way is to associate a monomial with each input vector, and then just add up the monomials to get the desired polynomial. For example, if you want $(0,1,1,0,1)\mapsto 1$, the monomial is $$(1-d_1)d_2 d_3 (1-d_4) d_5.$$ If instead you want $(0,1,1,0,1)\mapsto 0$, the monomial is $$1-(1-d_1)d_2 d_3 (1-d_4) d_5.$$
|
[
"stackoverflow",
"0035209501.txt"
] | Q:
Stripping filename and linenumber from exception message in Lua
Im having trouble stripping out the params I need in my exception message in Lua.
The message I get looks something like the following:
/path/anotherpath/class.lua:929: attempt to index field '?' (a nil value)
What I want to do is to extract the name of the class (the word before ".lua") and the line number (the number after the first ":")
Could anyone help me find the patters I need to be used in string.match?
A:
To give a slightly more complete answer than what Egor had (which looks correct with the caveat that it requires a .lua file extension):
value = "/path/anotherpath/class.lua:929: attempt to index field '?' (a nil value)"
filename, linenumstring = value:match(".-([^/:\\]-)%.lua:(%d+):")
linenum = tonumber(linenumstring)
|
[
"stackoverflow",
"0022778718.txt"
] | Q:
calling a javascript program for a website
Html
<html>
<head>
<script type="text/javascript" src="/test.js"></script>
<script type="text/javascript">
start();
</script>
</head>
<body>
</body>
</html>
Java script
var points = 1;
var points1;
var DELAY = 30;
var SPEED = 5;
var MAX_DY = 12;
var OBSTACLE_WIDTH = 30;
var OBSTACLE_HEIGHT = 100;
var TERRAIN_WIDTH = 10;
var MIN_TERRAIN_HEIGHT = 20;
var MAX_TERRAIN_HEIGHT = 50;
var POINTS_PER_ROUND = 5;
var DUST_RADIUS = 3;
var DUST_BUFFER = 10;
var NUM_OBSTACLES = 3;
var copter;
var dy = 0;
var clicking = false;
var score; // text you see on the screen
var obstacles = [];
var top_terrain = [];
var bottom_terrain = [];
var dust = [];
function start(){
starta();
}
function starta() {
setup();
setTimer(game, DELAY);
mouseDownMethod(onMouseDown);
mouseUpMethod(onMouseUp);
setTimer(points2, 10)
}
function points2(){
points1 = points/100
return points1;
}
function setup() {
setBackgroundColor(Color.black);
copter = new WebImage("image.png");
copter.setSize(25, 50);
copter.setPosition(getWidth()/3, getHeight()/2);
copter.setColor(Color.blue);
add(copter);
addObstacles();
addTerrain();
score = new Text("0");
score.setColor(Color.white);
score.setPosition(10, 30);
add(score);
}
function updateScore() {
points += POINTS_PER_ROUND;
score.setText(points);
}
function game() {
updateScore();
if (hitWall()) {
lose();
return;
}
var collider = getCollider();
if (collider != null) {
if (collider != copter) {
lose();
return;
}
}
if (clicking) {
dy -= 1;
if (dy < -MAX_DY) {
dy = -MAX_DY;
}
} else {
dy += 1;
if (dy > MAX_DY) {
dy = MAX_DY;
}
}
copter.move(0, dy);
moveObstacles();
moveTerrain();
moveDust();
addDust();
}
function onMouseDown(e) {
clicking = true;
}
function onMouseUp(e) {
clicking = false;
}
function addObstacles() {
for (var i = 0; i < NUM_OBSTACLES; i++) {
var obstacle = new WebImage("image.jpg");
obstacle.setSize(50, 100);
obstacle.setColor(Color.green);
obstacle.setPosition(getWidth() + i * (getWidth()/NUM_OBSTACLES),
Randomizer.nextInt(0, getHeight() - OBSTACLE_HEIGHT));
obstacles.push(obstacle);
add(obstacle);
}
}
function moveObstacles() {
for (var i=0; i < obstacles.length; i++) {
var obstacle = obstacles[i];
obstacle.move(-points1, 0);
if(obstacle.getX() < 0) {
obstacle.setPosition(getWidth(),
Randomizer.nextInt(0, getHeight() - OBSTACLE_HEIGHT));
}
}
}
function hitWall() {
var hit_top = copter.getY() < 0;
var hit_bottom = copter.getY() + copter.getHeight() > getHeight();
return hit_top || hit_bottom;
}
function lose() {
stopTimer(game);
var text = new Text("You Lose!");
text.setColor(Color.red);
text.setPosition(getWidth()/2 - text.getWidth()/2,
getHeight()/2);
add(text);
}
function getCollider() {
var topLeft = getElementAt(copter.getX()-1, copter.getY()-1);
if (topLeft != null) {
return topLeft;
}
var topRight = getElementAt(copter.getX() + copter.getWidth() + 1,
copter.getY() - 1);
if (topRight != null) {
return topRight;
}
var bottomLeft = getElementAt(copter.getX()-1,
copter.getY() + copter.getHeight() + 1);
if (bottomLeft != null) {
return bottomLeft;
}
var bottomRight = getElementAt(copter.getX() + copter.getWidth() + 1,
copter.getY() + copter.getHeight() + 1);
if (bottomRight != null) {
return bottomRight;
}
return null;
}
function addTerrain() {
for (var i=0; i <= getWidth() / TERRAIN_WIDTH; i++) {
var height = Randomizer.nextInt(MIN_TERRAIN_HEIGHT, MAX_TERRAIN_HEIGHT);
var terrain = new Rectangle(TERRAIN_WIDTH, height);
terrain.setPosition(TERRAIN_WIDTH * i, 0);
terrain.setColor(Color.green);
top_terrain.push(terrain);
add(terrain);
height = Randomizer.nextInt(MIN_TERRAIN_HEIGHT, MAX_TERRAIN_HEIGHT);
var bottomTerrain = new Rectangle(TERRAIN_WIDTH, height);
bottomTerrain.setPosition(TERRAIN_WIDTH * i,
getHeight() - bottomTerrain.getHeight());
bottomTerrain.setColor(Color.green);
bottom_terrain.push(bottomTerrain);
add(bottomTerrain);
}
}
function moveTerrain() {
for (var i=0; i < top_terrain.length; i++) {
var obj = top_terrain[i];
obj.move(-points1, 0);
if (obj.getX() < -obj.getWidth()) {
obj.setPosition(getWidth(), 0);
}
}
for (var i=0; i < bottom_terrain.length; i++) {
var obj = bottom_terrain[i];
obj.move(-points1, 0);
if (obj.getX() < -obj.getWidth()) {
obj.setPosition(getWidth(), getHeight() - obj.getHeight());
}
}
}
function addDust() {
var d = new Circle(DUST_RADIUS);
d.setColor("#ffd700");
d.setPosition(copter.getX() - d.getWidth(),
copter.getY() + DUST_BUFFER);
dust.push(d);
add(d);
}
function moveDust() {
for (var i=0; i < dust.length; i++) {
var d = dust[i];
d.move(-points1, 0);
d.setRadius(d.getRadius() - 0.1);
if(d.getX() < 0) {
remove(d);
dust.remove(i);
i--;
}
}
}
Okay so here is my script. The script works perfectly fine on a codehs sandbox, but now that I want to set it on my own website it is not working. Could some one please help me out. Thank you.
Could some one please tell me how I would execute this code from test.js. Thank you.
A:
You need to include the .js to your HTML page, like this:
<script type="text/javascript" src="/test.js"></script>
<script type="text/javascript">
start(); //starts your program
</script>
|
[
"stackoverflow",
"0056210626.txt"
] | Q:
completionHandler in Swift4 return String
I am trying to build a small currency converter and the problem is that my completionHandler does not work. As a result, the input Currency does not change instantly after the function was executed
I have already tried to implement a completionHandler; however, had no success yet
class CurrencyExchange: ViewController {
//Outlets
@IBOutlet weak var lblCurrency: UILabel!
@IBOutlet weak var segOutputCurrency: UISegmentedControl!
@IBOutlet weak var txtValue: UITextField!
@IBOutlet weak var segInputCurrency: UISegmentedControl!
//Variables
var inputCurrency: String!
var currencyCNY: Double!
var currencyEUR: Double!
var currencyGBP: Double!
var currencyJPY: Double!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
}
@IBAction func btnConvert(_ sender: Any) {
assignOutput()
if txtValue.text == "" {
self.lblCurrency.text = "Please insert value"
} else {
let inputValue = Double(txtValue.text!)!
if segOutputCurrency.selectedSegmentIndex == 0 {
let output = Double(inputValue * currencyCNY!)
self.lblCurrency.text = "\(output)¥"
} else if segOutputCurrency.selectedSegmentIndex == 1 {
let output = Double(inputValue * currencyEUR!)
self.lblCurrency.text = "\(output)€"
} else if segOutputCurrency.selectedSegmentIndex == 2 {
let output = Double(inputValue * currencyGBP!)
self.lblCurrency.text = "\(output)"
} else if segOutputCurrency.selectedSegmentIndex == 3 {
let output = Double(inputValue * currencyJPY!)
self.lblCurrency.text = "\(output)"
}
}
}
func assignOutput() {
let currencies = ["EUR", "JPY", "CNY", "USD"]
inputCurrency = currencies[segInputCurrency.selectedSegmentIndex]
Alamofire.request("https://api.exchangeratesapi.io/latest?base=\(inputCurrency!)").responseJSON { (response) in
let result = response.result
let jsonCurrencies = JSON(result.value!)
let dictContent = jsonCurrencies["rates"]
self.currencyCNY = dictContent["CNY"].double
self.currencyEUR = dictContent["EUR"].double
self.currencyGBP = dictContent["GBP"].double
self.currencyJPY = dictContent["JPY"].double
}
}
}
The expected result is that everytime the btnConvert function is called the assignInput and assignOutput functions are called and the variables are set to the right values. I am a beginner so any help would be highly appreciated.
A:
You need a completion handler in assignOutput(), I added also the minimum error handling to avoid crashes
//Variables
var inputCurrency = ""
var currencyCNY = 0.0
var currencyEUR = 0.0
var currencyGBP = 0.0
var currencyJPY = 0.0
@IBAction func btnConvert(_ sender: Any) {
assignOutput() { success in
if success {
if txtValue.text!.isEmpty {
self.lblCurrency.text = "Please insert value"
} else {
if let inputValue = Double(txtValue.text!) {
if segOutputCurrency.selectedSegmentIndex == 0 {
let output = Double(inputValue * currencyCNY)
self.lblCurrency.text = "\(output)¥"
} else if segOutputCurrency.selectedSegmentIndex == 1 {
let output = Double(inputValue * currencyEUR)
self.lblCurrency.text = "\(output)€"
} else if segOutputCurrency.selectedSegmentIndex == 2 {
let output = Double(inputValue * currencyGBP)
self.lblCurrency.text = "\(output)"
} else if segOutputCurrency.selectedSegmentIndex == 3 {
let output = Double(inputValue * currencyJPY)
self.lblCurrency.text = "\(output)"
}
} else {
self.lblCurrency.text = "Please enter a number"
}
}
} else {
self.lblCurrency.text = "Could not receive the exchange rates"
}
}
}
func assignOutput(completion: @escaping (Bool) -> Void) {
let currencies = ["EUR", "JPY", "CNY", "USD"]
inputCurrency = currencies[segInputCurrency.selectedSegmentIndex]
Alamofire.request("https://api.exchangeratesapi.io/latest?base=\(inputCurrency)").responseJSON { (response) in
if let result = response.result.value {
let jsonCurrencies = JSON(result)
let dictContent = jsonCurrencies["rates"]
self.currencyCNY = dictContent["CNY"].double
self.currencyEUR = dictContent["EUR"].double
self.currencyGBP = dictContent["GBP"].double
self.currencyJPY = dictContent["JPY"].double
completion(true)
} else {
completion(false)
}
}
}
A:
The basic idea of a completion handler is that you have some asynchronous method (i.e., a method that finishes later) and you need to give the caller the opportunity to supply what it wants the asynchronous method to do when it’s done. So, given that assignOutput is the asynchronous method, that’s the method that you would refactor with a completion handler escaping closure.
Personally, I’d configure this escaping closure to return a Result type:
For example:
func assignOutput(completion: @escaping (Result<[String: Double]>) -> Void) {
let inputCurrency = ...
Alamofire.request("https://api.exchangeratesapi.io/latest?base=\(inputCurrency)").responseJSON { response in
switch response.result {
case .failure(let error):
completion(.failure(error))
case .success(let value):
let jsonCurrencies = JSON(value)
guard let dictionary = jsonCurrencies["rates"].dictionaryObject as? [String: Double] else {
completion(.failure(CurrencyExchangeError.currencyNotFound)) // this is just a custom `Error` type that I’ve defined
return
}
completion(.success(dictionary))
}
}
}
And then you could use it like so:
assignOutput { result in
switch result {
case .failure(let error):
print(error)
case .success(let dictionary):
print(dictionary)
}
}
By using Result types, you have a nice consistent pattern where you can check for .failure or .success throughout your code.
That having been said, I’d suggest a variety of other refinements:
I wouldn’t make this view controller subclass from another view controller, ViewController. It should subclass UIViewController.
(Technically you can re-subclass your own custom view controller subclasses, but it’s exceptionally uncommon. Frankly, when you’ve got so much in your view controller subclass that you need to have subclasses of subclasses, it may be code smell indicating that you’ve got too much in your view controller.)
I’d give this view controller a class name that unambiguously indicates the type of object, e.g. CurrencyExchangeViewController, not just CurrencyExchange. This habit will pay dividends in the future, when you start breaking these big view controllers into something more manageable.
You have the list of accepted currencies in four different places:
In your storyboard for segOutputCurrency
In your storyboard for segInputCurrency
In your btnConvert routine
In your assignOutput routine
This makes your code brittle, making it easy to make mistakes if you change the order of the currencies, add/remove currencies, etc. It would be better to have a list of currencies in one place, programmatically update your UISegmentedControl outlets in viewDidLoad and then have your routines all refer back to a single array of which currencies are permitted.
You should avoid using the ! forced unwrapping operator. For example, if the network request failed and you then reference result.value!, your app will crash. You want to gracefully handle errors that happen outside of your control.
If you’re going to format currencies, remember that in addition to currency symbols, you should consider that not all locales use . for decimal place (e.g. your European users may use ,). For that reason, we would generally use NumberFormatter for converting the calculated number back to a string.
Below, I’ve just used NumberFormatter for the output, but you really should use it when interpreting the user’s input too. But I will leave that to the reader.
There’s a more subtle point when dealing with currencies, above and beyond the currency symbol, namely how many decimal places the result should display. (E.g. when dealing with Japanese yen, you generally don’t have decimal places, whereas euros and US dollars and would have two decimal places.)
You can write your own conversion routine if you want, but I might associate the chosen currency codes with Locale identifiers, that way you can leverage the symbol and the number of fractional digits appropriate for each currency. And I’d format the string representations of numbers using NumberFormatters.
The convention for outlet names is usually some functional name followed by the type of control. E.g. you might have inputTextField or currencyTextField and outputLabel or convertedLabel. Likewise, I might rename the @IBAction to be didTapConvertButton(_:)
I’d personally excise the use of SwiftyJSON, which, despite the name, feels unswifty to me. I’d use JSONDecoder.
Pulling that all together, you might end up with something like:
// CurrencyViewController.swift
import UIKit
import Alamofire
// types used by this view controller
struct Currency {
let code: String // standard three character code
let localeIdentifier: String // a `Locale` identifier string used to determine how to format the results
}
enum CurrencyExchangeError: Error {
case currencyNotSupplied
case valueNotSupplied
case currencyNotFound
case webServiceError(String)
case unknownNetworkError(Data?, HTTPURLResponse?)
}
struct ExchangeRateResponse: Codable {
let error: String?
let base: String?
let rates: [String: Double]?
}
class CurrencyExchangeViewController: UIViewController {
// outlets
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var inputCurrencySegmentedControl: UISegmentedControl!
@IBOutlet weak var outputCurrencySegmentedControl: UISegmentedControl!
@IBOutlet weak var resultLabel: UILabel!
// private properties
private let currencies = [
Currency(code: "EUR", localeIdentifier: "fr_FR"),
Currency(code: "JPY", localeIdentifier: "jp_JP"),
Currency(code: "CNY", localeIdentifier: "ch_CH"),
Currency(code: "USD", localeIdentifier: "en_US")
]
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
updateCurrencyControls()
}
@IBAction func didTapConvertButton(_ sender: Any) {
let inputIndex = inputCurrencySegmentedControl.selectedSegmentIndex
let outputIndex = outputCurrencySegmentedControl.selectedSegmentIndex
guard inputIndex >= 0, outputIndex >= 0 else {
resultLabel.text = errorMessage(for: CurrencyExchangeError.currencyNotSupplied)
return
}
guard let text = inputTextField.text, let value = Double(text) else {
resultLabel.text = errorMessage(for: CurrencyExchangeError.valueNotSupplied)
return
}
performConversion(from: inputIndex, to: outputIndex, of: value) { result in
switch result {
case .failure(let error):
self.resultLabel.text = self.errorMessage(for: error)
case .success(let string):
self.resultLabel.text = string
}
}
}
func updateCurrencyControls() {
outputCurrencySegmentedControl.removeAllSegments()
inputCurrencySegmentedControl.removeAllSegments()
enumerateCurrencies { index, code in
outputCurrencySegmentedControl.insertSegment(withTitle: code, at: index, animated: false)
inputCurrencySegmentedControl.insertSegment(withTitle: code, at: index, animated: false)
}
}
}
// these might better belong in a presenter or view model rather than the view controller
private extension CurrencyExchangeViewController {
func enumerateCurrencies(block: (Int, String) -> Void) {
for (index, currency) in currencies.enumerated() {
block(index, currency.code)
}
}
func errorMessage(for error: Error) -> String {
switch error {
case CurrencyExchangeError.currencyNotFound:
return NSLocalizedString("No exchange rate found for those currencies.", comment: "Error")
case CurrencyExchangeError.unknownNetworkError:
return NSLocalizedString("Unknown error occurred.", comment: "Error")
case CurrencyExchangeError.currencyNotSupplied:
return NSLocalizedString("You must indicate the desired currencies.", comment: "Error")
case CurrencyExchangeError.valueNotSupplied:
return NSLocalizedString("No value to convert has been supplied.", comment: "Error")
case CurrencyExchangeError.webServiceError(let message):
return NSLocalizedString(message, comment: "Error")
case let error as NSError where error.domain == NSURLErrorDomain:
return NSLocalizedString("There was a network error.", comment: "Error")
case is DecodingError:
return NSLocalizedString("There was a problem parsing the server response.", comment: "Error")
default:
return error.localizedDescription
}
}
func performConversion(from fromIndex: Int, to toIndex: Int, of value: Double, completion: @escaping (Result<String?>) -> Void) {
let originalCurrency = currencies[fromIndex]
let outputCurrency = currencies[toIndex]
fetchExchangeRates(for: originalCurrency.code) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let exchangeRates):
guard let exchangeRate = exchangeRates.rates?[outputCurrency.code] else {
completion(.failure(CurrencyExchangeError.currencyNotFound))
return
}
let outputValue = value * exchangeRate
let locale = Locale(identifier: outputCurrency.localeIdentifier)
let string = formatter(for: locale).string(for: outputValue)
completion(.success(string))
}
}
/// Currency formatter for specified locale.
///
/// Note, this formats number using the current locale (e.g. still uses
/// your local grouping and decimal separator), but gets the appropriate
/// properties for the target locale's currency, namely:
///
/// - the currency symbol, and
/// - the number of decimal places.
///
/// - Parameter locale: The `Locale` from which we'll use to get the currency-specific properties.
/// - Returns: A `NumberFormatter` that melds the current device's number formatting and
/// the specified locale's currency formatting.
func formatter(for locale: Locale) -> NumberFormatter {
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = locale
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currencyFormatter.currencyCode
formatter.currencySymbol = currencyFormatter.currencySymbol
formatter.internationalCurrencySymbol = currencyFormatter.internationalCurrencySymbol
formatter.maximumFractionDigits = currencyFormatter.maximumFractionDigits
formatter.minimumFractionDigits = currencyFormatter.minimumFractionDigits
return formatter
}
}
}
// this might better belong in a network service rather than in the view controller
private extension CurrencyExchangeViewController {
func fetchExchangeRates(for inputCurrencyCode: String, completion: @escaping (Result<ExchangeRateResponse>) -> Void) {
Alamofire.request("https://api.exchangeratesapi.io/latest?base=\(inputCurrencyCode)").response { response in
guard response.error == nil, let data = response.data else {
completion(.failure(response.error ?? CurrencyExchangeError.unknownNetworkError(response.data, response.response)))
return
}
do {
let exchangeRates = try JSONDecoder().decode(ExchangeRateResponse.self, from: data)
if let error = exchangeRates.error {
completion(.failure(CurrencyExchangeError.webServiceError(error)))
} else {
completion(.success(exchangeRates))
}
} catch {
completion(.failure(error))
}
}
}
}
As indicated in the comments above, I’d probably move some of that stuff in the extensions into different objects, but I suspect even the above changes are a bit much to take in at one time, so I’ve stopped my refactoring there.
|
[
"stackoverflow",
"0013561483.txt"
] | Q:
Solve syntax error "unexpected identifier dmap" with visual studio express 2012
Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
I am compiling Palabos with visual studio 2012.
I get the following error:
Warning 1 warning C4346: 'plb::ExtractDynamicsChainFunctional2D::DMap' : dependent name is not a type c:\users\max\desktop\drawing\c++\palabos\src\dataprocessors\metastufffunctional2d.hh 100 1 Drawing
Error 2 error C2061: syntax error : identifier 'DMap' c:\users\max\desktop\drawing\c++\palabos\src\dataprocessors\metastufffunctional2d.hh 100 1 Drawing
The code causing this error is:
/* ******** ExtractDynamicsChainFunctional2D ************************************ */
template<typename T, template<typename U> class Descriptor>
ExtractDynamicsChainFunctional2D<T,Descriptor>::ExtractDynamicsChainFunctional2D (
ExtractDynamicsChainFunctional2D<T,Descriptor>::DMap const& dynamicsMap_,
pluint maxChainSize_ )
: dynamicsMap(dynamicsMap_),
maxChainSize(maxChainSize_)
{ }
My knowledge of c++ is very limited. Can somebody explain what is causing this error, and how I can fix it.
A:
The error means: ExtractDynamicsChainFunctional2D<T,Descriptor>::DMap is by default not a type and cannot be used as such. If you want it to be recognised as a type, you have to put typename in front of it.
The problem occurs only inside a templated code, where you want to access a member type of another template.
|
[
"stackoverflow",
"0059714898.txt"
] | Q:
Convert timestamp to interval in postgresql
I am trying to convert a timestamp to interval & expecting an out of hh:mm only.
My code is like below
SELECT to_timestamp('2020-01-10 08:00', 'YYYY-MM-DD hh24:mi')::timestamp without time zone
at time zone 'Asia/Calcutta'
at time zone 'Etc/UTC'
Actual purpose of the code is change the time zone into utc for a given date time value.
A:
It seems you are trying to get the timedifference (interval) between two timezones at a specific time.
This can be done like this for example:
SELECT to_timestamp('2020-01-10 08:00', 'YYYY-MM-DD hh24:mi')::timestamp without time zone
at time zone 'Asia/Calcutta'
-
to_timestamp('2020-01-10 08:00', 'YYYY-MM-DD hh24:mi')::timestamp without time zone
at time zone 'Etc/UTC'
This returns an interval = -05:30:00
You can of course convert it to hours and minutes with the to_char function, but that returns string, not interval.
Best regards,
Bjarni
|
[
"scifi.stackexchange",
"0000009069.txt"
] | Q:
Who is the man we saw at the end of season 4 episode 8 of Fringe?
At the end of episode 8 of season 4 of Fringe (Back To Where You've Never Been), Col. Boyle called a man to advise him that (the alternate version of) Olivia and Lincoln Lee are coming.
Who is that man? The preview of the next episode indicates that he his not a new character.
A:
He is David Robert Jones, an antagonist from Season 1. He worked with ZFT and The Pattern using the advanced science and technology that Walter and William Bell created to prepare "recruits" (people who had potential for super-human powers, including Olivia) Over Here for the coming war with Over There. In so doing, he broke numerous laws, was chased down by the Fringe Team, and in the end was killed by Peter cutting him in half by turning off the portal he was traversing (as mentioned in S4E8).
Note: All of the above were witnessed in the original (S1-S3) timeline Over Here, it's unknown what the history of the David Robert Jones shown at the end of Fringe S4E8 is, as we haven't seen that timeline. In addition, we don't know if this is "Over Here's" David Jones, or if it's "Over There's" David Jones.
|
[
"stackoverflow",
"0010533421.txt"
] | Q:
Accessing 64 bit registry from 32 bit application
I need to open a registry entry "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F86416024FF}" in c++. It contains the java 64 bit application. The full path of that registry entry is "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{26A24AE4-039D-4CA4-87B4-2F86416024FF}".
We can view this path through regedit. I use
returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F86416024FF}"),
0, KEY_ALL_ACCESS, &hKey)
for open the registry; But it returns error value (2).
returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")...
returns a success result. What can i do?
A:
The registry keys for 32 bit and 64 applications are separated, you can't access (directly) the 64 bit registry from your 32 bit application. In your case the required hive doesn't exist in the 32 bit part of the registry then you can access the parent folder only.
From MSDN:
On 64-bit Windows, portions of the registry entries are stored separately for 32-bit application and 64-bit applications and mapped into separate logical registry views using the registry redirector and registry reflection, because the 64-bit version of an application may use different registry keys and values than the 32-bit version. There are also shared registry keys that are not redirected or reflected.
You can read the list on MSDN: Registry Keys Affected by WOW64. Unfortunately the SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall is not mentioned but it's affected too.
Solution
What you have to do is to explicitly ask RegOpenKeyEx to access the 64 bit part of the registry. This can be done adding the KEY_WOW64_64KEY flag to your call (you can access the 32 bit registry from a 64 bit application using KEY_WOW64_32KEY). Please note that this flag is not supported on Windows 2000 then if your application must be compatible with that (old) version you have to manage the case.
See this link on MSDN for further details: Accessing an Alternate Registry View.
To make it easy, simply change your call from:
returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F86416024FF}"),
0, KEY_ALL_ACCESS, &hKey);
to:
returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F86416024FF}"),
0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &hKey);
Note
Note that you may access the key only via its path without any flags using this HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall.
Because the Wow6432 node is the virtualized node used by WOW64 but you shouldn't rely on this, it's stable but it should be considered an implementation detail subject to change.
References
- Registry Virtualization on MSDN.
- Readers my find interesting tips on this post: http://poshcode.org/2470, it's for the PowerShell but it explains how to access WMI data (relative to the 64 bit registry part) from a 32 bit application.
|
[
"stackoverflow",
"0057119312.txt"
] | Q:
How Do I Avoid Repeating A Variable In Terraform?
Terraform doesn't allow you to interpolate variables within the variables file otherwise you get the error:
Error: Variables not allowed
on variables.tf line 9, in variable "resource_group_name": 9:
default = "${var.prefix}-terraform-dev_rg"
Variables may not be used here.
This then means I end up duplicating the value of the prefix in my variables.tf file when I try to create the name for the resource group.
Is there a nice way around this to avoid duplicating the value of the variable?
variables.tf
variable "prefix" {
description = "The prefix used for all resources in this plan"
default = "terraform-dev"
}
variable resource_group_name {
type = "string"
default = "terraform-dev_rg"
}
variable resource_group_location {
type = "string"
default = "eastus"
}
main.tf
# Configure the Microsoft Azure Provider
provider "azurerm" {
version = "=1.28.0"
}
# Create a resource group
resource "azurerm_resource_group" "resource-group" {
name = var.resource_group_name
location = var.resource_group_location
}
#Create an application gateway with web app firewall
module "firewall" {
source = "./firewall"
resource_group_name = var.resource_group_name
resource_group_location = var.resource_group_location
}
./firewall/variables.tf
#Passed down from the root variables.tf
variable "prefix" {}
variable "resource_group_name" {}
variable "resource_group_location" {}
./firewall/main.tf
# Create a virtual network for the firewall
resource "azurerm_virtual_network" "firewall-vnet" {
name = "${var.prefix}-waf-vnet"
address_space = ["10.0.0.0/16"]
resource_group_name = var.resource_group_name
location = var.resource_group_location
}
A:
Try to use local values,
https://www.terraform.io/docs/configuration/locals.html
variable "prefix" {
description = "The prefix used for all resources in this plan"
default = "terraform-dev"
}
variable resource_group_location {
type = "string"
default = "eastus"
}
locals {
resource_group_name = "${var.prefix}_rg"
}
resource "azurerm_resource_group" "resource-group" {
name = local.resource_group_name
location = var.resource_group_location
}
|
[
"pm.stackexchange",
"0000029604.txt"
] | Q:
How to calculate Schedule Variance in Scrum with story points?
I am trying to find a way to calculate the schedule variance for the scrum. I was trying to found a similar question here on StackExchange, but Yet I didn't found any. So I have posted it here.
Below is how we count the schedule variance.
For example, If a sprint has 3 stories and each has 5 story points. Only 2 stories get completed at the end of the sprint, then The Schedule Variance would be 66.67 (10/15*100).
Is this a good way to go with the calculation? Or do we have any other way to calculate schedule variance in scrum?
A:
What you're trying to do makes no sense.
The first problem is that story points have no relation to time. Story points are a measure of effort needed or complexity. Something that requires a lot of effort may be something that can also be done very quickly. However, something that is estimated to be a very small amount of effort may be done with the same amount of working time or much longer. You simply can't compare an estimate of effort or complexity to time.
The second is that Scrum doesn't have the concept of a project schedule. In Scrum, each Sprint is a timeboxed activity that could be viewed as a project. At the end of the timebox, work is either done or not done. You deliver at least one potentially releasable Increment every Sprint. The only variance is in the scope of what is delivered and rarely, if ever, in the minimum frequency of delivery.
I would recommend assessing why you wish to use schedule variance. I do not believe that it is appropriate for situations that Scrum, and other Agile methods, are appropriate. Agile methods are best used when there is a good deal of uncertainty. With uncertainty, it's not effective to make long term plans that you would use to calculate variances against.
|
[
"stackoverflow",
"0058612833.txt"
] | Q:
Split list of dictionaries into list of lists with list length based on a key value pair inside the dictionary
I have a list of dictionaries, sorted by a given key/value 'weight'. I want to group these together for example so that weight never exceeds 20, and each list shouldn't exceed a length of 5, but gets as close as possible per dict group. The input would look like this:
[{'name': 'A', 'weight': 1},
{'name': 'B', 'weight': 1},
{'name': 'C', 'weight': 1},
{'name': 'D', 'weight': 1},
{'name': 'E', 'weight': 1},
{'name': 'F', 'weight': 1},
{'name': 'G', 'weight': 5},
{'name': 'H', 'weight': 5},
{'name': 'I', 'weight': 5},
{'name': 'J', 'weight': 10},
{'name': 'K', 'weight': 10},
{'name': 'L', 'weight': 20},
{'name': 'M', 'weight': 20},
]
And the output should look like this:
[
[
{'name': 'A', 'weight': 1},
{'name': 'B', 'weight': 1},
{'name': 'C', 'weight': 1},
{'name': 'D', 'weight': 1},
{'name': 'E', 'weight': 1}
],
[
{'name': 'F', 'weight': 1},
{'name': 'G', 'weight': 5},
{'name': 'H', 'weight': 5},
{'name': 'I', 'weight': 5}
],
[
{'name': 'J', 'weight': 10},
{'name': 'K', 'weight': 10}
],
[
{'name': 'L', 'weight': 20}
],
[
{'name': 'M', 'weight': 20}
]
]
Another catch is that I'd like to be able to limit the max number of
I fiddled around with some list comprehension, and I have
out = [dict_list[i:i + 5] for i in range(0, len(dict_list), 5)] which allows me to split by 5, but I'm having trouble figuring out how to get the lists weighted.
A:
You can keep appending the dict in the input list to the last sub-list of the output list in a for loop, but create a new sub-list if the output list is empty, the weight sum of the last sub-list plus the current item exceeds 20, or the size of the last sub-list is already 5. This would cost only O(n) in time complexity:
output = []
for item in lst:
if not output or last_sum + item['weight'] > 20 or len(output[-1]) == 5:
output.append([])
last_sum = 0
output[-1].append(item)
last_sum += item['weight']
output becomes:
[[{'name': 'A', 'weight': 1},
{'name': 'B', 'weight': 1},
{'name': 'C', 'weight': 1},
{'name': 'D', 'weight': 1},
{'name': 'E', 'weight': 1}],
[{'name': 'F', 'weight': 1},
{'name': 'G', 'weight': 5},
{'name': 'H', 'weight': 5},
{'name': 'I', 'weight': 5}],
[{'name': 'J', 'weight': 10},
{'name': 'K', 'weight': 10}],
[{'name': 'L', 'weight': 20}],
[{'name': 'M', 'weight': 20}]]
Demo: https://repl.it/@blhsing/ForcefulIroncladEmulation
|
[
"stackoverflow",
"0007330378.txt"
] | Q:
Trap the window close event
I am facing the problem to logout my page. I calls the logout method from the tag of the page like this
<body onbeforeunload="beforeLogout();" onUnload="logout('/ruxamod/faces/zzrucmpvhs1.xhtml?logout=t');" onclick="hideDescFrame();">
but I have no idea how to trap the window close button is clicked because all these methods are call when user refresh the page.
Thanks
A:
I have no idea how to trap the window close button is clicked
As far as I know, there is no way to do this. You can't find out the reason why the document is getting unloaded.
You may be able to catch this by frequently polling from the opener document whether the window is still open.
Alternatively, you could consider using an inline dialog like jQuery UI dialog where you can catch all events.
|
[
"stackoverflow",
"0015519410.txt"
] | Q:
How to run a callback function on a jQuery trigger("click")?
I need to trigger a custom event in the callback of a trigger call, but I can't get it to work.
I tried this:
var $input = $( ".ui-popup-container" ).find( "input" ).eq(2);
function runtests () {
console.log("clicked the input");
};
$input.trigger('click', runtests());
and this:
var $input = $( ".ui-popup-container" ).find( "input" ).eq(2);
$input.trigger('click', function(){
console.log("clicked the input");
}
Neither of which works.
Question:
How do I get a callback function to run when I'm triggering a click on an element?
A:
When you call trigger, the bound event handler is immediately executed, so you don't need any callback. Just use
$input.trigger('click');
runtests();
A:
Yes - It is true that trigger doesn't take callback but we can pass callback as parameter.
//.trigger( eventType [, extraParameters ] )
$("#element").bind("customCall", function(e, callback){
callback();
}
var callback = function(){alert("Hello");}
$("#element").trigger("customCall",[callback]);
Hope this will helps
A:
First you need to bind the click event and then you can trigger the click event.
$input.bind('click', function() {
console.log("clicked the input");
});
$input.trigger('click');
|
[
"stackoverflow",
"0005680094.txt"
] | Q:
Drupal 6 - error message for custom login form remains empty
I'm using garland's theme for my Drupal 6 administrator. I added a template called: page-user-login.tpl.php which I can access from mywebiste.com/user/login. Inside the template I simply added:
<html ...>
<head>
<?php print $head ?>
<?php print $styles ?>
</head>
<body>
<?php
print drupal_get_form('user_login_block');
print $messages;
?>
</body>
</html>
The login form gets displayed and is working correctly for existing users.
However, if a user doesn't exists, no messages are displayed on the page. I tried using "theme_status_messages" and "drupal_get_messages" but they always are empty. What should I do in order to get the return error message?
PS: I'm creating a custom login page because it needs a complete different design than all the other pages.
A:
The user login form is already loaded up in the $content variable.
<?php print $content; // instead of print drupal_get_form(... ?>
I had a similar page override, so I just dropped in your method and confirmed errors do not display (user field does highlight red though). Errors do display when I print $content though.
My guess is it has to do with 2 of the same form being retrieved in the same page request.
|
[
"math.stackexchange",
"0003478463.txt"
] | Q:
Solve $y(1+xy)dx + x(1+xy+x^2y^2)dy = 0$
I came across this question in of my textbook, I tried solving it but i got stuck here.
Please help me complete solving it.
My approach:
For given eq I've tried to check if it's a exact differential equation but it was not. I got $\frac{\partial{M}}{\partial{y}} \ne \frac{\partial{N}}{\partial{x}}$
Then I try to reduce the given eq to exact differential equation by finding Integrating Factor (I.F).
I.F = $\frac{1}{Mx - Ny}$
Then I multiplied I.F with given equation to convert it into exact differential equation. After, I tried to check the condition $\frac{\partial{M}}{\partial{y}} = \frac{\partial{N}}{\partial{x}}$ but I got $\frac{\partial{M}}{\partial{y}} \ne \frac{\partial{N}}{\partial{x}}$.
What am I doing wrong here?
A:
$$y(1+xy)dx + x(1+xy+x^2y^2)dy = 0\tag1$$
Comparing $(1)$ with $~Mdx+Ndy=0~$, we have
$$M=y(1+xy)\qquad\text{and}\qquad N=x(1+xy+x^2y^2)$$
showing that $(1)$ is of the form $$f_1(xy)~y~dx+f_2(xy)~x~dy=0~.$$
Again $~Mx-Ny=xy(1+xy)-xy(1+xy+x^2y^2)=-x^3y^3\ne 0~$.
Hence the integrating factor (I.F.) is $~\dfrac{1}{Mx-Ny}=-\dfrac{1}{x^3y^3}~$.
Multiplying both side of $(1)$ by I.F. we have
$$\dfrac{1}{x^3y^2}(1+xy)dx + \dfrac{1}{x^2y^3}(1+xy+x^2y^2)dy = 0$$
$$\left[\dfrac{1}{x^3y^2}+\dfrac{1}{x^2y}\right]dx + \left[\dfrac{1}{x^2y^3}+\dfrac{1}{xy^2}+\dfrac{1}{y}\right]dy = 0$$
$$d\left(-\dfrac{1}{2x^{2}y^{2}}-\dfrac1{xy}+\ln y\right) = 0$$
Integrating we have
$$-\dfrac{1}{2x^{2}y^{2}}-\dfrac1{xy}+\ln y=c$$where $~c~$ is integrating constant.
|
[
"stackoverflow",
"0009695279.txt"
] | Q:
Serial Console Driver as a Loadable Module
Can a linux 2.6 serial console driver that registers itself using the console_initcall() macro be developed as a loadable module or must it be compiled in-kernel?
A:
As described in the kernel documentation there needs to be a system console driver which is called during the initialization phase.
So if you want default system console support for the serial drivers, you need to have them in-kernel. See drivers/tty/serial/Kconfig for the existing drivers.
This discussion might be also interesting for you.
|
[
"stackoverflow",
"0040277959.txt"
] | Q:
Angular2 event binding, can it be done without '(' & ')', Property binding can it be done without '[' & ']'
I wonder if there is any way to achieve the event and the property binding without using parenthesis or brackets?
Reference : https://angular.io/docs/ts/latest/guide/template-syntax.html#!#event-binding
<input [value]="currentHero.firstName"
(input)="currentHero.firstName=$event.target.value" >
In Angular2 for event-binding we need '(event-type)', looking for some way to perform the same
In Angular2 for property-binding we need '[property-value]', looking for some way to perform the same functionality.
Can this be done the way normal DomElements, because '[]' & '()' is not a valid Html attributes..!
Edit:
function:
getDomElement(model:Object){
//...some logic to control the elemet generation
return {text-type-InputElement};// ..only returns elemnts(eg: <input type="text"/>)
}
var type = getDomElement(elem).type; // .. will give us TEXT
var tagName = getDomElement(elem).tagName;//.. will give us INPUT
Using the above returned DomElement, I am trying to perform element.setAttribute("[(ngModel)]","model.firstName").
Which is not possible, any alternatives to achieve this.
A:
<input bind-value="currentHero.firstName"
on-input="currentHero.firstName=$event.target.value" >
See https://angular.io/docs/ts/latest/guide/template-syntax.html (search for "canonical")
|
[
"meta.stackexchange",
"0000085498.txt"
] | Q:
Is it possible to add images to comments?
I was wondering if it is possible to post a comment with an image.
Recently, during a question about data-visualization in Cross Validated, there was a controversy about using one type of chart for another.
I had posted a question about pie-charts, after reading some references I decided to build an example and clarify the point of using waffle-chart vs pie-chart. In a way, my example was not an answer it was more properly a comment on waffle-charts. But it seems to be impossible to post a comment with an image (Maybe, there is a way but I can't figure out how).
I don't know if it is relevant to post images in comments in other SO sites. So, if there is no way to post images in comments... why not making it possible? And if there is a way to post an image with a comment, how I can do it?
A:
You can't (see How do comments work?). The only formatting allowed in comments is things that change a single line (bold, code, etc.). Things that take up multiple lines aren't available, because comments don't span blocks like posts do. Along the same thinking, comments have a fairly low character limit. All of this serves to keep comments compact; adding images lets you make huge comments, and posts can have dozens or hundreds of comments:
If you really need an image, just link to it in the comment and people can click through
A:
A work around is to start a new answer or question, use the image upload button to get the images into the stakcoverflow imgur account, then take the links and link to the images from your comments. Discard the answer or question you started.
|
[
"stackoverflow",
"0063040124.txt"
] | Q:
How to use list comprehension to create a list from a dictionary
I Have this object:
myObj = [{'city':'New York', 'number': 5550}, {'city':'San Francisco', 'number': 0565}]
How could I use list comprehension to store only the _city_ attribute in the list below:
my_new_list = [ HERE THE LIST COMPREHENSION ]
Output should be: "New York", "San Francisco"
A:
Try this:
my_new_list = [item['city'] for item in myObj]
The item value would be {'city':'New York', 'number': 5550} the first time and {'city':'San Francisco', 'number': 0565} the second time. Since these are dictionaries, we can use item['city'] to access the city value from each dictionary.
|
[
"stackoverflow",
"0055589014.txt"
] | Q:
npm can't find package.json when running docker container with compose
I am trying to wire up my Angular 7 client app into docker compose locally.
I get the following error when I docker-compose up:
client-app | npm ERR! errno -2
client-app | npm ERR! syscall open
client-app | npm ERR! enoent ENOENT: no such file or directory, open '/app/package.json'
Dockerfile:
FROM node:9.6.1
RUN mkdir -p /app
WORKDIR /app
EXPOSE 4200
ENV PATH /app/node_modules/.bin:$PATH
COPY . /app
RUN npm install --silent
RUN npm rebuild node-sass
CMD ["npm", "run", "docker-start"]
The compose part for the client is:
client-app:
image: ${DOCKER_REGISTRY-}client
container_name: client-app
ports:
- "4200:81"
build:
context: .
dockerfile: ClientApp/Dockerfile
package.json is in the ClientApp folder along-side Dockerfile, I would assume COPY . /app should copy the package.json to the container. I don't have any excludes in dockerignore. I am using Docker for Windows with Unix containers. I tried npm init before (but that will create an empty package.json anyway) and looked through the SO posts but most of the dockerfile definitions look exactly the same. I also tried: COPY package*.json ./ additionally and building the image with --no-cache.
A:
Your Dockerfile is fine, and COPY package*.json ./ is not necessary - its being copied with your entire app.
The problem is in your docker-compose file.
you defined:
build:
context: .
dockerfile: ClientApp/Dockerfile
that means, your Dockerfile will accept the docker-compose context, which is 1 directory above:
├── docker-compose.yml -- this is the actual context
└── ClientApp
├── Dockerfile -- this is the expected context
so when the CMD is running, it is 1 directory above the package.json, therefore it cannot run the command and the container exits.
to fix it, give your docker-compose file the correct context:
build:
context: ClientApp
dockerfile: Dockerfile
and it should work.
|
[
"stackoverflow",
"0030378176.txt"
] | Q:
Can I change CSS style after HTML load in multiple places
I have HTML code the loads a grid of images. The images have a box-shadow around them. Each image is loaded one by one on the grid, but they are all using the same style sheet. I want to make each box-shadow a different colour for the images. Is this possible?
I tried to test this a simple way by making each alternate image's shadow a different colour, but it only uses the last image's colour that is loaded for all of the images. Here is how I tested it:
//i is defined outside this
if($i == 0){
//I am using PHP to print out the HTML
Echo "<style> ul.rig li { box-shadow: 0 0 10px #2de61c; }</style>";
$i++;
}else if($i == 1){
Echo "<style> ul.rig li { box-shadow: 0 0 10px #ed1515; }</style>";
$i--;
}
Whatever i equals for the last loaded image, the rest of the image's shadows will have that colour. Is it possible to alternate/have different colours like this?
A:
Just use nth-child CSS.
ul.rig li:nth-child(odd) { box-shadow: 0 0 10px #2de61c; }
ul.rig li:nth-child(even) { box-shadow: 0 0 10px #ed1515; }
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
|
[
"math.stackexchange",
"0001083516.txt"
] | Q:
Trigonalise a matrix
Let $\mathbf{A}=\begin{bmatrix}
0 & 1 & 1 \\
-1 & 1 & 1 \\
-1 & 1 & 2
\end{bmatrix}$
Trigonalise a matrix
Could someone trigonalise this matrix in details way, i wanna see the difference between yours and the french one
to start here's $P_{1}(\lambda)=(\lambda -1)^3$
note that some authors in book's frnech use :
$$T = \left( \begin{array}{ccc} \lambda_{1} & 1 & 0 \\ 0 & \lambda_{2} & 1 \\ 0 & 0 & \lambda_{3} \\ \end{array} \right)$$
and other use $$T = \left( \begin{array}{ccc} \lambda_{1} & a & b \\ 0 & \lambda_{2} & c \\ 0 & 0 & \lambda_{3} \\ \end{array} \right)$$
im wondering wich way that you using in usa english's books
A:
From @Ian's comment below, the author appears to be saying to "make triangular by similarity transformations", which gives something of the form (or like you added to the comment).
$$T = \left( \begin{array}{ccc} \lambda_{1} & a & b \\ 0 & \lambda_{2} & c \\ 0 & 0 & \lambda_{3} \\ \end{array} \right)$$
We try two things: $1.)~$ Diagonalize when possible, and if that fails, $2.)~$ Find the Jordan Normal Form.
For this specific problem, we have:
$$\mathbf{A}=\begin{bmatrix}
0 & 1 & 1 \\
-1 & 1 & 1 \\
-1 & 1 & 2
\end{bmatrix}$$
We find the characteristic polynomial and eigenvalues using $|A - \lambda I| = 0$, resulting in:
$$-\lambda ^3+3 \lambda ^2-3 \lambda +1 = 0 \implies -(-1 + \lambda)^3 = 0 \implies \lambda_{1, 2, 3} = 1$$
Next, we want to find three linearly independent eigenvectors using $[A- \lambda I]v_i = 0$, but this is not always possible due to algebraic and geometric difference (deficient matrices), so we have to resort to generalized eigenvectors.
So, we have $[A - \lambda_1 I]v_1 = [A -I]v_1 = 0$ as:
$$\left(
\begin{array}{ccc}
-1 & 1 & 1 \\
-1 & 0 & 1 \\
-1 & 1 & 1 \\
\end{array}
\right)v_1 = 0$$
If we put that in row-reduced-echelon-form (RREF), we arrive at:
$$\left(
\begin{array}{ccc}
1 & 0 & -1 \\
0 & 1 & 0 \\
0 & 0 & 0 \\
\end{array}
\right) v_1 = 0$$
This only provides one linearly independent eigenvector as:
$$v_1 = \begin{pmatrix} 1 \\ 0 \\ 1 \end{pmatrix}$$
Now, we need to find two more generalized eigenvectors and there are many approaches to that. One approach is to try $[A - \lambda I]v_2 = v_1$, yielding an augmented RREF of:
$$\begin{pmatrix} 1 & 0 & -1 & 0 \\ 0 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 \end{pmatrix}$$
This yields $a = c, b = 1$, so choose $c = 0$, thus:
$$v_2 = \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}$$
Repeating this process, we set up and solve $[A - I]v_3 = v_2$, yielding an augmented RREF of:
$$\begin{pmatrix} 1 & 0 & -1 & -1 \\ 0 & 1 & 0 & -1 \\ 0 & 0 & 0 & 0 \end{pmatrix}$$
This yields $a = -1 + c, b = -1$, so choose $c = 0$, thus:
$$v_3 = \begin{pmatrix} -1 \\ -1 \\ 0 \end{pmatrix}$$
We can now form $P = (v_1~|~v_2~|~v_3)$ as:
$$P = \begin{pmatrix} 1 & 0 & -1 \\ 0 & 1 & -1 \\ 1 & 0 & 0 \end{pmatrix}$$
This yields the Jordan Normal Form:
$$T = PAP^{-1} = \left( \begin{array}{ccc} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \\ \end{array} \right)$$
Note: there are various ways to solve these problems.
You want to look for references with the Jordan Normal Form.
You can sometimes infer $T$ (see references below).
Some sources for generalized eigenvectors and the Jordan Normal Form are:
Wiki
Notes 1
Notes 2
Jordan Normal Form and Chaining
Book - Abstract Algebra by Dummit and Foote
Books - many books on linear algebra
|
[
"music.stackexchange",
"0000101796.txt"
] | Q:
Rules for making guitar chords playable on the fretboard
Background: A program that generates common chord progressions given a key. For example, in the key of C major, one of the popular progressions we have is I – vi – IV – V (C – Am – F – G). My goal is to render these 4 chords from the neck of the guitar onto the screen.
Let's say I have a C chord and I want to figure out playable positions for it on the guitar fretboard starting at the open string position. The C major triad consists of [C, E, G]. I came up with the following chord that marks all the [C, E, G] notes from fret 0 (open string position) to fret 3
Now this is obviously wrong but It has all the required notes by the C major triad (please disregard multiple notes on the same string, as I am still working on this program). Is there a set of "rules" or heuristics I can use to figure out which fretted notes sound good as a chord while played together with other chords in the progression? For example, if I play the C chord from above, then Am, F and G, it sounds a bit dissonant compared to playing x32010 which sounds a bit cleaner. I think one of the rules is that the chord always needs to start at the root position, this would eliminate the low E string, because the root note is not E or G.
Do inversions play a role in this?
A:
The rules are thus:
Can you play it? Like, physically, can your fingers reach the notes and can they do so consistently in the context of a song as chords are changing? This sounds obvious but it's important because sometimes "closed" voicings can be tough on a guitar fretboard especially when you get into seventh chords. This rule invalidates your "always needs to start at the root position" premise. Inversions and "drop" chords are essential both for voice leading and the simple practicality of being able to reach all the notes. You only have 4 fretting fingers and the fact that you can only sound 1 note per string makes compromises necessary.
Does it sound good? Some voicings, even if they technically contain all the required notes, don't sound good. Sometimes it's because two notes are too close together, sometimes it's because a certain note doesn't sound good in the root, and sometimes the register just makes it sound too muddy or shrill. Also the context is important. You usually want to "voice lead" the changes which means to consider each individual note as its own voice or part that should change either minimally or melodically as the chord changes. For instance imagine your four fingers are a barber shop quartet each singing their own part. Each finger should form a melodic line but together they should form a chord. In practice, this usually means that if two adjacent chords share a note, then that finger should stay put and the others should move as minimally as possible. But what does your ear say, does it sound good?
Does it fulfill the functional harmonic purpose? You don't have to include all the notes. For instance you might read somewhere that a 13th chord includes the 1, 3, 5, 7, 9, 11, and 13. But, in reality, that rarely happens. You might have 4 or so of those notes that conveys that chord. And that chord is one of a series where one chord leads to another for a harmonic purpose. It serves a function in that it leads you to the next chord and the totality of which leads you from beginning to the end making a meaningful harmonic progression. So, did you include the notes that fulfill that? In other words—even outside of functional harmony—the song calls for a particular chord for a particular purpose. Does it fulfill that purpose?
|
[
"stackoverflow",
"0038712042.txt"
] | Q:
How to make Jersey ignore ssl certificate error?
Error Trace :
javax.ws.rs.ProcessingException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target##
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:701)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:697)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
at com.nextlabs.openaz.rest.RestClient.execRequest(RestClient.java:49)
at com.nextlabs.openaz.RestClientTest.test(RestClientTest.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:394)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
... 36 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 51 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 57 more
Like all other client like apache httpclient, by default, Jersey checks SSL certificate, which is correct way. But in some cases, like development phase, highly probability is that we don't have CA trusted SSL certificate. So question is, how can we make Jersey ignore SSL certificate error?
A:
Please note that trusting all certificates is extremely risky. Be careful when doing it.
The following piece of code is not much different from the one shown in yukuan's answer. However, the following solution uses only the JAX-RS Client API. In theory, it should work with other JAX-RS implementations too:
TrustManager[] trustManager = new X509TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, null);
Client client = ClientBuilder.newBuilder().sslContext(sslContext).build();
Note 1: At the time of writing, the standard solution described above won't work with RESTEasy. RESTEasy delegates HTTP calls to HttpClient from the Apache HttpComponents project. To trust all certificates with RESTEasy, the HttpClient must be customized. For more details, have a look at this answer.
Note 2: You may find https://badssl.com a useful resource to test clients against bad SSL configs.
|
[
"stackoverflow",
"0032952957.txt"
] | Q:
Redirect /search?query=foo to /search/foo
I am trying to redirect /search?query=foo to /search/foo but all my attempts have failed.
I have tried the solutions in similar questions but they have not worked. I believe this is because I am trying to rewrite the request to index.php so that the PHP framework can process it.
I know that it is not the PHP framework causing the issue as when I manually go to /search/foo it is handled correctly.
My .htaccess looks like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/search$
RewriteCond %{QUERY_STRING} ^query=(.*)$
RewriteRule ^ search/%1 [R=302,NS]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
I don't understand why it's not working as when I look at the logs the URL is successfully being transformed into what I'm after:
applying pattern '^' to uri 'search'
RewriteCond: input='/search' pattern='^/search$' => matched
RewriteCond: input='query=asd' pattern='^query=(.*)$' => matched
rewrite 'search' -> 'search/asd'
add per-dir prefix: search/asd -> .../app/public/search/asd
explicitly forcing redirect with http://localhost/.../app/public/search/asd
A:
You need to get rid of the query string. Instead of:
RewriteCond %{REQUEST_URI} ^/search$
RewriteCond %{QUERY_STRING} ^query=(.*)$
RewriteRule ^ search/%1 [R=302,NS]
Try:
RewriteCond %{THE_REQUEST} \ /+search\?query=([^&\ ]+)
RewriteRule ^ search/%1? [L,R=302,NS]
The important part is the ? after the backreference, %1. This tells mod_rewrite that the new query string is just ? (i.e. nothing). Othewise the existing query string automatically gets appended to the rewritten URL/redirect.
|
[
"stackoverflow",
"0057021245.txt"
] | Q:
Could not find com.android.tools.build:gradle:3.0.1. project from Github
I would like to open ten https://github.com/mukundmadhav/Wordpress-to-Android-app project in Android Studio. However, I have a problem.
I'm getting errors
ERROR: Could not find com.android.tools.build:gradle:3.0.1.
Searched in the following locations:
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.jar
Required by:
project :
Add Google Maven repository and sync project
Open File
I tried to solve the problem with these methods
Gradle 4.1 issue on latest android studio 3.0.1
Could not find com.android.tools.build:gradle:3.0.1
Could not find com.android.tools.build.gradle:3.0.0-alpha7
However, nothing helped, does anyone know how to open this project?
Update:
Android Version 3.4.1
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url "https://maven.google.com" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
A:
There should be google() repo in repositories which searches plugins/libraries in google repository.
Also, version number for com.android.tools.build should match the Android Studio Version. For example: for Android studio 3.4.1, classpath dependency should be:
classpath 'com.android.tools.build:gradle:3.4.1'
Here is the modified code for build.gradle.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
|
[
"stackoverflow",
"0061231738.txt"
] | Q:
Publish to Azure web app sub application fails with 409 error
We're in the process of migration our product to the cloud. I'm currently testing the deployment of our web application to azure web apps. Our application consists of 2 parts. An ASP.Net Webforms application, and a ASP.Net Web API project. These projects are 2 separate applications, and need to run in azure as 2 separate applications. I've configured the web app as follows:
As you can see, the api is a sub application of the root. Now I have 2 deployment tasks (AzureRmWebAppDeployment@4), that deploy the website and API. The task to deploy the website runs without any issues. However, the task to deploy the api throws an error:
Got service connection details for Azure App Service:'***'
##[error]Error: Failed to create path 'site/wwwroot/api' from Kudu. Error: Conflict (CODE: 409)
Successfully added release annotation to the Application Insight : ***
Successfully updated deployment History at https://***.scm.azurewebsites.net/api/deployments/***
App Service Application URL: http://***.azurewebsites.net/api
Finishing: Publish API to Azure
Apparently it cannot create the "api" folder in wwwroot.
The diagnostic logging shows that it determines the "api" folder doesn't exist, and a conflict error occurs when trying to create it:
##[debug]Virtual Application Map: Physical path: 'site\wwwroot\api'. Virtual path: '/api'.
##[debug][GET]https://$***:***@***.scm.azurewebsites.net/api/vfs/site/wwwroot/api/
##[debug]loaded affinity cookie ["ARRAffinity=***;Path=/;HttpOnly;Domain=***.scm.azurewebsites.net"]
##[debug]listFiles. Data: {"statusCode":404,"statusMessage":"Not Found","headers":{"cache-control":"no-cache","pragma":"no-cache","content-length":"57","content-type":"application/json; charset=utf-8","expires":"-1","server":"Microsoft-IIS/10.0","x-ms-request-id":"f395b98d-89ca-450e-b4f4-9df4d81f3ef0","x-aspnet-version":"4.0.30319","x-powered-by":"ASP.NET","set-cookie":["ARRAffinity=***;Path=/;HttpOnly;Domain=***.scm.azurewebsites.net"],"date":"Thu, 16 Apr 2020 13:58:57 GMT","connection":"close"},"body":{"Message":"'D:\\home\\site\\wwwroot\\api\\' not found."}}
##[debug]setting affinity cookie ["ARRAffinity=***;Path=/;HttpOnly;Domain=***.scm.azurewebsites.net"]
##[debug][PUT]https://$***:***@***.scm.azurewebsites.net/api/vfs/site/wwwroot/api/
##[debug]Encountered a retriable status code: 409. Message: 'Conflict'.
##[debug][PUT]https://$***:***@***.scm.azurewebsites.net/api/vfs/site/wwwroot/api/
##[debug]Encountered a retriable status code: 409. Message: 'Conflict'.
##[debug][PUT]https://$***:***@***.scm.azurewebsites.net/api/vfs/site/wwwroot/api/
##[debug]Encountered a retriable status code: 409. Message: 'Conflict'.
##[debug][PUT]https://$***:***@***.scm.azurewebsites.net/api/vfs/site/wwwroot/api/
##[debug]Encountered a retriable status code: 409. Message: 'Conflict'.
##[debug][PUT]https://$***:***@***.scm.azurewebsites.net/api/vfs/site/wwwroot/api/
##[debug]createPath. Data: {"statusCode":409,"statusMessage":"Conflict","headers":{"cache-control":"no-cache","pragma":"no-cache","content-length":"87","content-type":"application/json; charset=utf-8","expires":"-1","server":"Microsoft-IIS/10.0","x-ms-request-id":"5a889012-0b6c-421a-9c38-2eced7483369","x-aspnet-version":"4.0.30319","x-powered-by":"ASP.NET","date":"Thu, 16 Apr 2020 13:59:50 GMT","connection":"close"},"body":{"Message":"Cannot delete directory. It is either not empty or access is not allowed."}}
##[debug]Deployment Failed with Error: Error: Failed to create path 'site/wwwroot/api' from Kudu. Error: Conflict (CODE: 409)
##[debug]task result: Failed
##[error]Error: Failed to create path 'site/wwwroot/api' from Kudu. Error: Conflict (CODE: 409)
##[debug]Processed: ##vso[task.issue type=error;]Error: Failed to create path 'site/wwwroot/api' from Kudu. Error: Conflict (CODE: 409)
##[debug]Processed: ##vso[task.complete result=Failed;]Error: Failed to create path 'site/wwwroot/api' from Kudu. Error: Conflict (CODE: 409)
When manually trying to add the "api" folder to the azure web app, I also get an error:
The deployment task to deploy the api looks like this:
- task: AzureRmWebAppDeployment@4
inputs:
ConnectionType: 'AzureRM'
azureSubscription: '***'
appType: 'webApp'
WebAppName: '***'
packageForLinux: '$(Pipeline.Workspace)\API'
VirtualApplication: 'api'
displayName: Publish API to Azure
What's the deal here? Is there any tutorial on how to do this? Am I configuring something wrong in Azure? What do I need to change to make this work? I've tried to see if I can publish the API manually from visual studio to see if it works there, but visual studio doesn't seem to support sub applications via the interface.
A:
The problem turned out to be that the AzureRmWebAppDeployment@4 task automatically enabled the WEBSITE_RUN_FROM_PACKAGE setting. Enabling this causes the entire wwwroot folder to become read-only. However there is no mention of this anywhere in the interface. This makes it impossible to deploy a sub application. Disabling this option fixes the issue.
I'm now going to try to include the API sub application in the package before sending it to azure, to see if the sub application then works. Otherwise I can simply not use the "run from package" option, despite its advantages over a normal deploy
|
[
"gaming.stackexchange",
"0000222302.txt"
] | Q:
How do I get on a Minecraft PE server when it says 'invalid name'?
I am having trouble getting onto a server in Minecraft PE on iOS. When I tap on the person's server it just says invalid name:
I have tried turning off and restarting the iPad, going to home screen and logging back into the server but I have had no luck and no change. Is there a reason why this is so?
A:
My kids had this problem after the update. Exit the game to the title screen, go into settings, and change your name to one without spaces or special characters. Then it will let you join other worlds again.
|
[
"drupal.stackexchange",
"0000017682.txt"
] | Q:
Copying a CiviCRM/Drupal install from one server to another (got error)
I've tried copying a a CiviCRM/Drupal install from 1 server to another. I copied all the files within the drupal root, and the database, and changed the database details in both Drupal's settings.php file and CiviCRM's civicrm.settings.php file. Drupal now works fine - copying this over appears to have worked, and I've done so succesfully with the same method many times. However, CiviCRM is not fully working. When I visit the main CiviCRM admin page (ie. http://cea-crm.philosofiles.com/civicrm/ on my server) I see CiviCRM's sidebar boxes (indicating it's working to some extent) but, to the right of them, see:
Page not found
The requested page "/civicrm/" could not be found.
When I click on any sidebar box link, such as 'My Contact Dashboard', I likewise see:
Page not found
The requested page "/civicrm/user?reset=1" could not be found.
Presumably I've missed some change I needed to make to reflect my new server setup? I can't see anything in civicrm.settings.php I still need to change, e.g. I've added lines like define( 'CIVICRM_UF_BASEURL' , 'http://cea-crm.philosofiles.com/' ); and $civicrm_root = '/home/myusername/public_html/d7/sites/cea-crm.philosofiles.com/modules/civicrm';
A:
If you have Drush installed, you can also use the following command to update some of those settings:
drush civicrm-update-cfg
It will try to update the URL and directory settings, which is pretty equivalent to the URL: "http:///index.php?q=civicrm/admin/setting/updateConfigBackend&reset=1".
After that, you can use the API to flush various CiviCRM caches which may be using that data:
drush civicrm-api system.flush
|
[
"stackoverflow",
"0062176307.txt"
] | Q:
How do you structure components and screens when using expo, native-base and react-navigate?
Just starting out with trying to build an app with React Native. I decided to use expo + react-navigate + native-base as a baseline, however I am having trouble setting up my project because each documentation seems to be doing things differently.
Specifically, I would like to know where to keep the code for components (e.g. a searchbar) and different screens in react-navigate. The documentation for react-navigate seems to be keeping all screens in the App.js file, but shouldn't I be separating different screens into different .js files in a subfolder? The documentation for native-base completely changes the App.js file so that I have no idea how to implement screens within that. All guides I could find seem to be outdated or not using the expo file structure, so I am having trouble getting the setup to work.
Thanks in advance!
A:
Usually the file structure is somewhat like this:
node_modules
expo
src
screens
components
app.js
package.json
package-lock.json
The src folder will not be there when you initially do expo start.
You will have to make it.
Generally you put the components that you use, in the components directory of the src folder, and the screens in the screens directory. The screens from the screens directory use the components from the components directory.
The app.js file is usually used for the initial screen you want to display on start-up of the app. But also most people make this app.js file into a navigator file where you can import all the navigation screens.
Keep in mind that these rules are just convention, you can customise according to your convenience as well.
|
[
"stackoverflow",
"0047475895.txt"
] | Q:
How to set Java ProcessBuilder parameter to run external .java file?
I'm trying to run other java file using ProcessBuilder class.
I would like to get input of entire path of java file + file name + .java and compile it.
Example, input: C:\Windows\test.java
And then, I store input into String variable FILE_LOCATION and call processbuilder to compile input .java file.
Here is my code:
static String JAVA_FILE_LOCATION;
static String command[] = {"javac", JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
process = new ProcessBuilder(new String[]{"java","-cp",A,B}).start();
But I don't know how to set the parameters.
process = new ProcessBuilder(new String[]{
"java","-cp",A,B}).start();
How should I set that parameter (A, B)?
A:
To answer your exact question, let's say, for instance, your class is in package com.yourcompany.yourproduct and your class file is in /dir/to/your/classes/com/yourcompany/yourproduct/Yourclass.class.
Then A = "/dir/to/your/classes" and B = "com.yourcompany.yourproduct.Yourclass".
However, there's a few things to be aware of. Looking at your code:
static String JAVA_FILE_LOCATION;
static String command[] = {"javac", JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);
No. You need to CD to the directory and then run javac. The easiest way to do that is by calling processBuilder.directory(new File("/dir/to/your/classes")). Then you need to give javac a relative path to your source file ("com/yourcompany/yourproduct/Yourclass.java").
Process process = processBuilder.start();
process = new ProcessBuilder(new String[]{"java","-cp",A,B}).start();
Wait until the first process has finished compiling before you try to run it! Between the two lines above, insert process.waitFor();. You might also want to check for any errors and only run the second process if the first has succeeded.
By the way, there's no need for all that long-hand creation of string arrays. Just use varargs: process = new ProcessBuilder("java", "-cp", A, B).start();.
|
[
"stackoverflow",
"0018844696.txt"
] | Q:
Artifacts with SVG text animations (CSS3)
I'm experiencing artifacts for text animations/scaling in most modern browsers: Chrome 29, IE10, Safari 5.1 (Windows), Safari 6.0.5 (Mac) and Opera 16. Only Firefox (tested with version 23) is working fine (all on Windows, except Safari 6).
Example:
http://jsfiddle.net/jejPS/1/
Hover over the "uf" tag. The text will scale up. When leaving the tag, the 'f' will leave a trail while scaling down.
Background:
This is part of a Tag Cloud. The SVG elements are generated by a company internal library (hardcoded in the jsfiddle). I enhanced our implementation to add this scaling on hover feature.
It doesn't matter if you use transform: scale(2) or the current font-size transition (:hover -> 2em). I haven't found any way to scale svg-text elements with CSS3/SVG-Animations without these artifacts.
Note: It appears that this only happens with certain characters like 'f' or 't'. But with every font I tried
I tried several workarounds:
Different CSS3 properties for better rendering:
-webkit-backface-visibility: hidden;
-webkit-transform: translateZ(0);
-webkit-transform: translate3d(0,0,0);
Or using
-webkit-transform: scale(1.1);
And even
<animateTransform attributeName="transform" attributeType="XML" type="scale" from="2" to="1" additive="sum" begin="mouseover" dur="1s" fill="freeze" />
All with the same effect in all of the mentioned browsers.
I haven't filed any bug report yet because I can hardly imagine that WebKit, Presto (Opera) and Internet Explorer 10 all have the same rendering bug.
I hope that there is just another way of scaling text in SVGs out there which I'm not yet aware of.
Thanks a lot for any help!
edit: typo
A:
A cheap hack that also seems to work is to add a non-breakable space at the end of your text (ie. "uf ").
|
[
"stackoverflow",
"0046496043.txt"
] | Q:
I was wondering how to make a cell go to another view controller in Xcode 9, swift
I've been trying to figure out how to configure a cell to go to another view, in this case, I'm listing a group of services after login and when the user taps on a service they like, it takes them to a map. But I don't know how to set the cell up in a way that it takes them to the map when its tapped. I've tried creating a segue but nothing happens when the cell is tapped. I'm new to programming and was wondering if someone could explain this.
I've watched a bunch of youtube videos which gave me the understanding on how to set up the cell (basic stuff).
Would really appreciate some advice, thanks!
Hope this post helps anyone that's dipping their feet into the programming journey!
Thank you, happy coding!
Here is the code I currently have:
import UIKit
struct cellData {
let cell : Int!
let text : String!
let image : UIImage! }
class ListServicesTVC: UITableViewController {
var arrayOfCellData = [cellData]()
override func viewDidLoad() {
arrayOfCellData = [cellData(cell : 1, text : "Barber Services", image : #imageLiteral(resourceName: "barberservice") ),
cellData(cell : 2, text : "Salon Services", image : #imageLiteral(resourceName: "salonservice"))]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfCellData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if arrayOfCellData[indexPath.row].cell == 1 {
let cell = Bundle.main.loadNibNamed("BarberServiceCell", owner: self, options: nil)?.first as! BarberServiceCell
cell.barberImageView.image = arrayOfCellData[indexPath.row].image
cell.barberServicesLabel.text = arrayOfCellData[indexPath.row].text
return cell
}
else if arrayOfCellData[indexPath.row].cell == 2 {
let cell = Bundle.main.loadNibNamed("SalonServicesCell", owner: self, options: nil)?.first as! SalonServicesCell
cell.salonImageView.image = arrayOfCellData[indexPath.row].image
cell.salonServicesLabel.text = arrayOfCellData[indexPath.row].text
return cell
}
else {
let cell = Bundle.main.loadNibNamed("BarberServiceCell", owner: self, options: nil)?.first as! BarberServiceCell
cell.barberImageView.image = arrayOfCellData[indexPath.row].image
cell.barberServicesLabel.text = arrayOfCellData[indexPath.row].text
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if arrayOfCellData[indexPath.row].cell == 1 {
return 120
}
else if arrayOfCellData[indexPath.row].cell == 2 {
return 120
}
else {
return 120
}
}
}
A:
Just follow the steps below:
create A tableView Outlet in ViewController Class.
create a TableViewCell Class and register with tableView Outlet.
then, create a DetailViewController Class ( i.e, When You click on a particular cell, it should show details of that particular cell)
In main "ViewController" do the following code
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {'
@IBOutlet var tableView: UITableView!
var tableData: [String] = ["Apple", "Samsung", "LG"]
// 1
override func viewDidLoad() {
super.viewDidLoad()
// Register customCell with tableView Outlet
let nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
// 2
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
// 3
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! CustomTableViewCell
// injecting data to cell
cell.lblCompanyName.text = tableData[indexPath.row]
cell.imgCompanyName.image = UIImage(named: tableData[indexPath.row])
return cell
}
// 4
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailObj=DetailViewController(nibName: "DetailViewController", bundle: nil)
self.navigationController?.pushViewController(detailObj, animated: true)
detailObj.nameVar=tableData[indexPath.row]
detailObj.imgStr=tableData[indexPath.row]
}
In "CustomTableViewCell" class
class CustomTableViewCell: UITableViewCell {
@IBOutlet var imgCompanyName: UIImageView!
@IBOutlet var lblCompanyName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}}
in "DetailViewController"
class DetailViewController: UIViewController {
@IBOutlet var name: UILabel!
@IBOutlet var image: UIImageView!
var nameVar:String?
var imgStr:String?
override func viewDidLoad() {
name.text=nameVar
image.image=UIImage(named: imgStr!)
super.viewDidLoad()
// Do any additional setup after loading the view.
}}
End of the Code
I think I am clear, if you have any quires just comment below.
|
[
"tex.stackexchange",
"0000132590.txt"
] | Q:
Align tikz node labels
I have created the following picture using tikz:
\tikzset{
graphnode/.style={
draw,fill,
circle,
minimum size=0.7mm,
inner sep=0
},
}
\begin{tikzpicture}[every node/.style={graphnode}]
\node (b)[label=left:$b$] at (0,0) {};
\node (g)[label=right:$g$] at (4,0) {};
\node (r)[label=above:$r$] at (2,3.4641) {};
\node[label=below:$v$] (n1) at (1.5,0.8) {};
\node[label=below:$u$] (n2) at (3,0.5) {};
\node[label=above right:$w$] (n3) at (2.1,2) {};
\draw(r.center) -- (g.center) -- (b.center) -- cycle;
\draw (n1.center) -- (b);
\draw (n2.center) -- (b);
\draw (n3.center) -- (b);
\draw (n1.center) -- (n2.center);
\draw (n2.center) -- (g);
\draw (n3) -- (g);
\draw (n1.center) -- (n3.center);
\draw (n2.center) -- (n3.center);
\draw (n3.center) -- (r);
\end{tikzpicture}
The problem is that the two labels b and g are not properly aligned. How can I align them without changing the node positions?
A:
One possibility is to use a math strut:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\tikzset{
graphnode/.style={
draw,fill,
circle,
minimum size=0.7mm,
inner sep=0
},
}
\begin{tikzpicture}[every node/.style={graphnode}]
\node (b)[label=left:$\mathstrut b$] at (0,0) {};
\node (g)[label=right:$\mathstrut g$] at (4,0) {};
\node (r)[label=above:$r$] at (2,3.4641) {};
\node[label=below:$v$] (n1) at (1.5,0.8) {};
\node[label=below:$u$] (n2) at (3,0.5) {};
\node[label=above right:$w$] (n3) at (2.1,2) {};
\draw(r.center) -- (g.center) -- (b.center) -- cycle;
\draw (n1.center) -- (b);
\draw (n2.center) -- (b);
\draw (n3.center) -- (b);
\draw (n1.center) -- (n2.center);
\draw (n2.center) -- (g);
\draw (n3) -- (g);
\draw (n1.center) -- (n3.center);
\draw (n2.center) -- (n3.center);
\draw (n3.center) -- (r);
\end{tikzpicture}
\end{document}
|
[
"stackoverflow",
"0032466232.txt"
] | Q:
Tableau tooltip incorrect when toggling through quick filter
Link to workbook on public tableau
I created calculated value to determine grade for business, and this is colormap (in tab Grade per Location)
And when I hover over datapoints on map (tab Map), it displays correct Grade, i.e. D for Shish Boom Bah Car Wash
But as soon as I select any location from a drop-down, all grades are A
Tot_Avg is calculated like this:
{ EXCLUDE [Location (Loc)] : AVG([Rating]) }
Avg_Rating like this:
AVG([Rating])
And here are the conditions for receiving an A:
IF [Avg_Rating] > ATTR([Tot_Avg]) - (.10 * ATTR([Tot_Avg]))
THEN "A"
How to troubleshoot?
A:
I think your confusion is in what that EXCLUDE is doing. It is NOT ignoring filters. It's just saying not to group by Location when aggregating AVG([Rating]). When you filter out all but one location, AVG([Rating]) and { EXCLUDE [Location (Loc)] : AVG([Rating]) } become equivalent, because with either calculation, you're averaging for all points in your filtered partition.
As a result, your condition for receiving an A will always be true if there's only one location. (Check the math: X > X - .1X → X > .9X)
Here's a different way to get what you're after. Make a calculated field (I'll call it Location Filter):
LOOKUP(ATTR([Location (Loc)]),0)
Then trash your Location filter and replace it with that field. We're doing something sneaky here - we're making the exact same filter as we had before, but we're disguising it as a table calculation (by using LOOKUP()). Tableau doesn't execute table calculations until after it's created the filtered partition, so we've tricked it into letting us use every location while still just examining one.
|
[
"stackoverflow",
"0012393358.txt"
] | Q:
Free hand character recognition in android
We are working on an android application that involves free hand character recognition.
The application requires to student to draw the free hand image of an alphabet on the android screen,and the application process the image drawn and returns the accuracy of the alphabet written.
We are considering two options
a. Using tesseract.
b. Using our own algorithm on which we are still working
Problems
a. Tesseract is not at all helping in recognizing free hand characters.Any pointers on how to train tesseract for the same will be highly appreciated.
b. None of our algorithm are working to our expectation.
A:
Tesseract is actually the wrong approach for recognizing characters written to the screen because it needlessly discards some very valuable info: how the image was originally drawn. How it breaks down into strokes, the order / direction of each stroke, etc - Tesseract has to spend a tremendous amount of time trying to figure out the underlying structure of each character when your software already knows it.
What you want is an actual "handwriting recognition" library, not just an OCR library like Tesseract; you specifically want an "online" handwriting recognition library, "online" meaning that you can capture the actual sequence of points that the user drew to the screen. There are a number of open-source libraries available for this, for example Unipen and LipiTk.
|
[
"stackoverflow",
"0025071556.txt"
] | Q:
removing tag from a line in Python
I have a text that has the following schema:
word1:word2<br />
word3:word4<br />
...
I would like to remove the last part , and store my results in another file. I have tried the following (still without saving my results in other file):
def main():
fileR=open("test.txt","r")
for line in fileR:
if line.endswith('<br />'):
line=line[:-6]
print line
but when I run it, it does not print anything. What is wrong?
Thanks
A:
That's because each line ends with newline character(s).
You can fix it like this (and automatically close the file):
def main():
with open("test.txt", "r") as fileR:
for line in (line.rstrip() for line in fileR):
if line.endswith('<br />'):
line = line[:-6]
print line
|
[
"stackoverflow",
"0002535631.txt"
] | Q:
Higher order functions in C
Is there a "proper" way to implement higher order functions in C.
I'm mostly curious about things like portability and syntax correctness here and if there are more than one ways what the merits and flaws are.
Edit:
The reason I want to know how to create higher order functions are that I have written a system to convert PyObject lists (which you get when calling python scripts) into a list of C structures containing the same data but organized in a way not dependant on the python.h libraries. So my plan is to have a function which iterates through a pythonic list and calls a function on each item in the list and places the result in a list which it then returns.
So this is basically my plan:
typedef gpointer (converter_func_type)(PyObject *)
gpointer converter_function(PyObject *obj)
{
// do som stuff and return a struct cast into a gpointer (which is a void *)
}
GList *pylist_to_clist(PyObject *obj, converter_func_type f)
{
GList *some_glist;
for each item in obj
{
some_glist = g_list_append(some_glist, f(item));
}
return some_glist;
}
void some_function_that_executes_a_python_script(void)
{
PyObject *result = python stuff that returns a list;
GList *clist = pylist_to_clist(result, converter_function);
}
And to clearify the question: I want to know how to do this in safer and more correct C. I would really like to keep the higher order function style but if that is frowned upon I greatly appreciate ways to do this some other way.
A:
Technically, higher-order functions are just functions that take or return functions. So things like qsort are already higher-order.
If you mean something more like the lambda functions found in functional languages (which is where higher order functions really become useful), those are quite a bit harder and can't be done naturally in current standard C. They're just not part of the language. Apple's blocks extension is the best candidate. It only works in GCC (and LLVM's C compiler), but they are really useful. Hopefully something like that will catch on. Here's a few relevant resources:
Apple's documentation on the feature (references some Apple-specific technologies and also addresses Objective-C, but the core block stuff is part of their extensionto C)
Here's a good intro on blocks
Cocoa for Scientists' overview of C blocks
A:
The big problem with implementing higher-order functions in C is that to do anything non-trivial you need closures, which are function pointers augmented with data structures containing local variables they have access to. Since the whole idea behind closures is to capture local variables and pass those along with the function pointer, it's hard to do without compiler support. And even with compiler support it's hard to do without garbage collection because variables can exist outside of their scope, making it hard to figure out when to free them.
A:
In straight c, this is really only done through function pointers, which are both a pain and not meant for this type of thing (which is partially why they are a pain). Blocks (or closures, according to non-apple) are fantastic for this, though. They compile in gcc-4.x or something, and icc something, but regardless thats what you're looking for. Unfortunately, I can't seem to find any good tutorials online, but suffice to say it works something like this:
void iterate(char *str, int count, (^block)(str *)){
for(int i = 0; i < count; i++){
block(list[i]);
}
}
main() {
char str[20];
iterate(str, 20, ^(char c){
printf("%c ", c);
});
int accum = 0;
iterate(someList, 20, ^(char c){
accum += c;
iterate(str, 20, ^(char c){
printf("%c ", c);
});
});
}
obviously this code is pointless, but it it prints each character of a string (str) with a space in between it, then adds all of the characters together into accum, and every time it does it prints out the list of characters again.
Hope this helps. By the way, blocks are very visible in Mac OS X Snow Leopard api-s, and I believe are in the forthcoming C++0x standard, so they're not really that unusual.
|
[
"stackoverflow",
"0024375773.txt"
] | Q:
Replace each letter with it's ASCII code in a string in PL/SQL
is a better, shorter way to preform this code:
/*Replace all letters by their respective ASCII code - 55*/
as_iban := REPLACE(as_iban, 'A', '10');
as_iban := REPLACE(as_iban, 'B', '11');
as_iban := REPLACE(as_iban, 'C', '12');
as_iban := REPLACE(as_iban, 'D', '13');
as_iban := REPLACE(as_iban, 'E', '14');
as_iban := REPLACE(as_iban, 'F', '15');
as_iban := REPLACE(as_iban, 'G', '16');
as_iban := REPLACE(as_iban, 'H', '17');
as_iban := REPLACE(as_iban, 'I', '18');
as_iban := REPLACE(as_iban, 'J', '19');
as_iban := REPLACE(as_iban, 'K', '20');
as_iban := REPLACE(as_iban, 'L', '21');
as_iban := REPLACE(as_iban, 'M', '22');
as_iban := REPLACE(as_iban, 'N', '23');
as_iban := REPLACE(as_iban, 'O', '24');
as_iban := REPLACE(as_iban, 'P', '25');
as_iban := REPLACE(as_iban, 'Q', '26');
as_iban := REPLACE(as_iban, 'R', '27');
as_iban := REPLACE(as_iban, 'S', '28');
as_iban := REPLACE(as_iban, 'T', '29');
as_iban := REPLACE(as_iban, 'U', '30');
as_iban := REPLACE(as_iban, 'V', '31');
as_iban := REPLACE(as_iban, 'W', '32');
as_iban := REPLACE(as_iban, 'X', '33');
as_iban := REPLACE(as_iban, 'Y', '34');
as_iban := REPLACE(as_iban, 'Z', '35');
The code above converts all the upper chars of the string to there respective ASCII code numbers. but this is not the correct way of going about it, but I can't figure out another way of doing it.
I have tried something like
FOR i in 1..LENGTH(as_iban)
LOOP
select regexp_replace(as_iban,'['||substr(as_iban,i,1)||']', ASCII(regexp_substr(as_iban,'['||substr(as_iban,i,1)||']')) - 55) into as_iban FROM dual;
END LOOP;
A:
I think you might be looking for something like this:
CREATE OR REPLACE FUNCTION FUBAR_STR(in_str VARCHAR2) RETURN VARCHAR2 AS
out_str VARCHAR2(4000) := '';
BEGIN
FOR i IN 1..LENGTH(in_str) LOOP
out_str := out_str || TO_CHAR(ASCII(SUBSTR(in_str,i,1)) - 55);
END LOOP;
RETURN out_str;
END FUBAR_STR;
So when you run:
select fubar_str('abcd') from dual;
You get: 42434445.
Here is the reversible, safer one to use.
CREATE OR REPLACE FUNCTION FUBAR_STR(in_str VARCHAR2) RETURN VARCHAR2 AS
out_str VARCHAR2(32676) := '';
BEGIN
FOR i IN 1..LEAST(LENGTH(in_str),10892) LOOP
out_str := out_str || LPAD(TO_CHAR(ASCII(SUBSTR(in_str,i,1)) - 55),3,'0');
END LOOP;
RETURN out_str;
END FUBAR_STR;
So when you run:
select fubar_str('abcd') from dual;
You get: 042043044045.
And because I'm really bored tonight:
CREATE OR REPLACE FUNCTION UNFUBAR_STR(in_str VARCHAR2) RETURN VARCHAR2 AS
out_str VARCHAR2(10892) := '';
BEGIN
FOR i IN 0..(((LENGTH(in_str) - MOD(LENGTH(in_str),3))/3) - 1) LOOP
out_str := out_str || CHR(TO_NUMBER(LTRIM(SUBSTR(in_str,(i * 3) + 1,3),'0')) + 55);
END LOOP;
RETURN out_str;
END UNFUBAR_STR;
So when you run:
select unfubar_str('042043044045') from dual;
You get: abcd.
|
[
"stackoverflow",
"0062628204.txt"
] | Q:
Decode seemingly malformed utf8 representation of Unicode pointer from Facebook data export
Similar to in this post, is there a way to decode some of the seemingly malformed UTF-8 data returned from downloading a copy of my Facebook data?
Looking at a particular example, in one of my chats I have a sent message containing only the emoji . Opening the message_1.json file with vim and looking at the appropriate entry shows the text "\u00f0\u009f\u0092\u008e". However this differs from the view from my terminal (Mac OSX)
$ jq '.messages[0].content' message_1.json
"ð" # stackoverflow seems to be truncating this string, there are 3 extra chars which show as spaces
$ jq '.messages[0].content' message_1.json > utf
$ cat utf
"ð"
$ od -h utf
0000000 c322 c2b0 c29f c292 228e 000a
0000013
$ wc utf
1 1 11 utf
This also differs the output from directly pasting the emoji into a file
$ echo '' > gem.txt
$ cat gem.txt
$ od -h gem.txt
0000000 9ff0 8e92 000a
0000005
$ wc gem.txt
1 1 5 gem.txt
And I get seemingly different information when reading in these two files with python3
$ python3
Python 3.7.3 (default, Dec 13 2019, 19:58:14)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('gem.txt', 'r') as f:
... gem = f.read()
...
>>> gem
'\n'
>>> len(gem)
2
>>> ord(gem[0])
128142
>>>
>>>
>>> with open('utf', 'r') as f:
... utf = f.read()
...
>>> utf
'"ð\x9f\x92\x8e"\n'
>>> len(utf)
7
>>> for char in utf:
... print(ord(char))
...
34
240
159
146
142
34
10
>>>
I have a few questions based on this behavior:
Is the data returned by Facebook encoded incorrectly? This page shows the proper Unicode pointer for the gem emoji to be U+1F48E, and the corresponding UTF-8 0xF0 0x9F 0x92 0x8E representation matches with the byte output from od
Is there a way for me to parse the returned string from Facebook? It seems that the previous question recommends a regular expression to transform the text before doing so, is this required?
The gem.txt had a length of 5 bytes, and subtracting the newline, 4 bytes to represent the emoji. This makes sense to me as its UTF-8 representation requires 4 bytes. Why does the utf document list 11 bytes (presumably 10 without the newline)?
A:
It looks like the content of your JSON file indeed got mojibaked, ie. misinterpreted with the wrong encoding.
>>> import json
>>> # That's how it should look:
>>> print(json.dumps(''))
"\ud83d\udc8e"
>>> # That's what you got:
>>> mojibaked = ''.encode('utf8').decode('latin1')
>>> print(json.dumps(mojibaked))
"\u00f0\u009f\u0092\u008e"
Check if you can fix how the JSON file is created.
Latin-1 is the default in some tools/protocols.
The convenient thing is that you can always decode any stream of bytes as Latin-1 without exceptions.
It might corrupt your input though, as happens here.
If you can't fix the source, you might be able to recover by doing the encoding round-trip in reverse:
>>> mojibaked = json.loads('"\\u00f0\\u009f\\u0092\\u008e"')
>>> mojibaked
'ð\x9f\x92\x8e'
>>> mojibaked.encode('latin1').decode('utf8')
''
|
[
"stackoverflow",
"0011857108.txt"
] | Q:
What should be the permissions on /var/tmp/mysite if my PHP script writes there?
I (PHP newbie) am setting up a legacy PHP website on my Linux/Apache server.
When I test the site in my browser I get this error:
Warning: move_uploaded_file(/var/tmp/jinfo/Circuit/best_cities.csv):
failed to open stream: Permission denied in /var/www/jinfo/includes/jinfo.inc.php on line 89
Warning: move_uploaded_file(): Unable to move '/tmp/phpMLE9Ox' to
'/var/tmp/jinfo/Circuit/best_cities.csv' in
/var/www/jinfo/includes/jinfo.inc.php on line 89
Looks like a file system permissions problem. The script uses /var/tmp/jinfo and its subfolders to store files. The permissions on that directory are:
drwxr-xr-x 5 root root 4096 Aug 7 15:32 jinfo
Since Apache is running as user www-data, the error message is expected. But what should the permissions be? I am sure there are lots of ways to make the error message go away by loosening permissions, but I want to follow the best practice. Should I change the owner (chown) to www-data, or chmod the permissions?
Note: I need the changes to propagate to subdirectories too.
A:
You need to fix your permissions before changing the group will be effective. As mentioned in Explosion Pill's answer, you should change the group to be www-data for Apache. You can do this recursively on your /var/www directory:
chown -R owner:www-data /var/www
where owner is the user that currently owns the files.
Here you can see the read/write/execute permissions on the file for the owner, group, and others respectively:
drwxr-xr-x
Ignore the d, the other letters mean:
owner - read write execute
group - read ------ execute
others - read ------ execute
This site gives you the meaning of the chmod numbers:
http://www.goldenplanet.com/support/kb/articles/changing-of-file-rights-chmod-on-the-webserver.html
0: No rights
1: Execute
2: Write
3: Write/Execute
4: Read
5: Read/Execute
6: Read/Write
7: Read/Write/Execute
You can do chmod 775 on the directory that is giving the permission error which will give the owner of the file and the group full permissions, while only giving "others," read and execute access.
|
[
"mathoverflow",
"0000004478.txt"
] | Q:
Torsion in homology or fundamental group of subsets of Euclidean 3-space
Here's a problem I've found entertaining.
Is it possible to find a subset of 3-dimensional Euclidean space such that its homology groups (integer coefficients) or one of its fundamental groups contains an element of finite order?
Context: The analogous question has a negative answer in dimension 2. This is a theorem of Eda's (1998). In dimension 4 and higher, the answer is positive as the real projective plane embeds. If the subset of 3-space has a regular neighbourhood with a smooth boundary, a little 3-manifold theory says the fundamental group and homology groups are torsion-free.
edit: Due to Autumn Kent's comment and the ensuing discussion, torsion in the homology has been ruled out provided the subset of $\mathbb R^3$ is compact and has the homotopy-type of a CW-complex (more precisely, if Cech and singular cohomologies agree).
A:
I don't think that
torsion in the homology has been ruled out
Certainly, torsion in Cech cohomology has been ruled out for a compact subset. The "usual" universal coefficient formula, relating Cech cohomology to $\operatorname{Hom}$ and $\operatorname{Ext}$ of Steenrod homology, is not valid for arbitrary compact subsets of $\Bbb R^3$ (although it is valid for ANRs, possibly non-compact). The "reversed" universal coefficient formula, relating Steenrod homology to $\operatorname{Hom}$ and $\operatorname{Ext}$ of Cech cohomology is valid for compact metric spaces, but it does not help, because $\operatorname{Ext}(\Bbb Z[\frac1p],\Bbb Z)\simeq\Bbb Z_p/\Bbb Z\supset\Bbb Z_{(p)}/\Bbb Z$, which contains $q$-torsion for all primes $q\ne p$. (Here $\Bbb Z_{(p)}$ denotes the localization at the prime $p$, and $\Bbb Z_p$ denotes the $p$-adic integers.
The two UCFs can be found in Bredon's Sheaf Theory, 2nd edition, equation (9) on p.292
in Section V.3 and Theorem V.12.8.)
The remark on $\operatorname{Ext}$ can be made into an actual example. The $p$-adic solenoid $\Sigma$ is a subset of $\Bbb R^3$. The zeroth Steenrod homology $H_0(\Sigma)$ is isomorphic by the Alexander duality to $H^2(\Bbb R^3\setminus\Sigma)$. This is a cohomology group of an open $3$-manifold contained in $\Bbb R^3$, yet it is isomorphic to $\Bbb Z\oplus(\Bbb Z_p/\Bbb Z)$ (using the UCF, or the Milnor short exact sequence with $\lim^1$), which contains torsion. Of course, every cocycle representing torsion is "vanishing", i.e. its restriction to each compact submanifold is null-cohomologous within that submanifold.
By similar arguments, $H_i(X)$ (Steenrod homology) contains no torsion for $i>0$ for every compact subset $X$ of $\Bbb R^3$.
It is obvious that "Cech homology" contains no torsion (even for a noncompact subset $X$ of $\Bbb R^3$), because it is the inverse limit of the homology groups of polyhedral neighborhoods of $X$ in $\Bbb R^3$. But I don't think this is to be taken seriously, because "Cech homology" is not a homology theory (it does not satisfy the exact sequence of pair). The homology theory corresponding to Cech cohomology is Steenrod homology (which consists of "Cech homology" plus a $\lim^1$-correction term). Some references for Steenrod homology are Steenrod's original paper in Ann. Math. (1940), Milnor's 1961 preprint (published in http://www.maths.ed.ac.uk/~aar/books/novikov1.pdf), Massey's book Homology and Cohomology Theory. An Approach Based on Alexander-Spanier Cochains, Bredon's book Sheaf Theory (as long as the sheaf is constant and has finitely generated stalks) and this paper http://front.math.ucdavis.edu/math/0812.1407
As for torsion in singular $4$-homology of the Barratt-Milnor example, this is really a question about framed surface links in $S^4$ (see the proof of theorem 1.1 in the linked paper).
A:
I'll assume that the subset is compact.
Then, if you use Cech cohomology, Alexander duality turns this into a question about the complement, which is a 3-manifold.
So, I answer with another question: Can a (wild) open submanifold of the 3-sphere have torsion in its homology? (My guess is no. But then I'm not RH Bing.)
A:
I think your subset of R^3 must be pretty ugly to have a fighting chance. If it is
a compact subpolyhedron of R^3, then by Alexander duality its k-homology is the same as
(2-k)-dimensional cohomology of an open 3-manifold. The only interesting case is k=1 because 0th (co)homology are torsion free, but if the open manifold is homotopy equivalent to a finite complex then by universal coefficients 1st cohomology is torsion free. This rules out all "nice" examples.
|
[
"stackoverflow",
"0010759741.txt"
] | Q:
Arduino Serial Communication: Local Echo Human character input
I'm using an Arduino Duemilanove to run some tests. I'm communicating with the arduino over a serial port. All i'm trying to do is read in a couple of ints, and i'm using the parseInt() function for its simplicity.
My question is, is there a way to program the ardunino to echo back each character as it is entered while still making use of the parseInt() function?
I know there are typically options to turn on local echo in a terminal clients, but i'd rather not rely on these.
Here is the code I'm using:
unsigned int timeTotal;
Serial.print("Enter Total Time of Period (ms): ");
while (!Serial.available()) { ; } //wait for input
while (Serial.available() > 0) {
//Serial.write(Serial.peek());
timeTotal = Serial.parseInt(); //read int
Serial.read(); //discard newline char at end of input
Serial.println();
Serial.print("Total Time: ");
Serial.println(timeTotal, DEC);
}
as you can see, i was trying to use a peek() but that only gets me one character....
Thanks in advance !!!
A:
You could read characters into a string (echoing them as you go) until your hit you delimiter. Then convert the string with atoi(). Without looking at the source, I am sure this ia what parseInt does anyway.
|
[
"stackoverflow",
"0028295626.txt"
] | Q:
Syntax error when trying to use a column named `lineno`
I've MYSQL and MSSQL query. MYSQL Query is working fine but same Query modified as a MSSQL Query is showing error.
In this MSSQL Query testCaseName is VARBINARY(MAX) type.
MYSQL QUERY:
update tce_lineno
set testcasename=concat(concat(testcasename,','),:tcname)
where lineno=:lineno and project=:project
MSSQL QUERY:
update tce_lineno
set testcasename=((testcasename +',')+'rosdsadp')
where lineno='23' and project='proj001';
ERROR IS:
Incorrect syntax near the keyword 'lineno'
How can I modified in correct way?
A:
lineno is a reserved word in TSQL and needs to be escapes with brackets
where [lineno] = '23' and project = 'proj001';
|
[
"stackoverflow",
"0022460328.txt"
] | Q:
Appending to a text area followed by a new line
I'd like to append a string to a text area, followed by a new line.
My research shows that
Here's what I've tried thus far, but have not had any luck with:
function putStr(str){
document.getElementById('output').value += str +\n;
}
function putStr(str){
document.getElementById('output').value += str \n;
}
function putStr(str){
document.getElementById('output').value += str;
document.getElementById('output').value += \n;
}
Thanks!
A:
Give this a go with the quotes
function putStr(str){
document.getElementById('output').value += str +"\n";
}
JS Fiddle: http://jsfiddle.net/DeanWhitehouse/xk4W3/
|
[
"stackoverflow",
"0006129465.txt"
] | Q:
Array-like statement with curly brackets - what is the purpose?
I found this snippet of code online and I was wondering what it does:
$k[$i] = ord($key{$i}) & 0x1F;
I know that ord() returns an ASCII value, but I'm unclear on what the curly brackets do $key{$i} and also what this does & 0x1F.
A:
That's not an array syntax. It's for accessing single characters from strings only. The index must be numeric.
$str{1} == $str[1]
It's briefly mentioned here in the info box: http://www.php.net/manual/en/language.types.string.php#language.types.string.substr
Also, it's officially declared deprecated. It has been on and off supposed deprecation in the manual, but is still very valid, if uncommon, syntax.
The & 0x1F is a bit-wise AND. In this case it limits the decimal values to 0 till 31.
A:
First part of your question: curly braces
This is about referencing the value of the variable.
In your example, if $i is equal to 123, then
$k[$i] = ord($key{$i}) & 0x1F;
will be the same as
$k[123] = ord($key[123]) & 0x1F;
Second part of your question: '&' sign
& is a binary operator. See more in the documentation. It sets the bits if they are set in both variables.
A:
In PHP, either [square brackets] or {curly braces} are fully legal, interchangeable means of accessing an array:
Note: Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).
Source: http://www.php.net/manual/en/language.types.array.php
Both are fully valid; curly braces are not deprecated.
Concerning "& 0x1F", others like @Tadek have responded:
& is a binary operator. See more in the documentation [http://www.php.net/manual/en/language.operators.bitwise.php]. It sets the bits if they are set in both variables.
|
[
"math.stackexchange",
"0001696233.txt"
] | Q:
Sets of exterior measure zero are necessarily measurable
$\mu_*$ is an exterior measure and the definition of a Caratheodory measurable set, $E$, is that for any $A \in X$,$\;\;$ $\mu_*(A)=\mu_*(E\cap A)+\mu_*(E^c\cap A)$
My book makes the remark that say that all sets of exterior measure zero are measurable and that this remark is immediate from the definition. Could someone explain to me why this is true?
A:
By the subadditivity of $\mu_{\ast}$ we have
$$\mu_{\ast}(A) \leqslant \mu_{\ast}(A\cap E) + \mu_{\ast}(A\setminus E)$$
whatever set $E$ is. If $\mu_{\ast}(E) = 0$, then by monotonicity ($A\cap E \subseteq E$) of $\mu_{\ast}$ we also have $\mu_{\ast}(A\cap E) = 0$ and hence, once more by monotonicity ($A \setminus E \subseteq A$),
$$\mu_{\ast}(A\cap E) + \mu_{\ast}(A \setminus E) = \mu_{\ast}(A\setminus E) \leqslant \mu_{\ast}(A) \leqslant \mu_{\ast}(A\cap E) + \mu_{\ast}(A\setminus E),$$
so equality overall.
|
[
"stackoverflow",
"0004250299.txt"
] | Q:
Alert with 2 buttons
I'm going to have a link to a website in my app. The user will click on a button that says Website and an Alert will appear with 2 buttons. One of the buttons is just going to be a cancel button and the other button is going to open the website.
Could you help me with this?
Thanks!
A:
put this into your header file:
@interface YourViewController : UIViewController <UIAlertViewDelegate>
put this into the class with your alert:
- (void)alertOKCancelAction {
// open a alert with an OK and cancel button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Open?" message:@"Open Website?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Open", nil];
alert.tag = 1;
[alert show];
[alert release];
}
add this method:
- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
// the user clicked one of the OK/Cancel buttons
if(alert.tag == 1)
{
if(buttonIndex == alert.cancelButtonIndex)
{
NSLog(@"cancel");
}
else
{
NSLog(@"ok");
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.google.com"]];
}
}
}
|
[
"stackoverflow",
"0045683587.txt"
] | Q:
Exclude Classes from Being Included in Shaded Jar
I'm trying to exclude certain classes from being included in a shaded jar.
I have tried several different configurations but for some reason the jars are still being included in my jar. Here is the plugin setup:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
<exclude>java/*</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin>
I have also tried the following patterns:
<exclude>java.*</exclude>
<exclude>java.util.concurrent.ConcurrentHashMap</exclude>
<exclude>java/util/concurrent/ConcurrentHashMap</exclude>
None of which have actually excluded the file from my jar. How can I exclude this class from my jar?
A:
You are only excluding top level files in the java folder. You can exclude recursively like this:
<exclude>java/**/*</exclude>
|
[
"stackoverflow",
"0026857371.txt"
] | Q:
Replace column using awk
I have 3 files
1file
14/09/15
14/09/15
14/09/15
14/09/15
14/09/15
2file
14/09/01
14/09/01
14/09/01
14/09/01
14/09/01
and 3file
15/09/14,11-37,01/09/14,1224A,0G,71%,RGS
15/09/14,11-41,01/09/14,2700A,0G,94%,RAN
15/09/14,11-43,01/09/14,2701A,0G,100%,RAN
15/09/14,11-44,01/09/14,2701B,0G,92%,RAN
15/09/14,11-46,01/09/14,2708A,0G,88%,RAN
I need replace the column 1 from 3f with the column 1 from 1f and the third from 3f with the column 1 of 2f
How can I replace using awk?
A:
The following awk code will be usefull
$ awk 'BEGIN{OFS=FS=","}NF==1{line[FNR]=line[FNR]","$0} NF>1{split(line[FNR], a); $1=a[2]; $2=a[3]; print $0}' 1file 2file 3file
14/09/15,14/09/01,01/09/14,1224A,0G,71%,RGS
14/09/15,14/09/01,01/09/14,2700A,0G,94%,RAN
14/09/15,14/09/01,01/09/14,2701A,0G,100%,RAN
14/09/15,14/09/01,01/09/14,2701B,0G,92%,RAN
14/09/15,14/09/01,01/09/14,2708A,0G,88%,RAN
What it does??
OFS=FS="," sets output field separatorOFS and field separator FS as ,
NF==1{line[FNR]=line[FNR]","$0} If number of fields/columsn , NF is one, save the value in line variable seperated by commas
NF>1{split(line[FNR], a); $1=a[2]; $2=a[3]; print $0} takes the action when NF greater than one
split(line[FNR], a); split the line variable to array a
$1=a[2]; $2=a[3]; sets the first and second column
print $0 prints the entire record
|
[
"stackoverflow",
"0012834594.txt"
] | Q:
Intent PACKAGE_ADDED not registering
Hello i am trying to detect application installed so that i can do some analysis on the application and i am using this example i found on stackoverflow to listen for package installs from my current application but nothing is happening in my logcat.
void registerReceiver() {
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
}
public void onReceive(Context context, Intent intent) {
String actionStr = intent.getAction();
if (Intent.ACTION_PACKAGE_ADDED.equals(actionStr)) {
Uri data = intent.getData();
String pkgName = data.getEncodedSchemeSpecificPart();
//handle package adding...
Log.i("Logging Service", pkgName);
}
}
<receiver android:name="RealTimeActivity">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_ADDED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_CHANGED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REMOVED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_INSTALL" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REPLACED" />
A:
Due to a broadcast behavior change since Android 3.1, your app must be started before it can receive the app installation/removal intents. See kabuko's answer in this thread.
The following receiver works for me on a Android 4.0 device (I have an activity in the app, first start the activity i.e. the app is also started, then the receiver can receive the broadcast).
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
(some apps run a dummy sticky service to keep the app process alive, so that they can receive certain broadcasts)
|
[
"stackoverflow",
"0063616406.txt"
] | Q:
How to Merge two array of objects based on same key and value in javascript?
I have two arrays videos and storeProducts. videos array may have product_id and storeProducts must have
product_id. I need merge these based on both produt_id same else only push video items in array.
let videos = [
{
"id": 1,
"product_id":"training_video_test_1",
"video_title": "Video title 1",
"video_short_description": "desc 1"
},
{
"id": 2,
"product_id":"training_video_test_2",
"video_title": "Video title 2",
"video_short_description": "desc 2"
},
{
"id": 3,
"product_id":"training_video_test_3",
"video_title": "Video title 3",
"video_short_description": "desc 3"
}
];
let storeProducts = [
{
"product_id":"training_video_test_1",
"prduct_title":"training_video_test_1",
"price":100
},
{
"product_id":"training_video_test_2",
"prduct_title":"training_video_test_2",
"price":100
}
];
I need to merge these two when storeProducts.product_id === videos.product_id otherswise ignore store products items push only video items.
Example output:
[
{
"id": 1,
"product_id":"training_video_test_1",
"video_title": "Video title 1",
"video_short_description": "desc 1",
"prduct_title":"training_video_test_1",
"price":100
},
{
"id": 2,
"product_id":"training_video_test_2",
"video_title": "Video title 2",
"video_short_description": "desc 2",
"prduct_title":"training_video_test_2",
"price":100
},
{
"id": 3,
"product_id":"training_video_test_3",
"video_title": "Video title 3",
"video_short_description": "desc 3"
}
]
I have tried Like this:
let resultArr = [];
videos.forEach((v)=>{
storeProducts.forEach((p)=>{
if(p.product_id == v.product_id){
resultArr.push(Object.assign({},v,p))
}
})
})
But it doesn't work as i expected.Please help me.
A:
You can use map instead
let videos = [
{ id: 1, product_id: "training_video_test_1", video_title: "Video title 1", video_short_description: "desc 1" },
{ id: 2, product_id: "training_video_test_2", video_title: "Video title 2", video_short_description: "desc 2" },
{ id: 3, product_id: "training_video_test_3", video_title: "Video title 3", video_short_description: "desc 3" },
];
let storeProducts = [
{ product_id: "training_video_test_1", prduct_title: "training_video_test_1", price: 100 },
{ product_id: "training_video_test_2", prduct_title: "training_video_test_2", price: 100 },
];
const result = videos.map(v => ({ ...v, ...storeProducts.find(sp => sp.product_id === v.product_id) }));
console.log(result);
|
[
"chemistry.stackexchange",
"0000115553.txt"
] | Q:
Why is Ni[(PPh₃)₂Cl₂] tetrahedral?
Since PPh₃ is strong field ligand and, the famous Wilkinson's catalyst, which also possess this ligand is square planar, then what makes the above complex tetrahedral?
A:
We sometimes call this type of complex 'pseudotetrahedral' since there is an isomerism from a tetrahedral to a square planar complex possible. I was unable to find the original work here but this link gives some information. As you already mentioned there are two strong and two weak ligands so it's hard to tell how strong the ligand field splitting will be. For your particular complex it seems to be right on the spot where it would change from one to the other so depending on what you do you can influence the equilibrium. From what I read this may depend on the ability of the solvent to coordinate to the complex as well, the temperature, etc.
This is also mentioned in Earnshaw's Chemistry of the elements
Planar-tetrahedral equilibria. Compounds
such as $\ce{[NiBr2(PEtPh2)2]}$ mentioned above as
well as a number of sec-alkylsalicylaldiminato
derivatives (i.e. Me in Fig. 27.6b replaced by
a sec-alkyl group) dissolve in non-coordinating
solvents such as chloroform or toluene to give
solutions whose spectra and magnetic properties
are temperature-dependent and indicate the presence
of an equilibrium mixture of diamagnetic
planar and paramagnetic tetrahedral molecules.
A:
Dichlorobis(triphenylphosphine)nickel(II), or $\ce{NiCl2[P(C6H5)3]2}$ in square planar form is red and diamagnetic. The blue form is paramagnetic and features tetrahedral Ni(II) centers. Both tetrahedral and square planar isomers coexist in solutions. Weak field ligands, favor tetrahedral geometry and strong field ligands favor the square planar isomer. Both weak field ($\ce{Cl−}$) and strong field ($\ce{PPh3}$) ligands comprise $\ce{NiCl2(PPh3)2}$, hence this compound is borderline between the two geometries.
Steric effects also affect the equilibrium; larger ligands favoring the less crowded tetrahedral geometry.[1]
Reference
Greenwood, Norman N.; Earnshaw, Alan (1997). Chemistry of the Elements (2nd ed.).
|
[
"crypto.stackexchange",
"0000019937.txt"
] | Q:
Show that the equal difference property exits for a modified DES encryption system
My cryptology professor gave us this problem on a past homework assignment and I only managed to get one of the 3 parts correct. Needless to say, I want to know how to do the other two parts as well. The question is as follows:
Consider the following DES-like encryption system that operates on 16-bit strings.
The system takes the input and divides it into two 8-bit string $L_0$ and $R_0$.
One round of encryption starts with $L_{i-1}$ and $R_{i-1}$
and the output is $L_i=R_{i-1}$ and $R_i=L_{i-1}\oplus S(R_{i-1})\oplus K$,
where $K$ is the key.
The function S rotates the bits of $R_{i-1}$ to the right.
More precisely, if $R_{i-1}=b_0\|b_1\|b_2\|b_3\|b_4\|b_5\|b_6\|b_7$
then $S(R_{i-1})=b_7\|b_0\|b_1\|b_2\|b_3\|b_4\|b_5\|b_6$.
The two parts that I was not able to get are:
1) Explain briefly why if $A$ and $B$ are bit strings, then $S(A\oplus B)=S(A)\oplus S(B)$
2) If $M$ is the plaintext, let $E_K(M)$ denote the process of encrypting $M$ using one round of the above process. Show that $E_K$ has the equal difference property, namely that if $A\oplus B = C\oplus D$, then $E_K(A)\oplus E_K(B)=E_K(C)\oplus E_K(D)$.
Anyway, if someone could provide a complete explanation (answer included) on how to the 2 above questions, I would greatly appreciate it! Thanks in advance!
A:
For 1) you need to show that $S(X)$ is linear with respect to xor.
We can define $S(X)$ as:
$S(X) = (x_{7}, x_{0}, x_{1}, x_{2}, x_{3}, x_{4}, x_{5}, x_{6})$
And define $A \oplus B$ as:
$A \oplus B = (a_0 \oplus b_0, a_1 \oplus b_1,a_2 \oplus b_2,a_3 \oplus b_3,a_4 \oplus b_4,a_5 \oplus b_5,a_6 \oplus b_6,a_7 \oplus b_7,)$
So we have:
$S(A \oplus B) = (a_7 \oplus b_7,a_0 \oplus b_0,a_1 \oplus b_1,a_2 \oplus b_2,a_3 \oplus b_3,a_4 \oplus b_4,a_5 \oplus b_5,a_6 \oplus b_6)$
$=(a_{7}, a_{0}, a_{1}, a_{2}, a_{3} a_{4}, a_{5}, a_{6}) \oplus (b_{7}, b_{0}, b_{1}, b_{2}, b_{3} b_{4}, b_{5}, b_{6})$
Which by definition is:
$=S(A) \oplus S(B)$
For number 2) we'll first show that if there is some difference $D = A \oplus B$ then $E_k(D) = E_k(A) \oplus E_k(B)$.
We can define $E_K(M)$ as:
$M_R || (M_L \oplus S(M_R))$
So given:
$E_k(A) \oplus E_k(B)$
$=\big[A_R || (A_L \oplus S(A_R))\big] \oplus \big[B_R||(B_L \oplus S(B_R))\big]$
$=(A_R \oplus B_R)||(A_L \oplus S(A_R) \oplus B_L \oplus S(B_R))$
And using the property proved in 1) you get:
$=(A_R \oplus B_R)||(A_L \oplus B_L \oplus S(A_R \oplus B_R))$
And because $D = A \oplus B$:
$=(D_R||(D_L \oplus S(D_R))$
$=E_k(D)$
Now we can show the equal difference property holds:
$A \oplus B = C \oplus D$
$E_k(A \oplus B) = E_k(C \oplus D)$
$E_k(A) \oplus E_k(B) = E_k(C) \oplus E_k(D)$
|
[
"stackoverflow",
"0011108915.txt"
] | Q:
Avoid carriage returns in a TextView
I have a simple TextView and I want it to automatically define the font size to prevent returns.
is it possible?
A:
Here a component I've used in the past:
Auto Scale TextView Text to Fit within Bounds
This text view will resize the font size by size of the text in it. Try it
|
[
"salesforce.stackexchange",
"0000018682.txt"
] | Q:
Can I assign Aggregate SOQL Result directly to variable?
Salesforce documentation suggests that aggregrate soql results must first be assigned to an instance of the AggregateResult class, as shown below:
AggregateResult[] groupedResults = [SELECT AVG(Amount)aver FROM Opportunity];
Object avgAmount = groupedResults[0].get('aver');
I'm wondering, is it possible for a more elegant solution that assigns the aggregated field directly to a variable of the same type? EG:
mainAccount.Active_Total_Opps_Rollup__c = [SELECT SUM(Amount) FROM Opportunity WHERE AccountID IN :ID_Group];
Obviously what I've written gives an error, because the query returns a list of results and not a single value. But is there a way for me to compactly indicate that I want to return only the aggregated value?
A:
You cannot simplify the query, but you can the assignment...
Decimal avgAmount = (Decimal) [SELECT AVG(Amount)aver FROM Opportunity][0].get('aver');
Normally I would have said this was a little unsafe, since your always assuming you have one item in the result array the aggregate query returns. However I've just tested it and even if the object has no records in it you do get an a single aggregate result. However the value of 'aver' is null.
|
[
"stackoverflow",
"0023905698.txt"
] | Q:
Javascript object with jQuery event scope issue
I've got a draggable within my Pointer object in which I want to refer back to a method within my Pointer from the drag stop. However I run into a scope issue. Now I suppose I can use $.proxy(). But I still need the $(this) inside the drag stop to get the width and height(right?)
Can anyone tell me how I can call this.snapToClosestTile()(one of last rows in code) within my draggable.stop()?
function Pointer (obj) {
this.element = obj;
this.getSnapX = function () {
var newOffsetX = null;
for (var i in board.tiles) {
var tile = board.tiles[i];
var offsetX = tile.offset().left;
//Compensate a quarter of the width of the object. If the pointer overlaps with 25% or less; it snaps closer to where the pointers' center is.
var objOffsetX = this.element.offset().left - (this.element.width()*0.25);
if (lastOffsetX != null) {
if (objOffsetX >= lastOffsetX && objOffsetX < offsetX) {
newOffsetX = tile.offset().left;
return newOffsetX;
}
}
//Save a last offset to determine that the object is between the last known offset and the current offset.
this.lastOffsetX = offsetX;
}
return newOffsetX;
}
this.getSnapY = function () {
var newOffsetY = null;
for (var i in board.tiles) {
var tile = board.tiles[i];
var offsetY = tile.offset().top;
//Compensate a quarter of the height of the object. If the pointer overlaps with 25% or less; it snaps closer to where the pointers' center is.
var objOffsetY = this.element.offset().top - (this.element.height()*0.25);
if (lastOffsetY != null) {
if (objOffsetY >= lastOffsetY && objOffsetY < offsetY) {
newOffsetY = tile.offset().top;
return newOffsetY;
}
}
//Save a last offset to determine that the object is between the last known offset and the current offset.
this.lastOffsetY = offsetY;
}
return lastOffsetY;
}
this.lastOffsetY = null;
this.lastOffsetX = null;
this.snapToClosestTile = function (obj) {
var newOffsetX = this.getSnapX();
var newOffsetY = this.getSnapY();
//When snap positions are found, set the object to those positions. If not, use the drag-start data to reset the pointer to the initial drag-position
if (newOffsetX != null && newOffsetY != null) {
this.element.offset({left: newOffsetX, top: newOffsetY});
} else {
this.element.offset({left: jQuery(this).data('startX'), top: jQuery(this).data('startY')});
}
}
this.element.draggable({
containment: '.board_container',
start: function () {
//Set all pointers to z-index 1, than higher the current to 2 to always be on top
jQuery('.pointer').css('z-index', 1);
jQuery(this).css('z-index', 2);
//Set a start position in the data of the element to reset it to that place when the stop is out of bounds
jQuery(this).data('startX', jQuery(this).offset().left);
jQuery(this).data('startY', jQuery(this).offset().top);
},
stop: function (e, obj) {
//The dragged item is contained to the parent. The parent is as high as the board
//However; the container is wider than the board(because of the pointer list)
//Therefore there should be a check to verify that the dragged item was dragged inside the #board div's perimeter.
//If not; Reset it to its startX and startY defined in the start above.
//And while we're at it; check the top aswell. It never hurts i suppose.
var objectMaxPositionLeft = board.offset.maxPosX - jQuery(this).width();
var currentPositionLeft = obj.offset.left;
var objectMaxPositionTop = board.offset.maxPosX - jQuery(this).height();
var currentPositionTop = obj.offset.top;
if (currentPositionLeft > objectMaxPositionLeft || currentPositionTop > objectMaxPositionTop) {
jQuery(this).offset({left: jQuery(this).data('startX'), top: jQuery(this).data('startY')});
}
this.snapToClosestTile(jQuery(this));
}
});
}
A:
In most cases you define a variable with a copy of this:
function Pointer()
{
var that = this;
this.blah = function()
{
...snip...
that.foo(); // that represents 'this' inside Pointer()
...snip...
};
this.element.draggable({
stop: function()
{
...snip...
that.foo(); // also works here
...snip...
}
});
this.foo = function()
{
...snip...
};
}
This is assuming Pointer() is a valid constructor, of course... otherwise this may not mean what you think inside of Pointer().
Update to answer the question about prototype:
function Pointer()
{
}
Pointer.prototype.blah = function() { ... };
Pointer.prototype.foo = function() { ... };
...
Then you can create an instance of the Pointer declaration with:
var ptr = new Pointer();
The advantage, if you need 10 different Pointer objects, is that all those prototype functions do not get duplicated. If you have really large objects, that can become important. It also allows you to inherit an object from another.
I have a working example in the file named editor.js here:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/plugins/editor/
If you scroll down a bit, you'll see the tree of classes that I use. And also I verify my code with the Google Closure Compiler. It helps a lot avoid many basic mistakes.
|
[
"drupal.stackexchange",
"0000247440.txt"
] | Q:
How to add back to top using drupal behaviors?
I have added the following Drupal behaviors below to my main.js file which is already included in my theme and renders on the page with the correct main.js file. The purpose of this behavior is to scroll the user to the top of the page and it is not working. I cannot even get it to log an alert('clicked'). Need help figure out what i am missing.
main.js
Drupal.behaviors.scrollToTop = {
attach: function (context, setting) {
$('#back-to-top', context).on('click', function(){
alert('clicked'); //does not work
$('body,html').animate({scrollTop : 0}, 500); //does not work
});
}
};
html
<body>
<!-- assume this is at the bottom and there is more in the body -->
<a id="back-to-top" href="javascript:void(0)";><div>div is used to insert up arrow</div></a>
</body>
A:
Try wrapping it:
(function ($) {
Drupal.behaviors.scrollToTop = {
attach: function (context, setting) {
$('#back-to-top', context).on('click', function(){
$('body,html').animate({scrollTop : 0}, 500);
});
}
};
}(jQuery));
Had the same issue, AFAIK the wrapper is necessary to actually fire the behavior.
|
[
"stackoverflow",
"0004751815.txt"
] | Q:
Problem in installing PHP 5.3.5 with apache 2.2.17 ( apache crashes)
I am trying to install PHP 5.3.5 ( using non Threaded x86 msi installer ) on windows 7 running Apache 2.2.17.
After running the install program, Apache crashed.
Anyone facing this problem? This is the latest build of PHP which was released on 6th Jan.
A:
Found the reason. There is a bug in this version of PHP installer (php-5.3.5-Win32-VC6-x86.msi). It adds incomplete values to httpd.conf file. Here is more detail about the bug : http://bugs.php.net/bug.php?id=53696 and the fix.
|
[
"stackoverflow",
"0019977514.txt"
] | Q:
String.contains() when reading from file
I am reading from a file line by line and then I want to check if that string contains another string so I use String.contains method but it returns always false.
I have tried to split the input line (and then using String.contains or String.equals) since the word to be checked is the first of the line.
The string I want to check is <now> and doing the splitting I have noticed that even when the line contains it I get false.
The strange fact is the string is printed out correctly but its length is bigger than the string <now>(even if I used replace to be sure there were no spaces) and I guess that is my problem. I am thinking it depends on the encoding of file but if so, is there any solution?
The file is the output of another Program (Praat) so I can not save it in another way.
line = inFile2.nextLine();
String[] w = line.split("[\t\\s]");
String checking = w[0];
checking.replace(" ","");
checking.replace("/t","");
String st ="<now>";
System.out.println(!checking.equals(st)); //returns always true
System.out.println(st.length()); //returns 5
System.out.println(checking.length()); //returns 11
System.out.println(checking); //it prints <now> correctly
The string in input is like: <now> 236 62 elena information-relation
A:
Strings are immutable :
Note: The String class is immutable, so that once it is created a
String object cannot be changed. The String class has a number of
methods, some of which will be discussed below, that appear to modify
strings. Since strings are immutable, what these methods really do is
create and return a new string that contains the result of the
operation.
So it should be :
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
Or even better (method chaining) :
Checking = Checking.replace(" ","").replace("/t","");
Also please respect naming conventions.
A:
I solved re-saving the text file using UTF-8 encoding.
|
[
"stackoverflow",
"0001796085.txt"
] | Q:
Dot net 3.5:how to enable intellisense while writting xml file refering to defined schema?
I have defined a xml schema as below
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="PacketTemplate"
targetNamespace="http://tempuri.org/PacketTemplate.xsd"
elementFormDefault="qualified"
xmlns="http://tempuri.org/PacketTemplate.xsd"
xmlns:mstns="http://tempuri.org/PacketTemplate.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:group name="packetTemplate">
<xs:sequence id="packetTemplateSequence" >
<xs:element name="packetType" maxOccurs="1" minOccurs="1" nillable="false" >
<xs:complexType >
<xs:attribute name="packetCode" type="xs:string" use="required"></xs:attribute>
<xs:attribute name="packetTypeIncoming" type="xs:boolean" use="required"></xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="packetFieldInfo" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="fieldName" type="xs:Name" use="required"></xs:attribute>
<xs:attribute name="fieldNumber" type="xs:integer" use="required"></xs:attribute>
<xs:attribute name="conversionCode" type="xs:integer" use="required"></xs:attribute>
<xs:attribute name="fieldInUse" type="xs:boolean" use="required"></xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
now when i write xml file corresponding to this schema i am not able to use intellisense features like it should show all of possible tags in my file?
Beside that what should i do so that this xml file refer the schema file i have defined?
Xml file is as below.
<?xml version="1.0" encoding="utf-8" ?>
<packetTemplate>
<packetType packetCode="601" packetTypeIncoming="123" fieldInUse="true">
</packetType>
</packetTemplate>
A:
In Visual Studio you can open the *.xml file and in the properties window you can specify the schema file in the property Schemas.
That way Visual Studio should provide Intellisense, assuming the provided schema is valid.
You can check the W3Schools examples in how to create a XML schema.
|
[
"stackoverflow",
"0042223447.txt"
] | Q:
Android APK Size is mostly the Design Support libraries
So I've made a relatively simple app, a couple of pages and basic text in/out functions. I'm using Xamarin. My compiled code is a couple of hundered KB, but the app's total size, for say the ARM ABI, is 21.7MB, and when I break the APK open, it's the android support libraries that seem to be taking 50% of the size up. Can anyone advise on what I'm doing wrong?
Here's the root view:
And here's the assemblies folder:
A:
By default the Linker in Android release mode is set to Link SDK Only. You can strip more unused IL code from the assemblies by setting it to Link All Assemblies, but beware, the linker works on static code references, so any code usage ref'd by reflection would not be seen and removed.
You need to make sure you are throughly testing your release builds for faults related to this and use the various linker preservation techniques (Ref: Linking on Android)
Xamarin.Android Hello World app using Android.Support.V7 and Android.Support.V4
Link SDK Only
13M ./assemblies
├── [ 2988032] Xamarin.Android.Support.Compat.dll
├── [ 2398208] Xamarin.Android.Support.v7.AppCompat.dll
└── [ 1985024] mscorlib.dll
├── [ 1357312] Mono.Android.dll
├── [ 915456] System.Xml.dll
├── [ 809984] Xamarin.Android.Support.Media.Compat.dll
├── [ 737280] System.dll
├── [ 710656] Xamarin.Android.Support.Core.UI.dll
├── [ 426496] Xamarin.Android.Support.Fragment.dll
├── [ 265216] Xamarin.Android.Support.Core.Utils.dll
├── [ 114176] Xamarin.Android.Support.Vector.Drawable.dll
├── [ 93184] Java.Interop.dll
├── [ 75776] AppV4V7Size.dll
├── [ 49664] Xamarin.Android.Support.Animated.Vector.Drawable.dll
├── [ 37888] Xamarin.Android.Support.v4.dll
├── [ 37888] System.Core.dll
├── [ 11264] System.Runtime.dll
├── [ 5632] System.Runtime.InteropServices.dll
├── [ 5632] System.Reflection.dll
├── [ 5120] System.Threading.dll
├── [ 5120] System.Runtime.Serialization.dll
├── [ 4608] System.Runtime.Extensions.dll
├── [ 4608] System.Reflection.Extensions.dll
├── [ 4608] System.Diagnostics.Debug.dll
├── [ 4608] System.Collections.dll
├── [ 4608] System.Collections.Concurrent.dll
├── [ 4096] System.Linq.dll
Link All Assemblies (9MB savings...)
3.9M ./assemblies
└── [ 1880576] mscorlib.dll
├── [ 785408] Mono.Android.dll
├── [ 392192] Xamarin.Android.Support.v7.AppCompat.dll
├── [ 222720] System.dll
├── [ 187392] Xamarin.Android.Support.Fragment.dll
├── [ 120320] Xamarin.Android.Support.Compat.dll
├── [ 115712] Xamarin.Android.Support.Media.Compat.dll
├── [ 92160] Java.Interop.dll
├── [ 75776] AppV4V7Size.dll
├── [ 52736] Xamarin.Android.Support.Core.UI.dll
├── [ 39936] Xamarin.Android.Support.Core.Utils.dll
├── [ 37376] System.Core.dll
├── [ 11264] System.Runtime.dll
├── [ 7680] Xamarin.Android.Support.v4.dll
├── [ 5632] System.Runtime.InteropServices.dll
├── [ 5632] System.Reflection.dll
├── [ 5120] Xamarin.Android.Support.Animated.Vector.Drawable.dll
├── [ 5120] System.Threading.dll
├── [ 5120] System.Runtime.Serialization.dll
├── [ 4608] Xamarin.Android.Support.Vector.Drawable.dll
├── [ 4608] System.Runtime.Extensions.dll
├── [ 4608] System.Reflection.Extensions.dll
├── [ 4608] System.Diagnostics.Debug.dll
├── [ 4608] System.Collections.dll
├── [ 4608] System.Collections.Concurrent.dll
├── [ 4096] System.Linq.dll
|
[
"chemistry.stackexchange",
"0000098946.txt"
] | Q:
Malic acid 3-step synthesis
I was quite puzzled by the answer for this question in my Carboxylic Acids and Derivatives tutorial question set. It is question 6 (a), on the synthesis of malic acid, as shown in the image below.
The idea for the synthesis is to convert the $\ce {Br}$ to $\ce {CN}$ and the carbonyl group to a cyanohydrin, then convert the $\ce {CN}$ to $\ce {COOH}$. I have no disputes about the last step, which is to heat with aqueous hydrochloric acid, or some other mineral acid. However, what I proposed was to perform the two initial conversions in one step, which is to heat the compound with $\ce {KCN (aq)}$ and ethanol. Would that not allow for both the nucleophilic addition, as well as the substitution, to take place, all in one step?
The proposed answer for steps 1 and 2 was to first heat with reflux, with ethanolic $\ce {KCN}$, then react with $\ce {HCN (aq)}$, with trace $\ce {KCN}$, or $\ce {NaOH}$ as catalyst, under temperature of 10-20 degrees C. Is it really necessary to perform the initial two conversions in two separate steps?
A:
I have clarified with my chemistry tutor and it appears that performing the substitution and the addition as two separate steps with two separate sets of conditions is absolutely necessary. The most important reason would be the temperature, which is also the most stark difference between the two different set of conditions.
Due to entropy considerations, addition should ideally be carried out at low temperatures. Thus, if we would like to have the addition of $\ce {HCN}$ to the substrate, it should be done at much lower temperatures as the reaction has a negative entropy change. However, the substition of $\ce {Br}$ by $\ce {CN}$ does not need such low temperlatures and should be done at higher temperatures to provide enough energy of activitation to break the carbon-bromide bond.
|
[
"stackoverflow",
"0055883152.txt"
] | Q:
Forcing sign of a bit field (pre-C++14) when using fixed size types
Skip to the bolded part for the essential question, the rest is just background.
For reasons I prefer not to get into, I'm writing a code generator that generates C++ structs in a (very) pre-C++14 environment. The generator has to create bit-fields; it also needs the tightest possible control over the behaviour of the generated fields, in as portable a fashion as possible. I need to control both the size of the underlying allocation unit, and how signed values are handled. I won't get into why I'm on such a fool's errand, that so obviously runs afoul of Implementation Defined behaviour, but there's a paycheck involved, and all the right ways to do what needs to be done have been rejected by the people who arrange the paychecks.
So I'm stuck generating things like:
int32_t x : 11;
because I need to convince the compiler that this field (and other adjacent fields with the same underlying type) live in a 32 bit word. Generating int for the underlying type is not an option because int doesn't have a fixed size, and things would go very wrong the day someone releases a compiler in which int is 64 bits wide, or we end up back on one where it's 16.
In pre-C++14, int x: 11 might or might not be an unsigned field, and you prepend an explicit signed or unsigned to get what you need. I'm concerned that int32_t and friends will have the same ambiguity (why wouldn't it?) but compilers are gagging on signed int32_t.
Does the C++ standard have any words on whether the intxx_t types impose their signedness on bit fields? If not, is there any guarantee that something like
typedef signed int I32;
...
I32 x : 11;
...
assert(sizeof(I32)==4); //when this breaks, you won't have fun
will carry the signed indicator into the bitfield?
Please note that any suggestion that starts with "just generate a function to..." is by fiat off the table. These generated headers will be plugged into code that does things like s->x = 17; and I've had it nicely explained to me that I must not suggest changing it all to s->set_x(17) even one more time. Even though I could trivially generate a set_x function to exactly and safely do what I need without any implementation defined behaviour at all. Also, I've very aware of the vagaries of bit fields, and left to right and right to left and inside out and whatever else compilers get up to with them, and several other reasons why this is a fool's errand. And I can't just "try stuff" because this needs to work on compilers I don't have, which is why I'm scrambling after guarantees in the standard.
Note: I can't implement any solution that doesn't allow existing code to simply cast a pointer to a buffer of bytes to a pointer to the generated struct, and then use their pointer to get to fields to read and write. The existing code is all about s->x, and must work with no changes. That rules out any solution involving a constructor in generated code.
A:
Does the C++ standard have any words on whether the intxx_t types impose their signedness on bit fields?
No.
The standard's synopsis for the fixed-width integers of <cstdint>, [cstdint.syn] (link to modern standard; the relevant parts of the synopsis looks the same in the C++11 standard) simply specifies, descriptively (not by means of the signed/unsigned keywords), that they shall be of "signed integer type" or "unsigned integer type".
E.g. for gcc, <cstdint> expose the fixed width integers of <stdint.h>, which in turn are typedefs to predefined pre-processor macros (e.g. __INT32_TYPE__ for int32_t), the latter being platform specific.
The standard does not impose any required use of the signed or unsigned keywords in this synopsis, and thus bit fields of fixed width integer types will, in C++11, suffer the same implementation-defined behavior regarding their signedness as is present when declaring a plain integer bit field. Recall that the relevant part of [class.bit]/3 prior to C++14 was (prior to action due to CWG 739):
It is implementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int, long, or long long bit-field is signed or unsigned. ...
Indeed, the following thread
How are the GNU C preprocessor predefined macros used?
shows an example where e.g. __INT32_TYPE__ on the answerer's particular platform is defined with no explicit presence of the signed keyword:
$ gcc -dM -E - < /dev/null | grep __INT
...
#define __INT32_TYPE__ int
|
[
"stackoverflow",
"0002562396.txt"
] | Q:
How to get file attributes in ColdFusion 7?
I cannot find a function that tells me the attributes of a given file. I specifically need to get the file's size. How do I find this info.?
edit:
I think I found an answer, just not the answer I was hoping for:
So far till ColdFusion 7, there was no
good way to find information like
size, last modified date etc about a
file. Only way you could do that was
to use cfdirectory tag to list the
directory, get the query from it, loop
over the query until you hit the
desired file and then fetch the
required metadata.
http://coldfused.blogspot.com/2007/07/new-file-io-in-coldfusion-8-part-ii.html
Anyone know of a better way?
A:
I believe cfdirectory is your simplest answer - but note, you can use the filter attribute as your filename, and you won't have to loop over the result.
A:
<cffunction name="getFileSize">
<cfargument name="filepath">
<cfreturn createObject("java","java.io.File").init(Arguments.filepath).length()>
</cffunction>
|
[
"stackoverflow",
"0023616093.txt"
] | Q:
Countdown timer - How to avoid resetting of timer
I have to add a countdown timer in my online testing website, but everytime I click on the next or any other button, the timer resets. What should I do to avoid that? Here is the code I used
<span id="countdown-1">10 seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
alert('time finished');
return false;
document.getElementById(id).style.display = 'none';
}
}
A:
Assuming you know to what date you are counting down to.
<?php
$dueTime = mktime(0,0,0, 1, 1, 2015);
$secondsRemaining = $dueTIme - time();
?>
<span id="countdown-1"><?php echo $secondsRemaining; ?> seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
alert('time finished');
return false;
document.getElementById(id).style.display = 'none';
}
}
|
[
"stackoverflow",
"0032215939.txt"
] | Q:
Change background image for TextView at runtime
I'm developing my first app and I need to display a larger image of a thumbnail that I click on to be set as the background for a text in a different fragment.
I'm trying to change the background image for a textview using
textView.setBackground(getResources().getDrawable(R.drawable.user_placeholder_image));
In order to minimize the bandwidth usage, I was hoping to download the backdrop image only when the thumbnail is clicked. In other words, is there a way to store resources to the drawable folder at runtime? If not, then is there any other alternative?
Thanks for the help!
A:
You can not store them in your resources at runtime. However you can always store them as bitmaps. Take a look at my example.
//OnClick
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("your url");
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Instead of setting the image to your ImageView, you could modify the code to store it.
|
[
"stackoverflow",
"0025493569.txt"
] | Q:
JDK instead of or in addition to JRE?
I have a question about the two versions of Java: JRE (Java Runtime Environment) and JDK (Java Development Kit).
Is the JDK installed and used in addition to the JRE or is it used instead of the JRE so that one could install the JDK as a JRE with simply more functions for developers?
A:
You must understand that JDK includes JRE. JRE is Java Virtual Machine where your Java programs run on whereas JDK is full featured Software Development Kit for Java
From the docs:
JRE (Java Runtime environment):
It is an implementation of the Java Virtual Machine* which actually executes Java programs.
Java Runtime Environment is a plug-in needed for running java programs.
The JRE is smaller than the JDK so it needs less Disk space.
The JRE can be downloaded/supported freely from https://www.java.com
It includes the JVM , Core libraries and other additional components to run applications and applets written in Java.
JDK (Java Development Kit)
It is a bundle of software that you can use to develop Java based applications.
Java Development Kit is needed for developing java applications.
The JDK needs more Disk space as it contains the JRE along with various development tools.
The JDK can be downloaded/supported freely from https://www.oracle.com/technetwork/java/javase/downloads/
It includes the JRE, set of API classes, Java compiler, Webstart and additional files needed to write Java applets and applications.
|
[
"math.stackexchange",
"0001323976.txt"
] | Q:
Diffeomorphism $\phi : M \to M$. Why can it be written like this?
Let $\phi : M \to M$ be a diffeomorphism from $M$ to $M$. Let $v \in T_pM$ and $f$ a differentiable function near $\phi(p)$. Then we have
$$ \Big( d\phi (v) (f) \Big)\phi(p) = v(f \circ \phi)(p) $$
Why is this true?
The proof is given in the book (Carmo page 26) as following
$$ \Big( d\phi (v) (f) \Big)\phi(p) = \frac{d}{dt}(f \circ \phi \circ \alpha)\Big|_{t=0} = v(f \circ \phi)(p) $$
where of course $\alpha : I \to M$ is a differentiable curve with $\alpha(0)=p$ and $\alpha'(0)=v$. I do not understand how this is true. I only know that $d\phi = \beta'(0) = \phi(\alpha'(0))$.
I am very confused on the way he writes the above stuff and I would appreciate some clarifications.
A:
Expanding my comment, as I have found some online text, by who I assume to be the same author. Using (most of) your notation, his definition of the tangent map was $$ (d\phi)_p(v)=\left.\frac{d}{dt}(\phi\circ\alpha)\right|_{t=0}. $$ This is our definition. Heuristically this says: "The pushforward of a tangent vector at $p$ is the tangent vector at $\phi(p)$ you can get by composing the curve your original tangent vector is tangent to with the map $\phi$ and taking that curve's tangent vector."
We know that if $\gamma$ is a curve to which $u$ is tangent at $\gamma(0)$, then $u[f]=d/dt(f\circ\gamma)|_{t=0}$.
In our case we know from the definition that $(d\phi)_p(v)$ is tangent to $\phi\circ\alpha$, so $$ (d\phi)_p(v)[f]=\left.\frac{d}{dt}(f\circ\phi\circ\alpha)\right|_{t=0}. $$
But rather than interpreting the right hand side as $f$ composed with $\phi\circ\alpha$, you can interpret it as $f\circ\phi$ (which is a scalar field) composed with $\alpha$. So, by the definition of tangent vectors, $$ \left.\frac{d}{dt}(f\circ\phi\circ\alpha)\right|_{t=0}=\alpha'(0)[f\circ\phi]=v[f\circ\phi]. $$
|
[
"math.stackexchange",
"0000994471.txt"
] | Q:
Why does this method of solution for this system of equations yield an incorrect answer?
We are required to solve the following system of equations:
$$x^3 + \frac{1}{3x^4} = 5 \tag1$$
$$x^4 + \frac{1}{3x^3} = 10 \tag2$$
We may multiply $(1)$ by $3x^4$ throughout and $(2)$ by $3x^3$ throughout (as $0$ is not a solution we may cancel the denominators) to yield.
$$3x^7 + 1 = 15x^4 \tag3$$
$$3x^7 + 1 = 30x^3 \tag4$$
Subtracting the two:
$$15x^4 - 30x^3 = 0$$
$$\implies x^3(x-2) = $$
As $0$ is not a solution we choose $x=2$.
But putting $x=2$ in the original equations does not satisfy them. How come?
A:
Solutions to (3) and (4) are equivalent to solutions of $15x^4 - 30x^3 = 0$ and one of (3) or (4). But the solution $x = 2$ to $15 x^4 - 30x^3 = 0$ does not satisfy (3) [or equivalently (4)], as $3*2^7 + 1 \neq 15*2^4$.
You shouldn't be surprised that a system of two equations in one unknown may be inconsistent, i.e. not have any solutions.
|
[
"stackoverflow",
"0018110916.txt"
] | Q:
Why is msgid_plural necessary in gettext translation files?
I've read the GNU Gettext manual about Translating plural forms and see its example:
#, c-format
msgid "One file removed"
msgid_plural "%d files removed"
msgstr[0] "%d slika je uklonjena"
msgstr[1] "%d datoteke uklonjenih"
msgstr[2] "%d slika uklonjenih"
Why is msgid_plural different from msgid, and doesn't that defeat the purpose of having translations be aware of plural forms?
I'd think that I could do something like this (for English):
#, c-format
msgid "X geese"
msgstr[0] "%d goose"
msgstr[1] "%d geese"
#, c-format
msgid "sentence_about_geese_at_the_lake"
msgstr[0] "There is one goose at the lake."
msgstr[1] "There are %d geese at the lake."
(using just one msgid).
Then in my code, I'd have something like:
<?php echo $this->translate('X geese', $numberA); ?>
<?php echo $this->translate('sentence_about_geese_at_the_lake', $numberB); ?>
If $numberA is 3, it would say "3 geese."
If $numberB is 0, the next line would say "There are 0 geese at the lake."
(because for English, the rule is (n != 1), so plural is used for any number that equals 0 or greater than 1).
It seems redundant for me to be required to specify 2 msgids for the same collection of phrases.
Thanks for your help!
A:
One of the ideas behind gettext is that the msgid is extracted from source files to create POT files, which are used as base for translations stored in PO files, and later compiled to MO files. A msgid is also used if no suitable translation is found.
A msgid is not a "key" that is non-readable by users; it is a real phrase that can be used in the program. So when in your code you request a translation for a plural (pseudocode here):
ngettext("One file removed", "%d files removed", file_count)
...these two strings will be used a) to extract messages from the source code; these messages will serve as guide for translators b) as the default strings when no suitable translation is found for the current locale.
That's why a plural string has two msgid: to show how they are defined in the source program (for translators) and to be used as default (when no translation exists).
In other localization systems, like Android String Resources or Rails YAML files, it works like you imagined -- the equivalent to a msgid is a single "key" even for plurals, but then the real phrase is not used in the source code, and defining translations is a two-steps action even for the original language.
|
[
"stackoverflow",
"0063360033.txt"
] | Q:
How do I create a download file link in React?
I have a question, I'm working on a project of my own, and I've set up some buttons in React, but when I click on my download button I get back nothing but my website. How do I fix this?
Here's the code for my button:
<Button className="resume__Button2" to="" download="./files/Chris_Warren.pdf" component={Link}>My Resume</Button>
Any ideas?
A:
when you are using React Router, you have to use this:
<Link to="/files/Chris_Warren.pdf" target="_blank" download>Download</Link>
or Button. both of them is possible but you have to note that "/files/Chris_Warren.pdf" is inside your public folder.
|
[
"math.stackexchange",
"0003363220.txt"
] | Q:
Labelling of the elements of $\Theta \le S_n$ such that also $\Gamma_\Theta \le S_n$
Let $\Theta=\{\theta_1,\dots,\theta_n\}$ be a subgroup of $S_n$, the symmetric group of degree $n$. Let's define $\Gamma_\Theta=\{\gamma_1,\dots,\gamma_n\}$ by:
$$\gamma_j(k):=\theta_k(j), \quad \forall j,k=1,\dots,n \tag 1$$
Lemma. $\Gamma_\Theta \subseteq S_n$ if and only if:
$$\theta_j(i)=\theta_k(i) \Rightarrow \theta_j=\theta_k \tag 2$$
Proof. If $\gamma_i \in S_n$, then $\theta_j(i)=\theta_k(i) \Rightarrow \gamma_i(j)=\gamma_i(k) \Rightarrow j=k \Rightarrow \theta_j=\theta_k$, so that $(2)$ holds. Conversely, if $(2)$ holds, then $\gamma_i(j)=\gamma_i(k) \Rightarrow \theta_j(i)=\theta_k(i) \Rightarrow \theta_j=\theta_k \Rightarrow j=k$, so that $\gamma_i$ is injective and then bijective. $\quad \Box$
Now, I suppose that there is some (unique?) labelling of the elements of $\Theta$ such that $\Gamma_\Theta \le S_n$; I've verified it directly for $n=3$ (and then necessarily $\Theta=\{(123),(231),(312)\}$ [*]), but I can't prove it in general.
[*] for example, $\theta_1=(123), \theta_2=(231), \theta_3=(312)$ works, while $\theta_1=(123), \theta_2=(312), \theta_3=(231)$ doesn't.
A:
Your Lemma answers your question.
There is a labelling with $\Gamma_\Theta\le S_n$ if and only if $\Theta$ is equivalent to a left regular representation of itself.
Proof:
$(\Rightarrow)$
$\theta_j(i)=\theta_k(i)\Rightarrow\theta_j=\theta_k$ is equivalent to ${\rm Stab}_\Theta(i)=1$, so $\Theta$ is semiregular. But $|\Theta|=n$ so the orbit-stabiliser theorem implies that $\Theta$ is semi-regular if and only if it is regular.
$(\Leftarrow)$
If $\Theta$ is a left regular representation of itself then $\Gamma_\Theta$ is the right regular representation of $\Theta$ (in particular $\Theta\cong\Gamma_\Theta$).
|
[
"stackoverflow",
"0019277584.txt"
] | Q:
Uploading or just archiving an app for a client
I know this has been talked before, but I don't know if this changes with recent changes in the App Store.
I'm a freelance developer, and as such I develop apps for many different clients, each of which have their own Apple Developer accounts to sell their apps on the App Store.
I know I can't upload the app myself for my client (not without their private key) I'm looking for an "easy" way to get the app on the App Store with as less effort as possible for the client side.
Options I can think of:
Getting the private key and credentials for the client and upload it for them. But I would like to avoid that.
Client adds me as a member of their iOS team, set me as a developer for the app and I download the provisioning profiles and somehow send them a file they can resign and upload to the store.
I upload the app to my account and then use the new transfer funcionality to put it under the client name.
I don't know, there HAS to be a way, hasn't it?
EDIT:
I seem to have found a way, its described in my answer.
A:
I'm sorry I didn't accept any of the answers yet, but I've been trying some stuff and I think I found a way, a little strange and probably not optimal, but it could work and I would like to share it with you to see if you think it's ok.
First: I'm a developer with my own Apple ID and developer certificate. I have my own apps on the app store.
Second: I also make client work and then I want to upload and manage the apps I do for them, to a certain extent.
Third: My client has to have their own developer account and it has to be a company account, which will allow them to manage teams.
This is what I think that works:
I ask my client to add me to their iOS Developer Team as an "admin". This is done through the member center. This allows me to create distribution certificates and distribution provisioning profiles, as stated in here.
After I accept the invitation (can't remember if I really have to) I log into the member center. It will ask me to select the team I want to use for my session (my own team or one of my clients'). I choose my client's team.
I go to Certificates and create a new Certificate for Production->App Store and Ad Hoc (I think there's a max of two per account, so if there are already two of them this option will be grayed out)
I have to upload a CSR file generated from my computer's keychain, following on screen instructions, and then my certificate is ready to download and use.
While I'm on member center I generate my AppID and then go to Provisioning Profiles and generate a new Distribution Profile for the App Store with my AppID and for the certificate just created.
That's it for member center, now I can download the distribution profile for the app I'm am developing for my client. Or let XCode 5 manage it.
Then I want to upload the app to the store and manage it with iTunes Connect with my own account.
I ask the client to iTunes Connect -> Manage Users -> iTunes Connect User and add me with a Technical role. This allows me to manage apps, but I wont see anything about banks, contracts, payments...
The problem with point 1 here is I already have an iTunes Connect account for myself with my email address and you can't have two iTunes Connect accounts linked to one email address. I could use a different address, but as I'm using gmail, I just use an alias. I give them the address: [email protected]
Once invited, I receive an activation mail and then I can log into iTunes Connect with that address and create apps and set them ready to upload.
Then I just have to go to Xcode, select my client's code signing identity (which is the certificate I created), the apps distribution provisioning profile (I created earlier too), archive, validate and submit to the app store with my alias for this client.
I've just tested it and it works.
It's not yet an optimal solution because when logging into iTunes Connect I can see every other app my client has and I could, potentially, delete something. But still, I think is a pretty good one for clients with no knowledge of XCode (or no interest in doing all this) but also wanting to keep their credentials and private keys secret.
|
[
"salesforce.stackexchange",
"0000178162.txt"
] | Q:
The formula expression is invalid: Syntax error. Missing ')'
I'm working on a custom formula but I'm getting a syntax error and I can't figure out the error. Essentially what I'm trying to do is a sign a value to a custom field based on amount? Thank you for your help in advance for your help. We want to be able to show $0 if $0 is entered. My formula is below:
IF(X > $1,000, "$5",
IF(X > $500, "$4",
IF(X > $100,"$3",
IF(X > $10, "$2",
IF(X > $1,"$1",
IF(X > $0,"$0", Null)))))
)
)
)
)
)
)
A:
Hopefully, your formula will be like this:
IF(X > $1,000, "$5",
IF(X > $500, "$4",
IF(X > $100,000,"$3",
IF(X > $10, "$2",
IF(X > $1,"$1",
IF(X < $1,"$0", Null)
)
)
)
)
)
|
[
"english.stackexchange",
"0000116587.txt"
] | Q:
Origin of "no." abbreviation in meaning of "number"?
I Russian speaker and we have № sign for American #.
But I surprised that there are uses of No. abbreviation as shortened form of number.
What the origin of "no." abbreviation in meaning of "number"?
Because it must be nu or num... Is that come from Latin?
A:
The "no." abbreviation of number is Latin in origin, a short form of numero. See http://latin-phrases.co.uk/abbreviations/ for other examples of Latin abbreviations.
|
[
"stackoverflow",
"0007042560.txt"
] | Q:
How can I test client side coffeescript/js using node with expresso/jasmine/
I have a web app where the client side stuff is written with coffeescript and loaded with require.js.
I would like to be able to isolate and test this stuff using a node based test runner such as expresso (although other suggestions are welcome) so that I can integrate the client side testing with our CI server - which is currently Team City.
Here's my directory set up:
.
├── coffee
│ ├── models
│ ├── node_modules
│ │ └── expresso
│ ├── spec
│ ├── tests
│ └── views
├── static
│ └── js
│ ├── lib
│ ├── models
│ ├── tests
│ └── views
These are hooked up using require.js like so:
deps = [
"lib/backbone", "models/websocket_collection", "/static/js/lib/date.js"
]
define(deps, (Backbone, ws) ->
# module code and exports here
And loaded into the browser like so:
<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="my_mod" src="/static/js/my_mod.js"></script>
In an idea world now I'd like to be able to have a test module that looks like:
{Model1, Model2} = require "models/some_module"
exports.test_a = ->
assert.equal # etc etc
I have several problems (having not really used node server side except when I played with zombie.js)
How do I tell node where all of my plain javascript dependencies are (in static/js/lib) some of these are as downloaded, but backbone.js has been marked up with require.js define stuff like so
define(function(require, exports, module) {
(function(){
How do I actually run the tests? I've tried r.js (which as I understand it is supposed to be a bridge between browser side require and node's require)
the problem I'm getting is:
ReferenceError: define is not defined
I've also tried to require("allplugins-require") which is the script I load browser side to collect all of my client code, but that seems to break node's require.
Is anybody doing this?
If you're not doing this how are you testing your code (bonus points for integration with CI)?
Any alternatives to require.js for managing client side dependencies that might play a bit better on the server side?
I'd be very happy to hear alternative approaches that people are using.
Thanks,
Ben
A:
The docs for running requirejs via r.js in node are here. In particular, r.js replaces node's require with its own. It can load node-only packages/modules that are installed via npm as long as the npm-installed modules are not visible to the require.js config.
The other caveat is that r.js needs to be a sibling file to the main.js, the top level app js file that is run in the node environment.
The latest code for r.js will support loading requirejs as a node module (as in require('requirejs') and that will give a better integration story. That change will be in the 0.26.0 release.
A:
I spent a long time trying to get this to work and eventually gave up. I did get it working, by referencing all of my require.js dependencies in a global variable and using that for the node.js tests, but the design was so ugly that I felt that I had defeated the point.
My current approach is:
write my JavaScript modules as CommonJS modules
Use the Jasmine BDD node integration to test my modules server-side
Use stitch to make the CommonJS modules work client-side
This is working well for me, with the following caveats:
Client-side debugging is difficult because stitch concatenates all my scripts. I found that leaving out libraries like jQuery from the stitch configuration helped with this.
I don't have any way to debug server-side. There is a node.js debugger but it has not worked with the last few versions of node.
|
[
"serverfault",
"0000026883.txt"
] | Q:
Windows Event Log Rotation?
Windows Server 2003.
Is there any way to easily rotate event logs (or automatically clear and save)? I'm doing a bit of auditing on this machine and my security log gets real big real quick and every couple of weeks I have to remember to save and clear it out.
Yeah I could rely on backup jobs and enable overwriting...but it would be nicer if I could just get Windows to automatically save and clear the log when it's nearing capacity.
A:
It seems like most people don't know about this feature, but Windows will rotate the log files automatically if so-configured. Look for "AutoBackupLogFiles" in this file.
You can configure this on a server-for-server basis, but that's tedious for a large number of servers. I created an Administrative Template to set this on server computers, and then scripted a startup script to add a scheduled task to periodically pick up, ZIP, and move the log files to a retention location. It worked really well, and was cheap!
http://mx02.wellbury.com/misc/EventLogPolicy.adm
|
[
"stackoverflow",
"0037946831.txt"
] | Q:
Trigger is not working on jquery-steps?
plugin which I used is http://www.jquery-steps.com/Examples#advanced-form (you can look at clicking by code to see)
and I want to make custom button or trigger but my trigger function is not working on this plugin why that ?
my jquery codes
$(document).ready(function(){
$('#go-next').click(function(){
$('a[href="#next"]').trigger('click');
})
})
A:
It worked for me,
$(document).ready(function(){
$('#go-next').click(function(){
$('a[href="#next"]').trigger('click');
});
$('a[href="#next"]').click(function(){
alert('d');
});
});
<body>
<a id="go-next" href="#">gonext</a>
<a id="next" href="#next">next</a>
</body>
|
[
"stackoverflow",
"0013413383.txt"
] | Q:
give the input format when converting a date
I read the date from a file to a variable. The date has the format ddmmyyyy. It has to be converted to yyyy-mm-dd
I already searched this forum and got this far :
date -d '$DATE' +%F
The problem is the input format is not recognised. Is there any way I can specify the input date format?
On an other forum I found : date -d "${OLD_DATE}" -D "%d%m%Y" +%F
where -D should specify the input format but this doesn't work. But -D is unknown.
thanks for the help and sorry for my English.
A:
You could to it like this:
echo "DDMMYYYY" | awk 'BEGIN {OFS="-"} {print substr($1,5,4), substr($1,3,2), substr($1,1,2)}'
Output:
YYYY-MM-DD
|
[
"stackoverflow",
"0062003690.txt"
] | Q:
ffmpeg difference when using -lavfi or -filter_complex
I've started to use ffmpeg recently. I have been using only the -filter_complex flag to apply filters. I stumbled upon this SO question:
FFmpeg: How to convert horizontal video 16:9 to vertical video 9:16, with blurred background on top and bottom sides
A ffmpeg maintainer answers it using the -lavfi flag:
ffmpeg -i input.mp4 -lavfi "[0:v]scale=iw:2*trunc(iw*16/18),boxblur=luma_radius=min(h\,w)/20:luma_power=1:chroma_radius=min(cw\,ch)/20:chroma_power=1[bg];[bg][0:v]overlay=(W-w)/2:(H-h)/2,setsar=1" output.mp4
I tried to change -lavfi flag to -filter_complex:
ffmpeg -i input.mp4 -filter_complex "[0:v]scale=iw:2*trunc(iw*16/18),boxblur=luma_radius=min(h\,w)/20:luma_power=1:chroma_radius=min(cw\,ch)/20:chroma_power=1[bg];[bg][0:v]overlay=(W-w)/2:(H-h)/2,setsar=1" output.mp4
The result is the same and didn't notice a perf change.
Is there a difference when using either flags?
A:
From the FFmpeg documentation:
-lavfi filtergraph (global) Define a complex filtergraph, i.e. one with arbitrary number of inputs and/or outputs. Equivalent to
-filter_complex.
|
[
"stackoverflow",
"0049374120.txt"
] | Q:
How to split a string by character by one or larger index
The split method for strings only takes a parameter for the delimiter, but how do I easily split by every (or every other, etc) letter? This method works to split by every letter, but seems clumsy for a simple task.
a=' '.join(string.ascii_lowercase).split()
I suppose a function could do this:
def split_index(string,index=1):
split=[]
while string:
try:
sect = string[:index]
string = string[index:]
split.append(sect)
except IndexError:
split.append(string)
return split
print(split_index('testing')) # ['t', 'e', 's', 't', 'i', 'n', 'g']
print(split_index('testing',2)) # ['te', 'st', 'in', 'g']
I am surprised if no one has wished for this before, or if there is not a simpler built in method. But I have been wrong before. If such a thing is not worth much, or I have missed a detail, the question can be deleted/removed.
A:
Strings are iterables of characters, so splitting it into characters is as simple as iterating over it. One way of doing that is just giving it to the list() built-in:
list("testing") # ['t', 'e', 's', 't', 'i', 'n', 'g']
The docs also provide a recipe for a grouper() method that will take an iterable and group it into chunks of the given size, as strings are iterables, this just works on them. This can be very efficient as it is lazy and utilises the fast itertools functions:
import itertools
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
E.g:
groups = list(grouper("testing", 2)) # [('t', 'e'), ('s', 't'), ('i', 'n'), ('g', None)]]
["".join(char for char in group if char) for group in groups] # ['te', 'st', 'in', 'g']
Obviously, if you are just iterating over the characters, you don't need to make a list - just iterate straight over the string or the grouper() iterable.
|
[
"stackoverflow",
"0039427675.txt"
] | Q:
application.properties outside jar file how to
As stated in spring-boot-reference:
On your application classpath (e.g. inside your jar) you can have an
application.properties that provides a sensible default property value
for name. When running in a new environment, an application.properties
can be provided outside of your jar that overrides the name
I place a duplicated application.properties with overridden name on the same path as jar file, however when running the application with:
java -jar target/myproject-0.0.1-SNAPSHOT.jar
The name value is not overridden, it still refers to the one inside application.properties inside jar file. I also tried:
java -Dspring.config.location=/target/application.properties -jar target/myproject-0.0.1-SNAPSHOT.jar
But it does not work, please help.
Edit
When I change the current directory to target and run it, it works.
java -jar myproject-0.0.1-SNAPSHOT.jar
Why? Why cannot be outside the path and run it?
A:
It doesn't work because you are trying to launch the jar from another folder: spring boot looks for files/folder relative your current folder.
You can:
1) copy application.properties either in ./ or ./config/, relative to your current folder.
2) Or specify -Dspring.config.location:
$ java -Dspring.config.location=target/application.properties -jar target/myproject-0.0.1-SNAPSHOT.jar
|
[
"space.stackexchange",
"0000039342.txt"
] | Q:
Why is the Space Shuttle's External Tank fuelled through the Orbiter's main engine plumbing system?
This answer states that Space Shuttle's External Tank (ET) was fuelled (this process is known as Tanking) through the Orbiter's main engine plumbing system with the Tail Service Masts (TSM). One delivered LH2 and the other delivered LOX.
For reference, here's a picture of the TSM fuelling Space Shuttle Atlantis.
However why not just directly fuel the ET instead of the fuel and oxidizer going through the orbiter. It seems like the orbiter's fuel plumbing system would be a lot more complex with fuel going from the TSM, into the orbiter, and then into the ET. Not only that, but the LOX had to be pumped up to where the LOX tank was located (in the upper half of the ET) whereas if it was directly fuelled into the ET, the pipes can be pumped upward in the tower possibly saving weight on the ET by not having a LOX feed-line.
Question: So what are the advantages or reasons that got NASA to fuel the ET through the orbiter instead of directly fuelling the ET?
A:
I don't have a great reference for this, but it was to reduce cost on the throw-away External Tank.
By using the same interface into the Orbiter used to supply propellants to the main engines, the cost and complexity of adding a dedicated loading interface to the tank was avoided.
It was not a tremendous complexity hit to the Orbiter Main Propulsion system plumbing. Basically "tees" and valves were added which interfaced the feedlines running from the tank to the engines, to the umbilical disconnects that interfaced with the Tail Service Masts.
(From the Ascent Pocket Checklist, fill lines highlighted)
As the only disposable major element of the system, there was great emphasis placed on cost of the tank. This is clear from even a skim of Lessons Learned From Space Shuttle External Tank Development - A Technical History of the External Tank - although the specific case of lacking a dedicated loading interface is not addressed in the document.
|
[
"serverfault",
"0000108473.txt"
] | Q:
Easiest way to get an Active Directory server for testing
We're developing a .net application, and are about to add authentication to it. We'd like to use Active Directory for this, but are aiming to make this as simple as possible for the test-server used for development.
What does it take to get Active Directory up and running? Can I run it locally on my Win7 installation? I've heard about ADAM and AD LDS, but don't really know the details besides knowing they are lightweight implementations.
So; what's the easiest way to a working Active Directory for testing?
A:
Your going to need a server installation (Windows 2003/2008/2008R2) to install Active directory.
Generally the easiest way to do this in a test/dev enviroment is to install the server OS in a VM and setup a domain inside of that. It's really not that hard if you are just looking to run a very small domain for people to test auth against.
|
[
"rpg.stackexchange",
"0000105946.txt"
] | Q:
Does any way to negate humans' need for sleep exist?
While staying human (so no altering the character into undead or constructs, or polymorphing into an elf) and keeping the ability to take Rests, is there any way to completely negate a human's need for sleep?
The purpose is for
druid characters needing to remain awake to prevent the ending of wild shape, while restoring extended use through long rests
characters with curses that kill when they fall asleep if not dispelled/broken first
being in worlds where if you fall asleep your soul will be ripped into eternal torment
etc.
A:
Yes
Pact of the Tome warlocks can take the Aspect of the Moon invocation, which explicitly negates the need for sleep.
You no longer need sleep and can't be forced to sleep by any means[...]
For a druid, this obviously would require multiclassing.
A:
A previous revision of this answer suggested that long rests did not require sleep and there were no rules for sleep deprivation. These assertions were respectively rendered incorrect by the publishing of 2017's PHB errata and then Xanathar's Guide to Everything.
The core books (PHB, DMG, and MM) have no rules regarding penalties for sleep deprivation; the closest I can find is that the PHB entry for Constitution states:
The DM might call for a Constitution check when you try to accomplish tasks like the following:
...
Go without sleep
However, Xanathar's Guide to Everything contains a wealth of optional rules for DMs who want to cover more unusual situations, and on page 78 it offers the following rule regarding characters who are forgoing long rests/sleep:
Whenever you end a 24-hour period without finishing a long rest, you must succeed on a DC 10 Constitution saving throw or suffer one level of exhaustion.
In any event; the application of levels of exhaustion to characters who are going without sleep is the obvious way to represent such a situation in the rules of the game. Your GM might rule that exhaustion incurred this way cannot be removed without sleeping; for starvation and dehydration, for instance, the game states that exhaustion caused by a lack of food or water cannot be removed until the character has eaten and drunk the appropriate amount.
In 3e, a popular method of overcoming fatigue was the use of the Restoration spells in their capacity to remove the conditions of exhaustion or fatigue. In 5e, the Greater Restoration spell can be used to remove one level of exhaustion (the Lesser Restoration spell only affects a much more limited set of conditions and cannot be used to combat exhaustion). Were I your GM and I was giving you levels of exhaustion for not sleeping, I would rule that Greater Restoration could be used to overcome sleep-related fatigue.
You might also have luck with the possibility of a custom magic item. 5e includes an Ioun Stone of Sustenance (and previous versions of the game included Rings of Sustenance) which enable the character to go without needing to eat or drink at all. A similarly priced item of Sleeplessness/Wakefulness which likewise negates the need for characters to actually sleep would seem like a perfectly reasonable magical item to me.
A:
Yes
The penalty for never sleeping is you start gaining a level of exhaustion each day after a bit.
Greater Restoration can remove a level of exhaustion (and is on the Druid list).
A Druid can afford to make use of this spell by using up 100gp of diamond dust daily each time they incur a level of exhaustion.
A Cleric can do this indefinitely via casting Conjure Celestial to
summon Couatls, which can cast Greater Restoration for free (once
per day per Couatl), in addition to snorting diamond dust at lower
levels.
Anyone who's got the assistance of an Androsphinx can go
without sleep easily-- such creatures can cast Greater Restoration
thrice daily without material components.
Anyone who's friends with
an Empyrean certainly needs no sleep; said creatures can cast the
spell without material components at-will.
|
[
"stats.stackexchange",
"0000241471.txt"
] | Q:
If multi-collinearity is high, would LASSO coefficients shrink to 0?
Given $x_2 = 2 x_1$, what's the theoretical behavior of LASSO coefficients and why?
Would one of $x_1$ or $x_2$ shrink to $0$ or both of them?
require(glmnet)
x1 = runif(100, 1, 2)
x2 = 2*x1
x_train = cbind(x1, x2)
y = 100*x1 + 100 + runif(1)
ridge.mod = cv.glmnet(x_train, y, alpha = 1)
coef(ridge.mod)
#3 x 1 sparse Matrix of class "dgCMatrix"
# 1
#(Intercept) 1.057426e+02
#x1 9.680073e+01
#x2 3.122502e-15
A:
Notice that
\begin{align*}
\|y-X\beta\|_2^2 + \lambda \|\beta\|_1
& = \|y - \beta_1 x_1 - \beta_2 x_2 \|_2^2 + \lambda \left( |\beta_1| + |\beta_2| \right) \\
& = \|y - (\beta_1 + 2 \beta_2) x_1 \|_2^2 + \lambda \left( |\beta_1| + |\beta_2| \right).
\end{align*}
For any fixed value of the coefficient $\beta_1 + 2\beta_2$, the penalty $|\beta_1| + |\beta_2|$ is minimized when $\beta_1 = 0$. This is because the penalty on $\beta_1$ is twice as weighted! To put this in notation, $$\tilde\beta = \arg\min_{\beta \, : \, \beta_1 + 2\beta_2 = K}|\beta_1| + |\beta_2|$$ satisfies $\tilde\beta_1 = 0$ for any $K$. Therefore, the lasso estimator
\begin{align*}
\hat\beta
& = \arg\min_{\beta \in \mathbb{R}^p} \|y - X \beta\|_2^2 + \lambda \|\beta\|_1 \\
& = \arg\min_{\beta \in \mathbb{R}^p} \|y - (\beta_1 + 2 \beta_2) x_1 \|_2^2 + \lambda \left( |\beta_1| + |\beta_2| \right) \\
& = \arg_\beta \min_{K \in \mathbb{R}} \, \min_{\beta \in \mathbb{R}^p \, : \, \beta_1 + 2 \beta_2 = K} \, \|y - K x_1 \|_2^2 + \lambda \left( |\beta_1| + |\beta_2| \right) \\
& = \arg_\beta \min_{K \in \mathbb{R}} \, \left\{ \|y - K x_1 \|_2^2 + \lambda \min_{\beta \in \mathbb{R}^p \, : \, \beta_1 + 2 \beta_2 = K} \, \left\{ \left( |\beta_1| + |\beta_2| \right) \right\} \right\}
\end{align*}
satisfies $\hat\beta_1 = 0$. The reason why the comments to OP's question are misleading is because there's a penalty on the model: those $(0, 50)$ and $(100,0)$ coefficients give the same error, but different $\ell_1$ norm! Further, it's not necessary to look at anything like LARs: this result follows immediately from the first principles.
As pointed out by Firebug, the reason why your simulation shows a contradictory result is that glmnet automatically scales to unit variance the features. That is, due to the use of glmnet, we're effectively in the case that $x_1 = x_2$. There, the estimator is no longer unique: $(100,0)$ and $(0,100)$ are both in the arg min. Indeed, $(a,b)$ is in the $\arg\min$ for any $a,b \geq 0$ such that $a+b = 100$.
In this case of equal features, glmnet will converge in exactly one iteration: it soft-thresholds the first coefficient, and then the second coefficient is soft-thresholded to zero.
This explains why the the simulation found $\hat\beta_2 = 0$ in particular. Indeed, the second coefficient will always be zero, regardless of the ordering of the features.
Proof: Assume WLOG that the feature $x \in \mathbb{R}^n$ satisfies $\|x\|_2 = 1$. Coordinate descent (the algorithm used by glmnet) computes for it's first iteration: $$\hat\beta_1^{(1)} = S_\lambda(x^T y)$$ followed by
\begin{align*}
\hat\beta_2^{(1)}
& = S_\lambda \left[ x^T \left( y - x S_\lambda (x^T y) \right) \right] \\
& = S_\lambda \left[ x^T y - x^T x \left( x^T y + T \right) \right] \\
& = S_\lambda \left[ - T \right] \\
& = 0,
\end{align*}
where $T = \begin{cases} - \lambda & \textrm{ if } x^T y > \lambda \\ \lambda & \textrm{ if } x^T y < -\lambda \\ 0 & \textrm{ otherwise} \end{cases}$. Then, since $\hat\beta_2^{(1)}= 0$, the second iteration of coordinate descent will repeat the computations above. Inductively, we see that $\hat\beta_j^{(i)} = \hat\beta_j^{(i)}$ for all iterations $i$ and $j \in \{1,2\}$. Therefore glmnet will report $\hat\beta_1 = \hat\beta_1^{(1)}$ and $\hat\beta_2 = \hat\beta_2^{(1)}$ since the stopping criterion is immediately reached.
A:
When I re-run your code, I get that the coefficient of $x_2$ is numerically indistinguishable from zero.
To understand better why LASSO sets that coefficient to zero, you should look at the relationship between LASSO and Least Angle Regression (LAR). LASSO can be seen as a LAR with a special modification.
The algorithm of LAR is roughly like this: Start with an empty model (except for an intercept). Then add the predictor variable that is the most correlated with $y$, say $x_j$. Incrementally change that predictor's coefficient $\beta_j$, until the residual $y - c - x_j\beta_j$ is equally correlated with $x_j$ and another predictor variable $x_k$. Then change the coefficients of both $x_j$ and $x_k$ until a third predictor $x_l$ is equally correlated with the residual
$y - c - x_j\beta_j -x_k\beta_k$
and so on.
LASSO can be seen as LAR with the following twist: as soon as the coefficient of a predictor in your model (an "active" predictor) hits zero, drop that predictor from the model. This is what happens when you regress $y$ on the collinear predictors: both will get added to the model at the same time and, as their coefficients are changed, their respective correlation with the residuals will change proportionately, but one of the predictors will get dropped from the active set first because it hits zero first. As for which of the two collinear predictors it will be, I don't know. [EDIT: When you reverse the order of $x_1$ and $x_2$, you can see that the coefficient of $x_1$ is set to zero. So the glmnet algorithm simply seems to set those coefficients to zero first that are ordered later in the design matrix.]
A source that explains these things more in detail is Chapter 3 in "The Elements of Statistical Learning" by Friedman, Hastie and Tibshirani.
|
[
"math.stackexchange",
"0003469771.txt"
] | Q:
$xy + ax^2 + bx + c = 0 , x+y$ has relative max or min if...
Options :
$b^2-4ac > 0$
$b^2/4ac >0$
$b/(c-1) >0$
$c/(a-1)>0$
$a/(b-1)>0$
Relative max or min is local max or min, means max or min at certain open interval..
$xy + ax^2 + bx + c = 0 $
$ax^2 + (y+b)x + c = 0 $ if its a qudratic fuction.
Then the max or min point will be (-b/2a , f(-b/2a))
$y = (-ax^2 - bx - c)/x$
But what does it mean by $x+y$ ?
When $x+y$ will have relative max or min?
A:
Get $y$ by itself so that $$y = \frac{-ax^{2}-bx-c}{x}$$
Then substitute this for $y$ in $f(x) = x+y$ so we have
$$f(x) = \frac{-ax^{2}-bx-c}{x} + x$$
and we want to know if $f(x)$ will have a relative minimum or maximum. The cases where it will not have a minimum or maximum are when the derivative has no real zeroes. Lets find the derivative using the product rule:
$$f'(x) = \frac{1}{x}(-2ax-b)-\frac{1}{x^{2}}(-ax^{2}-bx-c)+1$$
Simplify fractions
$$f'(x) = \frac{x(-2ax-b)-(-ax^{2}-bx-c)+x^{2}}{x^{2}}$$
Simplify
$$f'(x) = \frac{(-a+1)x^{2} + c}{x^{2}}$$
We wish to know when the derivative will be $0$, and we can multiply away the denominator to get
$$0 = (-a+1)x^{2} + c$$
$$x^{2} = \frac{-c}{-a+1} = \frac{c}{a-1}$$
Notice that we need real roots in order to have a relative minimum or maximum, and we are taking a square root, thus
$$\frac{c}{a-1}>0$$
|
[
"stackoverflow",
"0039919269.txt"
] | Q:
Iterate over spark cogroup() pairrdd output in scala
I created 2 Pair RDD's in Spark
var pairrdd = sc.parallelize(List((1,2),(3,4),(3,6)))
var pairrdd2 = sc.parallelize(List((3,9)))
I applied the cogroup function
var cogrouped = pairrdd.cogroup(pairrdd2)
The object type for cogroupedrdd looks like below.
cogrouped: org.apache.spark.rdd.RDD[(Int, (Iterable[Int], Iterable[Int]))] = MapPartitionsRDD[801] at cogroup at <console>:60
I am trying to create a function to iterate over these values
def iterateThis((x: Int,(x1:Iterable[Int],x2:Iterable[Int])))={
println(x1.mkString(","))
}
but am I getting below error.
<console>:21: error: identifier expected but '(' found.
def iterateThis((x: Int,(x1:Iterable[Int],x2:Iterable[Int])))={
^
A:
Your argument is of type (Int, (Iterable[Int], Iterable[Int])):
def iterateThis(arg: (Int, (Iterable[Int], Iterable[Int]))) = {
val (_, (x1, _)) = arg
println(x1.mkString(","))
}
|
[
"askubuntu",
"0000939736.txt"
] | Q:
What is the difference between /etc/profile and .bashrc
As the title suggests I am asking about the main differences between .bashrc and /etc/profile. What I know is that .bashrc is a shell script that runs on login(I guess). And I know /etc/profile runs on ssh login or terminal login I also guess. Could someone please steer me in the right direction here?
A:
I think this answer sums it up nicely:
From man bash:
Invocation
[...]
When bash is invoked as an interactive login shell, or as a
non-interactive shell with the --login option, it first reads and
executes commands from the file /etc/profile, if that file exists.
After reading that file, it looks for ~/.bash_profile, ~/.bash_login,
and ~/.profile, in that order, and reads and executes commands from
the first one that exists and is readable. The --noprofile option may
be used when the shell is started to inhibit this behavior.
[...]
When an interactive shell that is not a login shell is started, bash
reads and executes commands from ~/.bashrc, if that file exists. This
may be inhibited by using the --norc option. The --rcfile file option
will force bash to read and execute commands from file instead of
~/.bashrc.
|
[
"stackoverflow",
"0018912388.txt"
] | Q:
How do i Swap Data of an Arrays?
public class Swap_Numbers {
public static void main(String[] args) {
int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers
System.out.println (numTens[3]); // I want my numTens displays numHundred
System.out.println (numHundred[4]); // I want my numHundred displays numTens
}
}
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables.. hope some can explain me how Thanks!
A:
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables
You shouldn't, basically. Just take the simple route of a temporary variable:
int[] tmp = numTens;
numTens = numHundred;
numHundred = tmp;
For ints you can actually swap the values within the arrays using arithmetic without temporary variables (which is not the same as swapping which arrays the variables refer to), but it would be very odd to actually find yourself in a situation where you want to do that. Sample code:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5 };
int[] y = { 15, 60, 23, 10, 100 };
swapValues(x, y);
System.out.println("x: " + Arrays.toString(x));
System.out.println("y: " + Arrays.toString(y));
}
static void swapValues(int[] a, int[] b) {
// TODO: Validation
for (int i = 0; i < a.length; i++) {
a[i] += b[i];
b[i] = a[i] - b[i];
a[i] -= b[i];
}
}
}
Even there, I would actually write swapValues using a temporary variable instead, but the above code is just to prove a point...
|
[
"stackoverflow",
"0055003159.txt"
] | Q:
Using Vue and axios post to json file problem
I got problem with axis posting to local .json file. It gives me an error:
POST http://localhost:8080/todolist.json 404 (Not Found)
TodoListEditor.vue?b9d6:110 Error: Request failed with status code 404
at createError (createError.js?2d83:16)
at settle (settle.js?467f:18)
at XMLHttpRequest.handleLoad (xhr.js?b50d:77)
I tried many address schemes but everything ends the same. When I pass exact same address into axios.get() - it returns proper data and reads the file.
Here's my part of code:
axios.post('http://localhost:8080/todolist.json',
this.todolist,{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
}
}).then((response)=>{
console.log(response);
}).catch((error)=>{
console.log(error);
});
Thanks for help
A:
The types of HTTP requests GET and POST have their own roles. GET is a request to retrieve information, POST is a request to write data, and the server acts differently for each method. The above error indicates that the server is unable to process the request for POST requests.
Sending a get request from the URL above seems to work well because it means bringing in the todolist.json file, and sending a post request to a specific file is inappropriate.
|
[
"law.stackexchange",
"0000038281.txt"
] | Q:
Re-using a small part of an artwork in a logo design
The artwork La Gerbe by Matisse was created in 1953. It consists of about 30 fern-like shapes on a white background. I am making a logo for a non-commercial academic website and it was suggested to me to use one of those shapes, albeit recoloured to match the website's theme. (There are intellectual reasons, and a kind of mathematical and visual pun why this particular image was suggested...)
I am aware that the EU copyright in this work expires in about five years, as Matisse died in 1954, and US copyright would extend five years beyond that.
I'm hesitant because while some fair use principles seem to apply (no effect on the Matisse estate's earning power; only ~3% of the artwork, and not representative of the whole; non-profit usage in an academic setting; original is a painting but new work is a logo for a wiki website), I don't quite feel 100% comfortable. On GraphicDesign.SE, where I first asked this, one user commented this was a clear case where it would be a copyright violation.
Any advice or resources that would help make a more solid case either way? (I respect the above-mentioned GD.SE user's experience and advice, but it is the say-so of one person on the internet) I've had a quick look around, but I cannot find any discussion about similar situations.
A:
The problem is that decisions on what constitute fair use are highly fact-driven judgement calls. Such decisions cannot be automated, at least not in the present state of AI, nor can a checklist approach give a reliable answer. It is hard to see how any "resource" could be helpful, beyond a list of example cases to compare the facts of a new case against.
From the description, there is a plausible case for fair use under US law, but the only way to be sure would be a court decision, sure to be a lot of trouble at best.
Of course, one could always ask the estate for permission. Given the factors cited it might be granted.
By the way, in the US, the painting will be in copyright for 95 years after publication, so at least until 2047. the life+70 term does not apply to works created before 1977. See this chart
|
[
"stackoverflow",
"0012860231.txt"
] | Q:
Facebook Page update through external page
I'm new to Facebook App development and I got this Problem:
I've created a Facebook Page (so I'm the administrator). Now I would like to have an external Webpage with a simple textarea and a "send" button. So everybody who has the link to this page could update this Facebook Page even without a Facebook account. This status update should be send by my page administrator account.
I thought I could write an app and authorize this app to publish_streams on the page and after the authorization I could switch $fbuser = $facebook->getUser(); to $fbuser = IDOFMYACCOUNT.
So the fbuser would be always my account wich is allowed to post to the Page.
If I try to use this application with an other browser (wich isn't logged in to my fb account) I get this error: (#200) The user hasn't authorized the application to perform this action
So this is the way I thought I could solve my problem.
Do you guys have an idea how I (and other people who don't have a FB account or don't wan't to login or I don't want to add them to Facebook Page administrator) could update the Facebook Status of a Page from an external website?
A:
You will need your token "baked in" to your code and some sort of admin back end to update the access token before it expires.
Also you need manage_pages permission and the token of the page if you want to post as the page.
This can be accessed from /me/accounts
|
[
"stackoverflow",
"0035420987.txt"
] | Q:
How do you set a breakpoint before executing
I would like to set a breakpoint in an application before it starts to run, so that I can make sure the application does not pass the breakpoint on startup.
In order to set a breakpoint you need to do something like:
EventRequestManager reqMan = vm.eventRequestManager();
BreakpointRequest bpReq = reqMan.createBreakpointRequest(locationForBreakpoint);
bpReq.enable();
In order to get the Location for the breakpoint, you can do something like:
Method method = location.method();
List<Location> locations = method.locationsOfLine(55);
Location locationForBreakpoint = locations.get(0);
In order to get a Method you can do something like:
classType.concreteMethodByName(methodNname, String signature)
However in order to get that classType you seem to require an ObjectReference which seems to require a running JVM.
Is there any way to set the breakpoint before the application JVM runs, to be sure the breakpoint is not passed during application startup?
A:
First of all start you target program using a LaunchingConnector to get back the target virtual machine.
VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
LaunchingConnector lc = vmm.launchingConnectors().get(0);
// Equivalently, can call:
// LaunchingConnector lc = vmm.defaultConnector();
Map<String, Connector.Argument> env = lc.defaultArguments();
env.get("main").setValue("p.DebugDummy");
env.get("suspend").setValue("true");
env.get("home").setValue("C:/Program Files/Java/jdk1.7.0_51");
VirtualMachine vm = lc.launch(env);
(change environment values according to your needs,but remember to start target VM with suspended=true).
With this VM in you hand intercept a ClassPrepareEvent using a ClassPrepareRequest.
ClassPrepareRequest r = reqMan.createClassPrepareRequest();
r.addClassFilter("myclasses.SampleClass");
r.enable();
Create a ClassPrepareEvent handler
executor.execute(()-> {
try {
while(true)
{
EventQueue eventQueue = vm.eventQueue();
EventSet eventSet = eventQueue.remove();
EventIterator eventIterator = eventSet.eventIterator();
if (eventIterator.hasNext()) {
Event event = eventIterator.next();
if(event instanceof ClassPrepareEvent) {
ClassPrepareEvent evt = (ClassPrepareEvent) event;
ClassType classType = (ClassType) evt.referenceType();
List<Location> locations = referenceType.locationsOfLine(55);
Location locationForBreakpoint = locations.get(0);
vm.resume();
}
}
}
} catch (InterruptedException | AbsentInformationException | IncompatibleThreadStateException e) {
e.printStackTrace();
}
}
then resume target VM with a call to vm.resume() to run program.
I hope this solve your problem.
|
[
"stackoverflow",
"0012466634.txt"
] | Q:
Using Leaflet with WMTS server?
Is it possible to use Leaflet javascript library to show map data from a WMTS (Web Map Tile Service) based server? Leaflet doesn't seem to support WMTS out of the box, but are there any plugins for that?
A:
You can use the L.TileLayer.WMTS class as implemented here:
http://depot.ign.fr/geoportail/api/develop/tech-docs-js/examples/js/geoportalLeaflet.js
Here is the result: http://depot.ign.fr/geoportail/api/develop/tech-docs-js/examples/geoportalLeaflet.html
|
[
"stackoverflow",
"0046766735.txt"
] | Q:
Cannot use Keychain in Xcode9 tests
I have a few unit tests to verify that the way I work with Keychain is correct and data are in same form when I load them.
Tests were running ok until update to XCode 9. At the moment, KeychainService return -50 (not saved).
According to this question, it was solved by adding Host to unit tests. However, my tests are in framework project and there is no app to use as a host.
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data ] as [String : Any]
SecItemDelete(query as CFDictionary)
SecItemAdd(query as CFDictionary, nil)
What is recommended solution? I expect just some configuration in XCode, moving tests into app is not a proper solution for me.
A:
With Xcode 9 test bundles require a host app to access the keychain from within the iOS simulator, see https://stackoverflow.com/a/46317131/5082444.
Simply add an app target and set it as the host application for your unit test bundle.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.