text:
Q: Trying to Modify Class Properties with PartialKeyPath in Swift I am fairly new (a few months in) to swift so please excuse me if the question is trivial or duplicated.
I am trying to build a class which includes properties as well as an array of tuples (with 3 parameters) within which I store the keypath to the properties in the class as well as some other parameters which I would like to use to initialise/modify the class's properties
The code below is an example of what I am trying to achieve.  The real code is a lot more complex and uses about a hundred properties within the class.
class Strategy
 {
    var name = ""
    var value = 0.0
    var position = 0

    var param = [(path: PartialKeyPath<Strategy>, label: String, value: Any)]()

    init()
        {

        self.param.append((path: \Strategy.name, label: "Name",value: "Generic String"))
        self.param.append((path: \Strategy.value, label: "Value",value: 375.8))
        self.param.append((path: \Strategy.position, label: "Position",value: 34))

        for paramIndex in 0..<self.param.count  {

            let kp = self.param[paramIndex].path
            self[keyPath: kp] = self.param[paramIndex].value
        }
}

var myStrat = Strategy()

let kp = myStrat.param[0].path

print(myStrat[keyPath: kp])

myStrat[keyPath: kp] = " New String"

The reason for this approach is that I then have to display all the properties in an NSTableView so I can load the table via a loop on param rather than each property at the time.  Also, as the properties need to be editable via the NSTableView, I can use the row index, find the keypath to the property to modify and modify it.
I am getting a "Cannot assign to immutable expression of type 'Any'" error on:
  self[keyPath: kp] = self.param[paramIndex].value

as well as on
  myStrat[keyPath: kp] = " New String"

which exemplifies how I would like to change the property name in the Strategy class
I think it has to do with self not being mutable but I cannot figure out how to solve this.
Thank you and apologies if this is a silly question of an inexperienced programmer.

A: You need to use ReferenceWritableKeyPath<Root,Value> to modify properties of reference type objects (class instances). One sad thing is that you need to specify both type Root and Value statically.
For example:
if let keyPath = kp as? ReferenceWritableKeyPath<Strategy, String> {
    myStrat[keyPath: keyPath] = " A String"
}

So, to make your code work, you may need something like this:
protocol AnyKeyAccessible: class {
    subscript (anyKeyPath keyPath: PartialKeyPath<Strategy>) -> Any? {get set}
}
extension AnyKeyAccessible {
    subscript (anyKeyPath keyPath: PartialKeyPath<Strategy>) -> Any? {
        get {
            switch keyPath {
            case let keyPath as KeyPath<Self, String>:
                return self[keyPath: keyPath]
            case let keyPath as KeyPath<Self, Double>:
                return self[keyPath: keyPath]
            case let keyPath as KeyPath<Self, Int>:
                return self[keyPath: keyPath]
            // More cases may be needed...
            default:
                return nil
            }
        }
        set {
            switch keyPath {
            case let keyPath as ReferenceWritableKeyPath<Self, String>:
                self[keyPath: keyPath] = newValue as! String
            case let keyPath as ReferenceWritableKeyPath<Self, Double>:
                self[keyPath: keyPath] = newValue as! Double
            case let keyPath as ReferenceWritableKeyPath<Self, Int>:
                self[keyPath: keyPath] = newValue as! Int
            // More cases may be needed...
            default:
                break
            }
        }
    }
}

And then you can re-write your code using it:
class Strategy: AnyKeyAccessible, CustomStringConvertible {
    var name = ""
    var value = 0.0
    var position = 0

    var param = [(path: PartialKeyPath<Strategy>, label: String, value: Any)]()

    init() {
        self.param.append((path: \Strategy.name, label: "Name",value: "Generic String"))
        self.param.append((path: \Strategy.value, label: "Value",value: 375.8))
        self.param.append((path: \Strategy.position, label: "Position",value: 34))

        for paramIndex in 0..<self.param.count  {
            let kp = self.param[paramIndex].path
            self[anyKeyPath: kp] = self.param[paramIndex].value
        }
    }

    //For debugging
    var description: String {
        return "name=\(name), value=\(value), position=\(position)"
    }
}

var myStrat = Strategy()

let kp = myStrat.param[0].path

print(myStrat[anyKeyPath: kp]) //-> Optional("Generic String")

myStrat[anyKeyPath: kp] = " New String"

print(myStrat) //-> name= New String, value=375.8, position=34

But, as I wrote in the comment of the code above, you may need many more cases to work with actual target classes. I'm not sure this really solves your issue.

A: Thank you.  Whilst playing with ReferenceWritableKeyPath I found a way that allows me not to specify the Value by putting it as Any.  I then declare my properties in the class as Any and it seems to work:
class Strategy
{
    var name = "" as Any
    var value = 0.0 as Any
    var position = 0 as Any

    var param = [(path: ReferenceWritableKeyPath<Strategy, Any>, label: String, value: Any)]()

    init()
    {

        self.param.append((path: \Strategy.name, label: "Name",value: "Generic String"))
        self.param.append((path: \Strategy.value, label: "Value",value: 375.8))
        self.param.append((path: \Strategy.position, label: "Position",value: 34))

        for paramIndex in 0..<self.param.count  {

            let kp = self.param[paramIndex].path
            self[keyPath: kp] = self.param[paramIndex].value
        }
    }

}

var myStrat = Strategy()

let kp = myStrat.param[0].path

print(myStrat[keyPath: kp])

myStrat[keyPath: kp] = "New String"

print(myStrat[keyPath: kp])

My only remaining doubt, being a novice to Swift if this may create problems in the future.  I have checked the types I get by using the keypaths and they match the properties types (String, Double and Int) even as I declared them as Any but initialised them as different types


text:
Q: Propagate the error in sagemaker from ProcessingStep to Worflow functions So I have a sagemaker worflow composed of multiple processing steps, training steps ...
I'm trying to change the FailureReason of the describe_pipeline_execution() to return useful information concerning the failure of my Sagemaker pipeline.
Indeed in my processing step and in my training step, having their code inside a docker container,  I want the pipeline to fail for various reasons. In the documentation here for processing step and here for training step, it is possible to return something by writing it in a file during the step through the functions DescribeProcessingJob or DescribeTrainingJob.
I was wondering if there is a path like /opt/ml/failure to put the output of my process so the function describe_pipeline_execution() can return what I want. Can't find it in the documentation!
Thanks in advance

A: There's no way to do this. You can log outputs from your scripts and view the logs in CloudWatch to help understand the error. You can also write to a file inside the job and upload it to S3 through a ProcessingOuput in the case of Processing jobs or by specifying the S3 path inside your training script. There's no reserved location for the errors but nothing stops you from writing your error logs and uploading them to S3.
I work at AWS and my opinions are my own.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to correctly rename a Rails model's attribute whose table is partitioned in PostgreSQL In my company we want to rename one of our main models to eliminate ambiguity of concepts. For most of the related models the process is straightforward, but we have one that stores our logs, and because of its size it's partitioned in PostgreSQL. The following migration very likely won't work in production, and even if it does, it's an incomplete solution:
class RenameMerchantAsCustomer < ActiveRecord::Migration[5.1]
  def change
    rename_table :merchants, :customers

    rename_column :logs, :merchant_id, :customer_id
  end
end

Does anybody know how to solve this situation?

A: You can totally write raw SQL on a migration or task to solve the issue, or simply use something that's already implemented for this matter. You know... don't reinvent the wheel. You can use something like pgslice


text:
Q: How can I prove these two norms are equivalent? Let  $\Omega \subset \mathbb{R}^N$ and $p\in C(\overline{\Omega})$.
Here, $W^{1,p(x)}(\Omega)$ is the generalized Lebesgue-Sobolev space which is defined as follows: $$W^{1,p(x)}(\Omega)=\{ u\in L^{p(x)}(\Omega):|\nabla u|\in L^{p(x)}(\Omega)\}$$ with the norm $$\| u \|_{W^{1,p(x)}(\Omega)}:=\| u\|_{L^{p(x)}(\Omega)}+\| \nabla u\|_{L^{p(x)}(\Omega)},$$ where $$L^{p(x)}(\Omega)=\{ u:\Omega \to \mathbb{R}\; measurable\; and \; \int_{\Omega}|u(x)|^{p(x)}dx<+\infty \}$$ with the norm $$\| u\|_{L^{p(x)}(\Omega)}=\inf \{ \beta >0 :\int_{\Omega}|\frac{u(x)}{\beta}|^{p(x)}dx\leq 1\}.$$
Let $\alpha \in L^{\infty}(\Omega)$ with $ess\inf_{s\in \Omega}\alpha (x)>0$. How can I show that the following norm $$||u||_{\alpha }=\inf \{ \sigma >0:\int_{\Omega}|\frac{u(x)}{\sigma}|^{p(x)}+|\frac{\nabla u(x)}{\sigma}|^{p(x)})dx\leq 1\}$$, on $W^{1,p(x)}(\Omega)$ is equivalent to that intruced above?


text:
Q: A question about "control groups" in IV regression I am doing an analysis which covers the electricity market in the US. The dataset that I use contains 39 states, which 15 of them has a value other (higher) than zero for the regressor. This makes the variable extremely skewed, and I believe this disrupts my results (the F-value of my instrument are 0.3). When I only include the states that contains the regressor, my F-value are 15.
My question is that should it be necessary to include the 24 states that does not contain my F-value in the analysis? The way I think is that I need to test the regressor for the whole of the US, not only in those states that includes my regressor. I have struggled finding information regarding this online.


text:
Q: webpack : You may need an appropriate loader to handle this file type I am using webpack for the first time and I am not very thorough with webpack. I am using angular - ES6 - bable and I am trying to use webpack-angular-translate.
I am getting below error:
ERROR in ./~/html-webpack-plugin/lib/loader.js!./src/index.html
    Module parse failed: /Users/samirshah/Desktop/nuskin_translate/node_modules/html-webpack-plugin/lib/loader.js!/Users/samirshah/Desktop/nuskin_translate/node_modules/webpack-angular-translate/dist/html/html-loader.js!/Users/samirshah/Desktop/nuskin_translate/src/index.html Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
I am trying to set preloaders in modules. When I try to set preloader of html I am getting above error.
preLoaders: [
    {
        test: /\.html$/,
        loader: WebPackAngularTranslate.htmlLoader()
    }
],

WebPackAngularTranslate.jsLoader() is working fine. I am not sure why WebPackAngularTranslate.htmlLoader() is throwing error.
Any one has faced any similar problem. Please help me here.
Thanks in advance.
here is my configuration file:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var WebPackAngularTranslate = require("webpack-angular-translate");

module.exports = {
  debug: true,
  entry: {
  vendor: ["jquery", "angular"],
  bundle: ['babel-polyfill', './src/app.js'],
},
// entry: ['babel-polyfill', './src/app.js'],
 output: {
    path: path.join(__dirname, 'public'),
    filename: '[name].js'
  },
  devServer: {
    // This is required for webpack-dev-server. The path should
    // be an absolute path to your build destination.
    outputPath: path.join(__dirname, 'public')
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Website Starter',
      template: 'src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true
      }
    }),
    new WebPackAngularTranslate.Plugin(),
    new ExtractTextPlugin("main.css"),
    new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      minChunks: 2
    }),
    // new webpack.optimize.UglifyJsPlugin({
    //   sourceMap: true,
    //   mangle: false,

    // }),
    new CopyWebpackPlugin([{ from: 'src/**/*.js', to: __dirname +     '/public' }]),
new CleanWebpackPlugin(['public'], {
  root: path.resolve(__dirname),
  verbose: true,
  dry: true
})],
  module: {
    preLoaders: [
        {
            test: /\.html$/,
            loader: WebPackAngularTranslate.htmlLoader()
        }],
    loaders: [
      {
                test: /\.js$/,
                loader: WebPackAngularTranslate.jsLoader()
        },
      {
        test: /\.js$/, loader: 'babel-loader', query: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: true,
          presets: ['es2015', 'stage-2']
        }, exclude: [/node_modules/, /\.spec.js$/, /\npm\.js$/]
      },
      { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
      { test: /\.scss$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader") },
      { test: /\.html$/, loader: 'file-loader?name=[path]/[name].[ext]', exclude: /index\.html$/ },
      { test: /\.jade$/, loader: 'file-loader?name=[path]/[name].html!jade-html?pretty=true' },
      // inline base64 URLs for <=8k images, direct URLs for the rest
      { test: /\.(png|jpg)$/, loader: 'file-loader?name=assets/images/[name].[ext]' },
      // helps to load bootstrap's css.
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?name=assets/fonts/[name].[ext]'
      },
      {
        test: /\.woff2$/,
        loader: 'file-loader?name=assets/fonts/[name].[ext]'
      },
      {
        test: /\.otf$/,
        loader: 'file-loader?name=assets/fonts/[name].[ext]'
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?name=assets/fonts/[name].[ext]'
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?name=assets/fonts/[name].[ext]'
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?name=assets/images/[name].[ext]'
      }
    ]
  },

  devtool: 'source-map'
};

A: It seems as index.html is loaded with webpack too, but it is excluded from the html loader configuration. You either have to include (or not explicit exclude it) or do not process it with webpack...

A: You need to make sure that your loader can't match src/index.html
This should work:
   {
        test: /\.html$/,
        loader: WebPackAngularTranslate.htmlLoader(),
        exclude: /src\/index\.html$/
    }


text:
Q: measurable function and inverse image not measurable set. A doubt.
Exists a $f:X\to Y$ measurable function and $f^{-1}(B)$ is not measurable set for some $B\subset Y$?

A: Take $f=\mathrm{Id}_X : X \to X$. Then for $B \subset X$ not mesurable, $f^{-1}(B)$ is not mesurable.


text:
Q: flutter bloc BlocProvider.of(context) in the context of bottom sheet dialog I have provided bloc in parent widget and trying to access that bloc instance in bottom sheet dialog. In bottom sheet dialog i have bloc builder which can not access the bloc instance.
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<DevicePairBloc>(
      create: (context) => DevicePairBloc(),
      child: DeviceList(),
    );
  }
}

class DeviceList extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => _DeviceListState();
}

class _DeviceListState extends State<DeviceList> {
  void showData(BuildContext context) {
    showModalBottomSheet(
        context: context, builder: (context) => ReadingScreen());
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        RaisedButton(onPressed: () => showData(context),),
      ],
    );
  }
}

class ReadingScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DevicePairBloc, DevicePairState>(
      builder: (context, state) {
        return Text("20 mg");
      },);
  }

}

A: If you want to access the same bloc in ReadingScreen() too, then you'll need to wrap your MaterialApp() with BlocProvider<DevicePairBloc>. At the moment you have wrapped the DeviceList() with that bloc provider, so it is only available to it.


text:
Q: Get file paths for files in Centennial app When converting an app to a Windows Store app, we add the files as mentioned here. But now - how do we access them? What's their path?
They're not in the special folder created for the package.

A: You can create a folder structure in your project where you can include the files and then since you are already crossing the Centennial Bridge, you can start using the Windows.Storage.StorageFile WinRT API to interact with files.
For example, you can use: StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///folderUnderYourAppRoot/image.bmp")); to get the file which is under the "folderUnderYourAppRoot". This is the generic guidance: https://msdn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files, so you can review it further...


text:
Q: I am not receiving response data from the client to the Java Spring Boot server I'm new to sockets in java.
I would like to know why I am not able to receive the data from the client to the server.
after making the connection, I can send data to the client, but with "client.observable.subscribe" I can not see the return data
Server code:
@GetMapping("/desktop/{client}")
public DeferredResult<String> getScreenshot(@PathVariable("client") String clientName) {
    DeferredResult<String> result = new DeferredResult<>();
    Client client = ClientListenerService.getClient(clientName);
    if (client == null) {
        result.setResult(new JSONObject().put("error", "Requested client was not found").toString());
        return result;
    }
    Long requestID = client.getRequestID();
    JSONObject request = new JSONObject();
    request.put("id", requestID);
    request.put("type", RequestType.GET_SCREENSHOT.getValue());
    try {
        PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
        out.println(request.toString());
    } catch (IOException ex) {
        result.setResult(new JSONObject().put("error", "Failed to write to the socket, exception: " + ex).toString());
        return result;
    }
    Runnable task = () -> {
        client.observable.subscribe((response) -> {
            JSONObject responseJson = new JSONObject(response);
            if (responseJson.has("id") && responseJson.getLong("id") == requestID) {
                result.setResult(response);
                Thread.currentThread().interrupt();
            }
        }, (error) -> {});
    };
    Thread thread = new Thread(task);
    thread.start();
    return result;
}

Client code:
public static void main(String[] args) throws IOException {
    Socket socketClient = null;
    BufferedReader in = null;
    PrintWriter out = null;

    try {
      socketClient = new Socket("localhost", 2222);
      in = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream())),true);
    } catch (IOException e) {
        System.err.println("Cannot set I/O channels for connection");
        System.exit(-1);
    }

    try {
        String line;
        line = in.readLine();
        System.out.println("Response server: " + line);

        out.println(line); // Send to server
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
    }

    out.close();
    in.close();
    socketClient.close();
}

I hope your help community, thank you


text:
Q: worldpay setup with spree I am trying to setup WorldPay with spree, I have created sandbox account also but could not found from where I found below details
INSTALLATION:
AMERICAN EXPRESS LOGIN:
DISCOVER LOGIN:
JCB LOGIN:
MASTERCARD LOGIN:
MAESTRO LOGIN:
VISA LOGIN:
please help if someone already setup this with the spree

A: I had the same issue, and my problem was that I was trying to integrate with Worldpay Online (not regular old Worldpay).
In the end I created my own gateway (very basic with only the options I needed, but you could extend this to add the functionality that you want):
class Spree::WorldpayOnlineGateway < Spree::Gateway

    preference :client_key, :string
    preference :service_key, :string

    def provider_class
        ActiveMerchant::Billing::WorldpayOnlinePaymentsGateway
    end

    def payment_source_class
        Spree::CreditCard
    end

    def purchase(money, credit_card, options = {})

      options[:client_key] = self.preferred_client_key
      options[:service_key] = self.preferred_service_key

      provider = provider_class.new(options)
      provider.purchase(money, credit_card, options)

    end

end

Then in your spree.rb initializer, add the gateway:
config = Rails.application.config
config.after_initialize do
     config.spree.payment_methods << Spree::WorldpayOnlineGateway
end


text:
Q: Adding a Query to a Subquery then produces no results The lastReports subquery by itself, returns 10 rows. The "wrapper" records do exist, but when I join them, I get 0 rows returned in 12ms from: This is on SQLite.
My joins is good, I'm not making a selection mistake mistake(SQL LEFT JOIN Subquery Alias)... what am I missing, or not understanding?
SELECT
    name
FROM
    teachers
INNER JOIN (SELECT
            teacher_id,
            reportingPeriod,
            ReportingType,
            date('now') - 3 as AgeOfReport,
            count(id) as NumberOf
        FROM
            reports
        GROUP BY
            teacher_id
        ORDER BY
            teacher_id ASC,
            reportingPeriod asc
    ) AS lastReports
ON teachers.id = lastReports.teacher_id;

SAMPLE DATA

TEACHERS
ID NAME
-----------------
1  Mr John Smith
2  Ms Janet Smith

REPORTS
---------------------------------------------------
ID   TEACHER_ID   REPORTINGPERIOD REPORTINGTYPE
1   1             Jan 2017         Draft
2   1             Feb 2017         Draft
3   2             Jun 2018         Draft
4   2             Jul 2018         Draft
5   1             Mar 2017         Final

DESIRED RESULTS
------------------
Mr John Smith      Final    Mar 2017
Ms Janet Smith     Draft    Jul 2018

A: You can try to make row_number by TEACHER_ID column and order by REPORTINGPERIOD, which mean closer the date in subquery, get rn = 1 the data in each TEACHER_ID the max date and JOIN on TEACHERS.
CREATE TABLE TEACHERS(
  ID INT,
  NAME VARCHAR(50)
);

INSERT INTO TEACHERS VALUES (1, 'Mr John Smith');
INSERT INTO TEACHERS VALUES (2, 'Ms Janet Smith');

CREATE TABLE REPORTS(
  ID INT,
  TEACHER_ID int,
   REPORTINGPERIOD DATE,
  REPORTINGTYPE varchar(100)
);

INSERT INTO REPORTS VALUES (1,1,'Jan 2017', 'Draft');
INSERT INTO REPORTS VALUES (2,1,'Feb 2017', 'Draft');
INSERT INTO REPORTS VALUES (3,2,'Jun 2018', 'Draft');
INSERT INTO REPORTS VALUES (4,2,'Jul 2018', 'Draft');
INSERT INTO REPORTS VALUES (5,1,'Mar 2017', 'Final');

Query 1:
SELECT t.NAME,
       t1.REPORTINGTYPE,
       t1.REPORTINGPERIOD
FROM teachers as t INNER JOIN
(
    SELECT *,(SELECT COUNT(*) FROM REPORTS tt WHERE tt.TEACHER_ID = t1.TEACHER_ID and tt.REPORTINGPERIOD>=t1.REPORTINGPERIOD) rn
    FROM REPORTS t1
) as t1 on t1.TEACHER_ID = t.id and rn = 1
ORDER BY t.NAME

Results:
|         t.NAME | t1.REPORTINGTYPE | t1.REPORTINGPERIOD |
|----------------|------------------|--------------------|
|  Mr John Smith |            Final |           Mar 2017 |
| Ms Janet Smith |            Draft |           Jun 2018 |

A: The REPORTINGPERIOD values do not compare correctly, because Jul comes before Jun in the alphabet. You should use a format like yyyy-mm where the most significant field comes first.
In SQLite, you can simply use MAX() to select entire rows:
SELECT t.Name,
       r.ReportingType,
       max(r.ReportingPeriod)
FROM Teachers t
JOIN Reports r ON t.ID = r.Teacher_ID
GROUP BY r.Teacher_ID;

NAME            REPORTINGTYPE  max(r.ReportingPeriod)
--------------  -------------  ----------------------
Mr John Smith   Final          2017-03
Ms Janet Smith  Draft          2018-07


text:
Q: Two-digit random number is chosen. What is the probability that the sum of its digits is 5? I tried this method at first...
Since I know the denominator of the fraction using combinations I include that first: $9C2$.
I am getting stuck at the numerator part of the fraction because there are only $3$ cases $\left(0,5;1,4;2,3,\right)$ right ?.
So the answer I get is $1/12$.
Is the correct? And does order matter in this case ?.

A: Bettween 10- 99 there are 90 two digit numbers.  Of them 14,23,32,41,and 50 have sums adding to 5.
So the probability is $\frac 5{90} = \frac 1{18}$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

A two-digit number can be written as $\ds{10a + b}$ where
  $\ds{a = 1,2,\ldots,9}$ and $\ds{b = 0,1,\ldots,9}$.

\begin{align}
\sum_{a = 1}^{9}{1 \over 9}\sum_{b = 0}^{9}{1 \over 10}\bracks{z^{5}}z^{a + b} & =
{1 \over 90}\bracks{z^{5}}\pars{\sum_{a = 1}^{9}z^{a}}
\pars{\sum_{a = 0}^{9}z^{b}} =
{1 \over 90}\bracks{z^{5}}\pars{z\,{z^{9} - 1 \over z - 1}}
\pars{z^{10} - 1 \over z - 1}
\\[5mm] & =
{1 \over 90}\bracks{z^{4}}{1 - z^{9} - z^{10} + z^{19} \over \pars{1 - z}^{2}} =
{1 \over 90}\bracks{z^{4}}\pars{1 - z}^{-2} =
{1 \over 90}{-2 \choose 4}\pars{-1}^{4}
\\[5mm] & =
{1 \over 90}{5 \choose 4}\pars{-1}^{4} = {1 \over 90}\,5 = \bbx{1 \over 18}
\end{align}


text:
Q: Make Function Wait Until First Function is Completed to Run I have this function in my React App.  It calls a few other functions.  Everything works except, I need the .then(() => this.getHCAid()) to complete before .then(() => this.addDocsList()) runs. I have not been able to make that happens. I'm sure it's simple, I just don't know how.
createHCA() {
      fetch(API_URL + `/hca/create`, {
        method: "PUT",
        body: JSON.stringify({
          client: this.state.client,
          short: this.state.short,
        }),
        headers: { "Content-Type": "application/json" },
      })
        .then((res) => {
          if (!res.ok) {
            throw new Error();
          }
          return res.json();
        })
        .then((data) => console.log(data))
        .catch((err) => console.log(err))
        .then(() => this.getHCAid())      <--- Need this to complete
        .then(() => this.addDocsList())   <--- Before this runs
        .then(() => this.getAllHCAs());
        this.setState({ showHide: false});
  }

A: I'd encourage you to do a couple of things here...

*

*Use async/await rather than a myraid of .then promises memoize
these function calls and use a useEffect (or multiple) with
dependencies to control when side-effects should be triggered. Convert to functional component to achieve this result.

*"showHide" is a very confusing term for future developers, be kind to
your future self and future devs and make a term like "show" or
"isHidden"

*If you really want to continue this pattern (chained .then statements), put your .catch at the very bottom to handle any issues/errors. This is where async/await is worth the time to quickly learn.

*You only want functions doing one main thing, and this is to createHCA, let your other code trigger the functions. As you scale you will be thankful you did.

async function createHCA() {
  let data
      try {
        data = await fetch(API_URL + `/hca/create`, {
            method: "PUT",
            body: JSON.stringify({
              client: this.state.client,
              short: this.state.short,
            }),
            headers: { "Content-Type": "application/json" },
          })
      } catch e => {
        throw new Error(e.message)
        return
      }
         this.setState({ showHide: false});
         return data?.json()
    }

A: It sounds like there are two issues going on here.
The first is that your functions sound like database queries or updates which will be asynchronous so you can't rely on the next step in the cycle to have access to any data returned if it hasn't been told to wait.
The solution you tried to come up with, setting state in one of the then methods, won't work either because it too batches up queries and processes them asynchronously, and the next step won't have access to that data either.
So, ideally what you should probably do is use a promise to return the id from getHCAid, and then pass that into addDocsList which also returns a promise, etc.
Here's a simplified example using async/await.
getHCAid() {
  return new Promise((res, rej) => {
    // Do DB process, get an id
    res(id);
  });
}

async getData() {
  const response = await fetch(API_URL);
  const data = await response.json();
  const id = await this.getHCAid();
  const list = await this.addDocsList(id);
  const hcas = await this.getAllHCAs();
  this.setState({ showHide: false });
}


text:
Q: How to Get this ID I'm doing an automation using Selenium WebDriver and I'm getting all the elements of a Table.
I used the code below:
var qntd= driver.FindElements(By.XPath("//*[@id='dataTable']/tbody/tr")).Skip(3);

I then realized that each element generated an Id that is not of the Id as shown in the Html

I tried to retrieve this id with a query but I could not because the return is the HTML Id attribute
var query = from a in qntd
                select a.GetAttribute("Id");

Where does this ID come from and how do I retrieve it?

A: Unfortunately you won't be able to access this field because the method "FindElements" returns the elements in the form of IWebElement. IWebElement does not have a method implemented to get the ID value you are looking for.
If the FindElements method was to return the type RemoteWebElement, or even ChromeWebElement, we would be able to access this field because the RemoteWebElement has a method to access it. However, this method is not implemented in the interface. So there is no way for us to get it. I've played around with casting and haven't been able to cast in the correct spot. So as of now, I'm not seeing a way to get this ID.
See RemoteWebElement.cs source code for more information:
https://github.com/SeleniumHQ/selenium/blob/master/dotnet/src/webdriver/Remote/RemoteWebElement.cs
Hopefully this helps you out a bit

A: If you want to get the IDs from all elements as a List<String> you could do
List<String> query = qntd.Select(it => it.Id).ToList();

A: It's a special id generated by the driver itself, not html property. You can use type cast to RemoteWebElement and then get this value using reflection as it is protected. But hardly this is the thing you need in your tests.
https://seleniumhq.github.io/selenium/docs/api/dotnet/?topic=html/P_OpenQA_Selenium_Remote_RemoteWebElement_Id.htm


text:
Q: How to get the intermediate portion of string? I have a string as under
var input= "dbo.xyx.v1.UserDefinedFunction";

The desired output will be "xyx.v1";
My attempt is
var input = "dbo.xyx.v1.UserDefinedFunction";
var intermediate = input.Split('.').Skip(1);
var res = intermediate.Reverse().Skip(1).Aggregate((a, b) => b + "." + a);

works fine..but any other proper and elegant method?
Kindly note that it can be any part(in the example I just showed 4 parts)
e.g.
Input : "dbo.part1.part2.part3.part4.UserDefinedFunction"
Output : "part1.part2.part3.part4"

A: This returns always the mid part of a string which can be one or two parts(acc. to the total part-number).
var input = "dbo.xyx.v1.UserDefinedFunction";
string[] tokens = input.Split('.');
int midIndex = (tokens.Length - 1) / 2;
IEnumerable<int> midIndices = midIndex % 2 == 0
    ? new[] { midIndex }
    : new[] { midIndex, midIndex + 1 };
string mid  = string.Join(".", tokens.Where((t, i) => midIndices.Contains(i)));

Demo
So in this case it returns xyx.v1, for a string bo.xyx.v1 it returns v1 since that's the only mid-part.

A: If you need to use LINQ, you can use Skip(1).Take(2) and string.Join, like this:
var parts = input.Split('.');
var res = string.Join(".", parts.Skip(1).Take(parts.Length-2));

If you need to throw away the first and the last parts, then you can use Substring, like this:
var start = input.IndexOf('.')+1;
var end = input.LastIndexOf('.')-1;
var res = input.Substring(start, end-start+1);

Finally, you can use regular expression, like this:
var res = Regex.Replace(input, "^[^.]+[.](.+)[.][^.]+$", "$1");

A:    string output= input.Substring(input.IndexOf('.') + 1,
                  input.LastIndexOf('.') - input.IndexOf('.') - 1);

A: var input = "dbo.xyx.v1.UserDefinedFunction";
var start = input.IndexOf('.');
var end = input.LastIndexOf('.');
string output;
if (start < end)
{
    output = input.Substring(start+1, end-start-1);
}
else
{
    output = input;
}

A: var input = "dbo.xyx.v1.UserDefinedFunction";
var intermediate = input.Split('.');
var res = string.Join(".", intermediate[1],intermediate[2]);

EDIT: for any part version
var res = string.Join(".", intermediate.Skip(1).Take(intermediate.Length - 2));

A: var input = "dbo.xyx.v1.UserDefinedFunction";
var res = string.Join(".", input.Split('.').Skip(1).Take(2));

A: You could simplify it and do:
var split = input.Split(".");
var result = String.Join(".", split[1], split[2]);

No need for Skip or Take.

A: [TestClass]
public class UnitTest2
{
    [TestMethod]
    public void TestMethod1()
    {

        var ret = "this.is.my.test.string".MySplit(".", new int[] {0,1,4 });//this.is.string

    }
}

public static class Process {
    public static string MySplit(this string Source, string seprator, int[] positionTokeep) {
        var items = Source.Split(seprator.ToCharArray());
        string ret = string.Empty;
        for (int i = 0; i < positionTokeep.Length; i++) {
            ret += items[positionTokeep[i]] + seprator;
        }
        if (!string.IsNullOrWhiteSpace(ret)) {
            ret = ret.Substring(0,ret.Length - seprator.Length);
        }
        return ret;
    }
}


text:
Q: How to paste one file content in to different files using bash script? I have a file with hundreds of names in it, ex:
Tokyo
New-York
Rio
Mexico
I want to create a empty file using the names of that list and latter apply/paste some text on it coming from another file.
So far I've done for f in $(cat list_of_names); do paste my text.txt > $f.nnn; done.
The idea is to generate a filename from the list like Tokyo.nnn (and many others) with the contents of text.txt
Tokyo.nnn will have a text with a configuration coming from text.txt. I expect to substitute $f with a name from the list while pasting the contents of text.txt on it.

A: You can create empty file using xargs touch < list_of_names.
And if you have a file named text.txt and need the its content in the files being created try this snippet.
while read filename; do
       cp -i sample "$filename".nnn
done < list_of_names


text:
Q: Flask - 400 Error with JSON request I have created the following simple flask app that displays the predicted value from a machine learning model and it renders the index.html as needed until I make the json.request. Then I receive a 400 error; here is my code:
works as needed from the command line, but need to display the prediction(s) in the browser. Can someone provide a quick starting point for me? Here is my code:
@app.route('/predict',methods=['POST'])
def predict():
    data = request.get_json(force=True)
    predict = [data["session"],data["time"],data["amount"]]
    predict = np.array(predict)
    predict = predict_request.reshape(1,-1)
    #make prediction
    with graph.as_default():
        area = keras_model_loaded.predict(predict)
        output = [area[0]]
        return render_template('index.html', output = output)

if __name__ == "__main__":
    # Choose the port
    port = int(os.environ.get('PORT', 9000))
    # Run locally
    app.run(host='127.0.0.1', port=port)

Here is how I am generating the JSON:
response = rq.get('https:xyz')
data=response.json()

session = data['currently']['session']
time = data['currently']['time']
amount = data['currently']['amount']

url= "http://127.0.0.1:9000/predict"

post_data = json.dumps({'session': session, 'time': time, 'amount': amount})

r = rq.post(url,post_data)

A: The JSON data doesn't seem to reach the server as expected. Kindly try updating your requests code to:
post_data = {'session': session, 'time': time, 'amount': amount}

r = rq.post(url, json=post_data)

From official python-requests docs:

Using the json parameter in the request will change the Content-Type in the header to application/json.


text:
Q: How do we think at the perspective of negatively charged wire in special relativity that causes magnetism? I am currently try to learn special relativity, and then i crossed on some video about how special relativity can cause magnetism here:
https://youtu.be/1TKSfAkWWN0
At timestamp 01:56 - 02:24 he explains that on positively charged cat and negatively charged wire frame of reference, the positively charged wire would seem the one to be moving and causing it to become looks more dense, causing the wire to be more positive and push the cat away. At timestamp 02:25 - 02:44 he explain in the other perspective which is positively charged wire, that the magnetic force are the cause of the pushed positively charged cat, but isn't that what we want to know in the first place? Also, when we try to think from positively charged wire again, isn't the negatively charged wire and positively charged cat looks more denser, so why doesn't the wire attract the cat?

A: That veritatasium video isn't particularly good, unfortunately.
You may want to try this youtube video: "The hidden link between electricity and magnetism" (Youtube channel: 'STEM Cell') (I haven't watched all of it but the author seems thorough.)
About the version presented in the Veritasium video: it's not just that the switch is to another perspective, the switch is to another case:
The two cases are:
-the cat is stationary with respect to the physical wire
-the cat is in motion relative to the physical wire.
Each of those two cases can be described in terms of a coordinate system that is stationary with respect to the wire, or in terms of a coordinate system that has a velocity with respect to the physical wire.
Only people who are already quite familiar with relativistic physics will be able to follow the narration in the Veritasium video, which of course defeats the purpose.
Derek Muller is generally very good, but when it comes to relativistic physics: in several different videos I have seen him fumble.

A: There is no negatively charged wire frame, because the wire never has a negative charge density. In Derek's frame (at rest with respect to the positively charged lattice), the linear charge density is zero because the density of protons and electrons are equal, with opposite charges:
$$\lambda_{\rm Derek} =  \lambda_+ + \lambda_- =\lambda(1-1)=0 $$
In Henry's frame (at rest with respect to the electrons), the proton are Lorentz contracted and the electron are Lorentz dilated:
$$\lambda_{\rm Henry} =  \gamma\lambda_+ + \frac 1 {\gamma}\lambda_- =(\gamma-\frac 1{\gamma})\lambda $$
(If you don't understand why the electrons are dilated, review Bell's Spaceship paradox, and replace the spaceships with electrons).
A little algebra shows:
$$\lambda_{\rm Henry}=\gamma(1-\frac 1{\gamma^2})\lambda=
\gamma\beta^2\lambda$$
showing there is a net positive charge.
It's tempting to say, "Thats because Lorentz contraction", but as with all relativity problem, that is half the story. From Henry's frame, the relativity of simultaneity supplies a factor of $\gamma^2\beta^2$ (relative to Derek), and the Lorentz contraction/dilation supplies a factor of $1/\gamma$...to the extent there is any physical meaning to separating the slope and intercept in a Lorentz transformation.


text:
Q: Plagiarism is a good way to earn reputation. Combatting this after the fact? There is a certain pattern of Stack Exchange users who habitually post plagiarized content.
Some cases are easy to deal with. If the user is still pretty new, a message explaining that plagiarism is not cool can turn them into more useful contributors. Some plagiarizers are so bad at it that their posts are irrelevant and can be removed wholesale. Some accounts do nothing but plagiarize and their accounts can be removed while leaving their positively-scored "contributions" (with proper sourcing added) in place.
This leaves quite a few accounts who:

*

*Post a mixture of plagiarized and original content. (Invariably you can tell the plagiarized content at a glance: it's the posts that contain a grammatically correct English sentence.)

*Do generally post more-or-less relevant answers, even when the answers aren't their own.

*Never, ever provide attribution for the content they copy, and sometimes even make a habit of editing attribution out.

It seems to me that we don't have a good way to deal with these people. Suspend the account for rules violation? They continue when they come back. Delete the account? Well, they do contribute decent content sometimes. Delete the posts? No, not when they're relevant.
When I see an account whose top-scoring answer (+50) is from copying a blog post from 2006… and whose second-highest scoring answer is from copying a blog post from 2011… and whose third-highest scoring answer is, well, you get the drill, I think that we should at least remove any reputation gain from those answers. Reputation is very much part of the game there; if you aren't too stupid or uninformed to do a web search for good, relevant preexisting blog posts, plagiarism is an easy way to earn lots of points. If plagiarism wasn't a good way to earn reputation, that would at least remove some of the incentive.
Can we have a procedure to remove reputation gains from plagiarized posts? Deletion isn't the answer because the posts are relevant and useful to future visitors. (Note that if the posts violate the author's copyright, that's a completely different matter; that complaint must come from the author themself through the formal channel of copyright counterclaims.) Community wiki conversion would only prevent future upvotes from mattering.
Is there a procedure we can follow (we being community members, moderators and Stack Exchange staff) to deny all reputation from plagiarized posts, even if (as often happens) they are discovered months after the fact?
I realize that "remove the poster's reputation gain from this list of posts" is a very dangerous tool — is there a better solution? What controls should be in place to make this both practically doable and not abusable?

A: Once upon a time, there was a feature that would retroactively make a post community wiki, thus erasing any/all reputation gains/losses.
So far as I'm aware, it was dev-only and rarely used. It hasn't existed in years, and I've no first-hand experience with it so pardon the lack of detail in my description...
...the point is, the feature you're asking for used to exist! It was removed because, it turns out, a "deny all rep" button is entirely too tempting - I know I routinely encounter posts that I'd prefer weren't pushing their authors toward getting privileges on the site; not just plagiarism, but grandstanding, hyperbolic opinionated rants purporting to be "the voice of experience", properly-attributed posts that none the less consist entirely of copied content, answers that link to w3schools... Not saying I would hammer these, but... Taking that option off the table keeps us honest.
And that's really the issue here, after all: honesty. If someone can earn a few upvotes by being good at searching, more power to 'em - as long as they make it clear that's what they're doing. Pretending to have written an answer you pulled off someone's blog is dishonest; regardless of whether or not the answer might have "deserved" the votes, or the author the reputation, the issue is the author's behavior.

Can we have a procedure to remove reputation gains from plagiarized posts?

Yes:

*

*immediately suspend the plagiarist.

*If he repeats it, suspend for longer.

*If he still doesn't get the message, delete the account.

All of these remove reputation gains. #3 removes them permanently.
I still believe that most of these posts should be unceremoniously deleted, at least until the author or someone else feels they're useful enough to edit - but that's a separate decision, and one that should be made based on the perceived usefulness of the post. The behavior of the author is not something where there is room for compromise, however.


text:
Q: PlayN 2.0 - How to prevent Android from autoscaling images? I am using PlayN 2.0 and I need to prevent Android from autoscaling images based on DPI. From what I've learned it seems that I need to store the images in /res/drawable-nodpi. My question is: Does this mean that I need to store the images in /res/drawable-nodpi instead of /assets? If so, what would be the most elegant way to achieve this when using PlayN 2.0?
Note: I'm new to both PlayN and Android. The autoscaling doesn't happen on all devices I tested. Is it possible that I'm missing something and the autoscaling effect is caused by something else? Any suggestions will be appreciated. Thanks!

A: The question has been answered here: https://groups.google.com/forum/#!topic/playn/B-22qA0jSWs
Summary of the answer: The density based scaling is performed by PlayN, not by Android. Disabling the scaling can be done by overriding the scaleFactor() method of GameActivity.


text:
Q: Composable not recomposing when ViewModel updated from a different Composable I am developing an Android app using Jetpack Compose. The app shows a list of items.
It also has a top bar containing a search bar.
We have 3 composable: the list of items, the search bar component, and the app bar
(the app bar contains the search bar).
The same ViewModel class is injected in the list composable and the search bar composable (using Hilt).
The ViewModel has the list of items:
var items by mutableStateOf<List<Item>?>(null)
as well as a search function, called by the search bar, to filter these items.
The problem is the following: the list composable is not recomposing when searching items.
NB:

*

*I log the output of the search function so I am sure that the function is working fine.

*When placing the searchbar composable in the same composable containing the list of items, the search works as expected.

So it seems that the list is recomposing only when the searchbar is in it.
How to make it working when the searchbar is in the app bar?
Thank you,
Edit:
By generating a random value when a ViewModel is initialized, it seems that Hilt is injecting two different instances in Searchbar composable and items composable.
Is it possible to inject ViewModel as a singleton? or should I save my data in the repository and then serve these data to the ViewModel?
Here's the code of the different classes:
Searchbar.kt
@Composable
fun SearchBar(itemViewModel: ItemViewModel = hiltViewModel()){
var searchText by remember { mutableStateOf("") }

    BasicTextField(
        singleLine = true,
        cursorBrush = SolidColor(Color.White),
        value = searchText,
        onValueChange = {
            searchText = it
            itemViewModel.searchByLabel(it)
        },
        modifier = Modifier
            .fillMaxWidth()
            .height(28.dp),
        textStyle = LocalTextStyle.current.copy(
            color = Color.White,
            fontSize = MaterialTheme.typography.body2.fontSize
        ),
        decorationBox = { innerTextField ->
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Icon(
                    Icons.Filled.Search,
                    contentDescription = "Search"
                )
                Column(Modifier.weight(1f)) {
                    Box(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        if (searchText.isEmpty()) {
                            Text(
                                "Search",
                                style = LocalTextStyle.current.copy(
                                    color = Color.White.copy(alpha = 0.7f),
                                    fontSize = MaterialTheme.typography.body2.fontSize
                                )
                            )
                        }
                        innerTextField()
                    }
                }
                if (searchText.isNotEmpty()) {
                    IconButton(onClick = { searchText = "" }) {
                        Icon(Icons.Filled.Cancel, contentDescription = "Delete")
                    }
                }
            }
        }
    )
}

Items.kt
@Composable
fun Items(
    navController: NavController,
    itemViewModel: ItemViewModel = hiltViewModel(),
){
    val items = itemViewModel.items
    items?.let { items ->
        LazyColumn(
            modifier = Modifier.fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {

            items(items) { item ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            navController.navigate("items/${item.id}")
                        },
                    Arrangement.spacedBy(8.dp)
                ) {
                    Text(item.label)
                }
            }
        }
    } ?: run {
        Text(
            text = "No protocols",
            modifier = Modifier.fillMaxWidth()
        )
    }
}

ItemViewModel.kt
@HiltViewModel
class ItemViewModel @Inject constructor(private val repository: ItemRepository) : ViewModel() {
     var items by mutableStateOf<List<Item>?>(null)

     init{ loadItems() }

     private fun loadItems(){
         viewModelScope.launch {
             items = repository.getItems()
         }
     }

     fun searchByLabel(value: String){
         viewModelScope.launch {
             items = repository.search(value)
         }
     }
}

ItemRepository.kt
class ItemRepository(){
    suspend fun getItems(): List<Item>? {
        return listOf(Item(1, "Label 1"), Item(2, "Label 2"), Item(3, "Label 3"))
    }

    suspend fun search(value: String): List<Item>? {
        return getItems()?.filter { it.label.lowercase().contains(value.lowercase())}
    }
}

Item.kt
data class Item(var id: Int, var label: String){}

A: I ended up storing data in the repository, which is injected as singleton. This way, even if multiple instances of a ViewModel are created, they still access the same data.


text:
Q: jmeter showing error when HTTP request is made I am totally new to JMeter, when I tried to test a website.
The test result was like this
Thread Name: Thread Group 1-1
Sample Start: 2018-06-19 10:18:49 IST

Load time: 0

Connect Time: 0

Latency: 0

Size in bytes: 1176

Sent bytes:0

Headers size in bytes: 0

Body size in bytes: 1176

Sample Count: 1

Error Count: 1

Data type ("text"|"bin"|""): text

Response code: Non HTTP response code: java.net.URISyntaxException

Response message: Non HTTP response message: Expected closing bracket for IPv6

What might be the issue?

A: Looks like improper HTTP Request sampler configuration, for instance you put some not supported character into "Server Name or IP" field. Well-behaved request should look like:

Another option is placing the full URL into "Path" field like

However the best option will be just recording your test scenario using JMeter's HTTP(S) Test Script Recorder, this way JMeter will generate appropriate HTTP Request samplers which you will be able to replay with increased number of threads. See Apache JMeter proxy Step-by-step guide for comprehensive instructions.
Alternatively you can use JMeter Chrome Extension - in this case you will not have to set up proxies and worry about SSL certificates.


text:
Q: setting up upstream with nginx and node? I have three instances on aws. one for nginx which the front-end server, and two backend nodejs intstances.
Im trying to set up the nginx server to upstream to these node.js instances:
upstream node_servers {
        server private_ip:8124 weight=10 max_fails=3; // node server 1 private_ip:port
        server private_ip:8124 weight=10 max_fails=3; // node server 2 private_ip:port
}
server {
    listen  private_ip:80;     // nginx server private ip:port
    root /home/ubuntu/project/;
    server_name public_ip.eu-west-1.compute.amazonaws.com;  // nginx public DNS
    location / {

                try_files $uri $uri/ /index.html;
                proxy_pass http://node_servers/;

     }
}

on my node 1 server, node 2 server instance app.js code:
app.listen(8124, "127.0.0.1");
console.log("listening on 8124");

I go to the nginx server public domain name, and nothing really happens, its just loads forever sending request.....

A: In your node code, you are listening on the loopback interface on 127.0.0.1 (requests from localhost only):
app.listen(8124, "127.0.0.1");

You have to listen on your specific private IP or 0.0.0.0:
app.listen(8124, "0.0.0.0");


text:
Q: Problema al fusionar dos objetos en JavaScript Tengo que fusionar dos objetos en uno, pongo ejemplos simples de lo que necesito hacer:
var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2A' }
];

var obj2 = { Prop3 : 'Valor 3A', Prop4 : 'Valor 4A', Prop5 : 'Valor 5A' }

Y tengo que crear un objeto final que quede con este resultado:
var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A', Prop3 : 'Valor 3A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2A', Prop4 : 'Valor 4A' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2A', Prop5 : 'Valor 5A' }
];

Lo que necesito es hacer un 'merge' de objetos en el que cada clave/valor del obj2 sea añadido en cada item del obj1.
He probado hacer esto pero no me devuelve el resultado correcto.
obj1.forEach(function(elem) {
    for(i in obj2) {
        elem['prop_nueva'] = obj2[i];
    }
});

Espero vuestra ayuda, gracias.

A: Lo puedes hacer así:

var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2B' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2C' }
];

var obj2 = { Prop3 : 'Valor 3A', Prop4 : 'Valor 4A', Prop5 : 'Valor 5A' }

let i=0;
for (propiedad in obj2) {
  console.log('copia', propiedad,'a', obj1[i]);
  obj1[i][propiedad]=obj2[propiedad];
  i++;
}
console.log(obj1);

Tienes que asegurarte de que el número de propiedades y el número de elementos en el array sea compatible

A: Mira a ver que te parece:

var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2A' }
];

var obj2 = { Prop3 : 'Valor 3A', Prop4 : 'Valor 4A', Prop5 : 'Valor 5A' }

Object.prototype.merge = function(obj2){
   let i=0, keys = Object.keys(obj2);
  for( o of this){
    this[i][keys[i]] = obj2[keys[i]];
    i++;
  }
}

obj1.merge(obj2)

console.log(obj1)

te va poniendo clave:valor del segundo objecto al final de cada objecto de la primera lista.


text:
Q: excel vba copy multiple column based on column header listed in cell ranges I want to copy multiple columns from sheet1 to sheet2 based on column header (eg. Date, Name, ID, Amount,etc), the column header is listed in sheet3, A1:A10.eg. Date, Name, ID, Amount,etc.
After googling for few hours, i got below code, but it only work copying one single column, how can i copy multiple column? which part of the code do i need to change? Would appreciate your time and help.
Thank you.
Sub CopySpecifcColumn()

    Set MR = Range("A1:e1")

    For Each cell In MR

        If cell.Value = "Date" Then cell.EntireColumn.Copy

    Next

End Sub

A: You are only copying one column (the "Date" column), because your If statement only copies the Date column. By continuing with your current method, you can copy the columns of the rest of the data in Range("A1:e1") by writing statements for those columns like so:
Set MR = Range("A1:e1")

For Each cell In MR

If cell.Value = "Date" Then
    cell.EntireColumn.Copy
End If

If cell.Value = "Name" Then    '<- Add these for each column title
    cell.EntireColumn.Copy
End If

If cell.Value = "ID" Then
    cell.EntireColumn.Copy
End If

If cell.Value = "Amount" Then
    cell.EntireColumn.Copy
End If

Next cell

There is another way of doing this by storing each Column Title in an array, and to copy each column by looping through the array which shortens the code and can be written more flexibly. Looping through ONLY the column titles in an array is also much faster than searching through each cell of the column ranges.
Looping by Column Titles would go something like this, with more details to work out:
Dim Sh2Cell As Range
Dim Sh3Cell As Range
Dim Sh2Title As Range
Dim Sh3Title As Range

Set Sh2Title = Sheet2.Range("Title Range")
Set Sh3Title = Sheet3.Range("Title Range")

For Each Sh2Cell In Sh2Title
    For Each Sh3Cell In Sh3Title
        If Sh2Cell = Sh3Cell Then
            'Copy column'
        End If
    Next
Next

A: Untested:
Sub CopyCols()

    Dim h As Range, f As Range, sht1, rngDest As Range

    Set sht1 = ThisWorkbook.Sheets("Sheet1")
    Set rngDest = ThisWorkbook.Sheets("Sheet2").Range("a1") 'start pasting here

    'loop through the headers to copy
    For Each h In ThisWorkbook.Sheets("Sheet3").Range("A1:A10").Cells
        'find the header on sheet1
        Set f = sht1.Rows(1).Find(h.Value, , xlValues, xlWhole)
        If Not f Is Nothing Then
            'found the header: copy the column
            f.EntireColumn.Copy rngDest
            Set rngDest = rngDest.Offset(0, 1) ' move destination
        End If
        Set f = Nothing
    Next h

End Sub

A: You have two possibilities here.

*

*This one is more in way with your code. Instead of checking If cell.Value = "Date" you need to check if cell.Value exists in Sheet3, A1:A10. Find method should be fine here, however, it returns error if the value was not found. Be aware of this.

*This one will work the other way around. For every cell in Sheet3, A1:A10, find a column header in sheet1 and copy that column. Find method will work here again, but it will be safer, as long as you keep names in Sheet3 without typos.

Of course you still need to paste copied data before you copy next column. There is third way to do this, by selecting all columns and then copy all of them, but I find it more complicated, and pasted data can have empty columns.


text:
Q: Sequencing code in a multithreaded environment I have a multithreaded C++ MFC application. I have one worker thread to execute my program logic, and the main thread is dedicated to handling GUI events. The GUI thread spawns the program logic threads, and detaches execution from it, like this -
void CMyDocument::InGUIThread()
{
    std::thread tProgramLogic(programLogicThreadFunction);
    tProgramLogic.detach()
}

My program logic takes roughly 5 minutes to execute.
Here is my problem : I want to call a function in the main GUI thread after my program logic has finished execution. How do I signal my main thread from the programLogic thread as it nears the end of execution?
P.S. The reason I detach my programLogic thread is so that I dont freeze my main thread, and thus it is responsive to GUI events.

A: You could go for a C++11 async solution and poll the result with wait_for, but in your specific case (in a Windows environment) I'd go for an even better solution:
1) Define a custom WM_ message and map it for handling, e.g.
 #define WM_MYMSG (WM_USER + 42)
 BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
     ON_MESSAGE(WM_MYMSG, ThreadHasFinished)
 END_MESSAGE_MAP()

2) Post WM_MYMSG when your logic thread ends to the main window with
3) Handle the logic's termination in ThreadHasFinished


text:
Q: scrollview is not working I got a list in my main but problem is that when I scan the barcodes for more than 15 barcodes, then it didn't show the"scan" button already and I tried to use the scroll view for that but it is not working :
Any helps?
     <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:fillViewport="true">
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
          <ListView
  android:id="@android:id/list"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"

/>
<TextView
  android:id="@android:id/empty"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="no notes"
   />
<Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="scan"/>

</LinearLayout>
</ScrollView>

Any suggestions?

A: Generally it is a bad idea to place a listview inside of the scrollview.  It doesn't work as expected.  See the following post:
https://groups.google.com/forum/?fromgroups#!topic/android-beginners/LRpLgGOy2Pc

A: In Android it's not possible to use a ListView in a ScrollView. In order to achieve the same result you can use a ListView and add a header and a footer.
addHeaderView()
You can use a ListActivity. Create one xml layout file for your header and add it to the ListView: (put the Code in your onCreate() function before calling setAdapter())
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getListView().addHeaderView(inflater.inflate(R.layout.header, null));
getListView().addFooterView(inflater.inflate(R.layout.footer, null));

The footer works exactly the same way.

A: Hi, you can use RelativeLayout instead of LinearLayout.
In such case you should place your button at the bottom of the layout. After that other controls should be placed above the button. RelativeLayout has special xml-attributes to help you do this. After that you do not need a ScrollView.


text:
Q: User selected values from JSON When a user fills out a form in a mobile application a json is created. I load this json into a postgres database and wanting to pull is apart and select the inputs that the user has selected.
I find this hard to explain you really need to see the json and the expected results. The json looks like this...
{
   "iso_created_at":"2019-06-25T14:50:59+10:00",
   "form_fields":[
      {
         "field_type":"DateAndTime",
         "mandatory":false,
         "form_order":0,
         "editable":true,
         "visibility":"public",
         "label":"Time & Date Select",
         "value":"2019-06-25T14:50:00+10:00",
         "key":"f_10139_64_14",
         "field_visibility":"public",
         "data":{
            "default_to_current":true
         },
         "id":89066
      },
      {
         "field_type":"Image",
         "mandatory":false,
         "form_order":6,
         "editable":true,
         "visibility":"public",
         "label":"Photos",
         "value":[

         ],
         "key":"f_10139_1_8",
         "field_visibility":"public",
         "data":{

         },
         "id":67682
      },
      {
         "field_type":"DropDown",
         "mandatory":true,
         "form_order":2,
         "editable":true,
         "visibility":"public",
         "label":"Customer ID",
         "value":"f_10139_35_13_35_1",
         "key":"f_10139_35_13",
         "field_visibility":"public",
         "data":{
            "options":[
               {
                  "is_default":false,
                  "display_order":0,
                  "enabled":true,
                  "value":"f_10139_35_13_35_1",
                  "label":"27"
               }
            ],
            "multi_select":false
         },
         "id":86039
      },
      {
         "field_type":"CheckBox",
         "mandatory":true,
         "form_order":3,
         "editable":true,
         "visibility":"public",
         "label":"Measure",
         "value":[
            "f_7422_10_7_10_1",
            "f_7422_10_7_10_2"
         ],
         "key":"f_10139_1_5",
         "field_visibility":"public",
         "data":{
            "options":[
               {
                  "is_default":true,
                  "display_order":0,
                  "enabled":true,
                  "value":"f_7422_10_7_10_1",
                  "label":"Kg"
               },
               {
                  "is_default":true,
                  "display_order":0,
                  "enabled":true,
                  "value":"f_7422_10_7_10_2",
                  "label":"Mm"
               }
            ],
            "multi_select":true
         },
         "id":67679
      },
      {
         "field_type":"ShortTextBox",
         "mandatory":true,
         "form_order":4,
         "editable":true,
         "visibility":"public",
         "label":"Qty",
         "value":"1000",
         "key":"f_10139_9_9",
         "field_visibility":"public",
         "data":{

         },
         "id":85776
      }
   ],
   "address":"Latitude: -37.811812 Longitude: 144.971745",
   "shape_id":6456,
   "category_id":75673,
   "id":345,
   "account_id":778
}

Can anyone help me?
Expected results:
account_id | report_id | field_label        | field_value
------------------------------------------------------------------------
778        | 345       | Time & Date Select | 2019-06-25T14:50:00+10:00
778        | 345       | Photos             |  []
778        | 345       | Customer ID        | 27
778        | 345       | Measure            | Kg
778        | 345       | Measure            | Mm
778        | 345       | Qty                | 1000

A: like say @Amadan, might need to hardcode each field separately instead of making a clever loop ,especially with the fields "Customer ID" "and" "Measure" or any other that requires it.
You can use the json function: json_array_elements_text, here you have a example, you can adjust to your case, i am trying with your case:
select account_id::text,report_id::text,field_label::text,
--case ""Customer ID"" and ""Measure""
case
when field_label::text='"Customer ID"' then  ((todo->'data'->'options')->0->'label')::text
when field_label::text='"Measure"' then  ((todo->'data'->'options')->0->'label')::text ||',' ||((todo->'data'->'options')->1->'label')::text

else
field_value::text
end as field_value
from
(
select dato->'account_id' as account_id,dato->'id' as report_id,
(json_array_elements_text(dato->'form_fields')::json)->'label' as field_label,
(json_array_elements_text(dato->'form_fields')::json)->'value' as field_value,
(json_array_elements_text(dato->'form_fields')::json) as todo
from (
select '{"iso_created_at": "2019-06-25T14:50:59+10:00",  "form_fields": [
{"field_type": "DateAndTime", "mandatory": false, "form_order": 0, "editable": true, "visibility": "public", "label": "Time & Date Select", "value": "2019-06-25T14:50:00+10:00", "key": "f_10139_64_14", "field_visibility": "public", "data":
 {"default_to_current": true}, "id": 89066},

 {"field_type": "Image", "mandatory": false, "form_order": 6, "editable": true, "visibility": "public", "label": "Photos", "value": [], "key": "f_10139_1_8", "field_visibility": "public", "data": {}, "id": 67682},

  {"field_type": "DropDown", "mandatory": true, "form_order": 2, "editable": true, "visibility": "public", "label": "Customer ID", "value": "f_10139_35_13_35_1", "key": "f_10139_35_13", "field_visibility": "public", "data": {"options": [{"is_default": false, "display_order": 0, "enabled": true, "value": "f_10139_35_13_35_1", "label": "27"}], "multi_select": false}, "id": 86039},

 {"field_type": "CheckBox", "mandatory": true, "form_order": 3, "editable": true, "visibility": "public", "label": "Measure", "value": ["f_7422_10_7_10_1","f_7422_10_7_10_2"], "key": "f_10139_1_5", "field_visibility": "public", "data": {"options": [{"is_default": true, "display_order": 0, "enabled": true, "value": "f_7422_10_7_10_1", "label": "Kg"},{"is_default": true, "display_order": 0, "enabled": true, "value": "f_7422_10_7_10_2", "label": "Mm"}], "multi_select": true}, "id": 67679},

 {"field_type": "ShortTextBox", "mandatory": true, "form_order": 4, "editable": true, "visibility": "public", "label": "Qty", "value": "1000", "key": "f_10139_9_9", "field_visibility": "public", "data": {}, "id": 85776}

 ], "address": "Latitude: -37.811812 Longitude: 144.971745", "shape_id": 6456, "category_id": 75673, "id": 345, "account_id": 778}'::json as dato) as dat
 ) dat2

and i get this result, similar to you:

take this example and ajust to you
regards

A: You need to unnest the values in form_fields and then pick the label and the value from that JSON object:
select fd.account_id,
       fd.report_id,
       ff.field ->> 'label' as field_label,
       ff.field ->> 'value' as field_value
from form_data fd
  left join jsonb_array_elements(data -> 'form_fields') as ff(field) on true;

The left join is needed to still see the row from form_data even if no form_fields is available in the main JSON column.
The above assumes a table form_data with the columns account_id, report_id and data (which contains the JSON)
Online example: https://rextester.com/RNIBSB94484


text:
Q: Waiting queue vs. Ready queue Why is there a Ready and Waiting queue for every object when using a monitor? If a thread is done with an object, just pop the next item in the Waiting queue. The Ready queue seems redundant.
The context is .NET, more specifically the monitor class.

A: A producer/consumer queue is a really good use case for learning about the Monitor class.
Assume that work is sporadically added to the queue.  Sometimes there are a lot of items needing to be processed, sometimes long periods of time will elapse with no items in the queue.
So, let's say you have k consumer threads waiting around to process items in the queue.  In other words, each thread implements a tight loop, constantly trying to

*

*Request to get the lock on the queue (this puts you in the Monitor's "ready" queue).

*Once you get the lock, check if the queue has any items.  If not, you have two choices for releasing the lock:
a) Call Monitor.Exit, and then call Monitor.Enter to put yourself in the back of the "ready" queue.
b) Or, call Monitor.Wait, and put yourself in the Monitor's "waiting" queue.

If you choose option "a", your k threads will be wasting CPU cycles moving through the ready queue over and over, finding no work to do, and starting all over again at the back of the queue.
If you choose option "b", you're saying "there's nothing here to do right now, let me sleep, and wake me up when there's something to do".
With option "b", if the queue is empty, you will soon find all of your consumers sleeping in the "waiting" queue, and no CPU time being wasted.
Then, when a producer adds an item to the queue, it calls Monitor.Pulse.  This wakes up the first thread in the "waiting" queue, which then goes to the back of the "ready" queue (which is also the front of the queue if the "ready" queue was empty).
When a thread gets the lock and consumes this item from the queue, it calls Monitor.Enter again, and goes to the back of the "ready" queue.
See this article for a classic implementation of a producer/consumer queue in .NET.

A: Assuming I've understood your question properly, the two serve different purposes.
The "ready" queue is for threads which are ready to run as soon as they can obtain the lock. They're just waiting to acquire the lock. This is mostly used for mutual exclusion, to prevent two threads from both using the same resource at the same time.
The "waiting" queue is for threads which are waiting for a particular signal - namely the monitor being pulsed. This is often used for co-ordination - for example in a producer/consumer queue, where if the queue is empty, a consumer will wait until a monitor is pulsed before it checks the queue again. While no-one is producing and no-one is consuming, no thread owns the monitor - there's no resource in use. But the monitor is used to co-ordinate the consumer with the producer.


text:
Q: GCC compile error I am trying to build and run GCC. After trying to build it a couple different ways I got it to build, however when I try to compile code (example:)
gcc -fopenacc -foffload=nvptx-none -o foo foo.c

with it I get this error:
lto-wrapper fatal error problem with building target image for nvptx-none

I tried to ask the internet for this question, and while others have reported this issue, there has been no solutions posted. I am using GCC6.


text:
Q: Equalize height of two/more child div of two/more different parent using CSS We have div's in separate parent like parent 1 and parent 2 as shown in below image.
We want to make height of both child div's are same by using CSS.
Something like child of Parent 2 should take height of child of Parent 1 or wise-versa.

We already have JS code to do equalization but it was failed in some cases, where some div's are hidden with their parents. So in that case the highest height of children are not able to fetch and assign to visible child div's.


text:
Q: Top Level Exception - Android Studio I have been getting Top level exception in android studio, i am using appcompat and sliding menu library. I know i am getting the exception because of conflict of Android Support Libraries as explained in some of the previous threads in stackoverflow. I have tried All the the methods shown in threads like including configuraion etc.
here is my Build.gradle(root)
// 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:1.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
    configurations {
        // to avoid double inclusion of support libraries
        all*.exclude group: 'com.android.support', module: 'support-v4'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Here is my Build.Gradle(App)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion '21.1.1'

    defaultConfig {
        applicationId "com.danaraddi.cprograms"
        minSdkVersion 8
        targetSdkVersion 21
        versionCode 9
        versionName "7.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        incremental true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.2'
}

// animations
dependencies {
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.0@aar'
    compile 'com.daimajia.androidanimations:library:1.0.8@aar'
}

// inject views
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.jakewharton:butterknife:5.1.2'
}

dependencies {
    // Your other dependencies go here
    compile project(':library')
}

Here is my Build.Gradle(Lib - SlidingMenu)
    buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
    }
}
apply plugin: 'android-library'

dependencies {
    compile 'com.android.support:support-v4:13.0.0'
}

android {
    compileSdkVersion 21
    buildToolsVersion '21.1.1'

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }

    sourceSets {
        main {
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']

            manifest.srcFile 'AndroidManifest.xml'
        }
    }

}

Here is my Log Cat
Error:Execution failed for task ':app:dexDebug'.

Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Landroid/support/v7/app/ActionBar$Callback;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:302)
        at com.android.dx.command.dexer.Main.run(Main.java:245)
        at com.android.dx.command.dexer.Main.main(Main.java:214)
        at com.android.dx.command.Main.main(Main.java:106)

PS : I Have places configuration in root,app build.gradle too , it builds successfully after a clean project and then after the same error.

A: Add
dexOptions {
    preDexLibraries = false
}

instead of
dexOptions {
        incremental true
    }

to build.gradle file inside the android block


text:
Q: Function call as iterable in for of loop ES6 Looking for best practice advice.
Is it a good practice to have function call in for of as iterable object?
const obj = {key1:'a', key2:'b'};

for(const i of Object.keys(obj)){ ... }

or better to have
const obj = {key1:'a', key2:'b'};
const allKeys = Object.keys(obj);
for(const i of allKeys){ ... }

Isn't Object.keys function called on every iteration of the loop?

A: you can check it by mocking a similar case

function A(){
    console.log('function called');
    return [1, 2, 3, 4, 5];
}

for(let i of A()){
    console.log(i);
}

As you can see A() is called only once

A: Your first example does the same thing as the second, just without the allKeys constant. In your first example:
const obj = {key1:'a', key2:'b'};

for(const i of Object.keys(obj)){ ...

...Object.keys will only get called once, and then its iterator will be retrieved and used for the loop. (This is covered in ForIn/OfHeadEvaluation in the spec, but it's...heavy going.) So you're fine using that form, it's not inefficient.

A: The call to Object.keys is only made once in both variants.
But consider also as possibility this for loop that does not depend on Object.keys:
for (const prop in obj) {  }

Object.keys creates an array, while the above for loop does not. The latter only retrieves the items as necessary. Of course, if your for loop is never exited prematurely, it will still retrieve all of them, so this only makes a difference when you plan to exit the loop prematurely. In that case the corresponding iterator never visits the remaining items, while Object.keys would already have done so in creating the array.
One thing to pay attention to: a for .. in loop will also iterate enumerable inherited properties, not only own properties, while Object.keys will only list own enumerable properties. You can add an extra test in the for loop to exclude non-own properties:
if (obj.hasOwnProperty(prop))


text:
Q: CSS fluid layout scaling content I have a CSS question you may be able to help with.
I'm trying to build a website with a 'Fluid' layout.
All website content will be contained within a wrapper div
When the screen shirks, I Would like the wrapper div to shirk along with it's content.
However, when the screen size is increased, I would like the wrapper div to maintain a max size. The aim is to prevent images scaling beyond their native resolution and the formatting of text changing (a paragraph may become a single line on very large screen)
Can I apply a max pixel with and a percentage to the wrapper DIV? is there a better way to achieve the goal?
.wrapper {
    margin: 0 auto;
    max-width: 800px;
    width: 80%;
    background-color: #ffffff;
    border: 1px solid;
    height: 1000px;
    }

Many thanks,
P

A: Yes, you can do this and it is a good practice.

A:
Can I apply a max pixel with and a percentage to the wrapper DIV?

YES, you can apply it
.wrapper {
    margin: 0 auto;
    max-width: 800px;
    width: 80%;
    background-color: #ffffff;
    border: 1px solid;
    height: 1000px;
    }

the width: 80%; means 80% of the screen width(or browser window) and it will not exceed   max-width: 800px;

The max-width property in CSS is used to set the maximum width of a
  specified element. The max-width property overrides the width
  property, but min-width will always override max-width whether
  followed before or after width in your declaration.


text:
Q: Is it possible to change what a thread is doing in Ruby? Say I create a thread like this:
thread = Thread.new do
 loop do
  puts "tick"
  sleep(1)
 end
end

What if somewhere down the line I want this thread to stop doing that and execute some_method(), how would I do that?

A: Have the other thread set a variable, and this thread check its value. The approach is elaborated in this answer: sleep until condition is true in ruby
If puts "tick" isn't necessary you could use a condition variable instead.


text:
Q: Hibernate index mapping (double column primary key) Say I have a primary key with two columns (a, b).
Will Hibernate create a singular index on both columns as well?
example output:
index on a
index on b
index on (a,b)

A: visit : http://www.objectdb.com/java/jpa/entity/index
How to define index by several columns in hibernate entity?


text:
Q: Strange characters in a function with pyspark I'm trying to understand how PySpark works with strange characters (for example Spanish accents).
If I put
print 'áááájgmdkfk'

It works and print
Áááájgmdkfk
But, if I define a function with strange characters, I get an error:
def dummy():
    print 'áááájgmdkfk'

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 1: ordinal not in range(128)

Does anyone know why I can't use strange characters in a function?


text:
Q: CS0029: Cannot implicitly convert type 'System.DateTime' to 'var My web application was working perfectly. There was no issue with that.
Suddenly I was need to add a reference of System.Web.Helpers.ddl in my project. After adding this in my project I am getting an error
Cannot implicitly convert type 'System.DateTime' to 'var' on this line var date = DateTime.Now.AddYears(i);
before this it was working perfectly, I didn't made any change in my code.
protected void Bind_Year()
{
    try
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Year", typeof(int));
        for (int i = -2; i < 4; i++)
        {
            var date = DateTime.Now.AddYears(i);
            var year = date.Year;
            dt.Rows.Add(year);

        }
        DropDownList3.DataSource = dt;
        DropDownList3.DataBind();

    }
    catch (Exception ex)
    {
        WebMsgBox.Show(ex.Message);
    }

}

A: The problem here is that you got a type somewhere named var.
I didn't think this was possible myself, so I tried it in LINQPad:
void Main()
{
    var x = DateTime.Today;
}
public class var
{
}

Sure enough, it gives me this compiler error:

Cannot implicitly convert type 'System.DateTime' to 'UserQuery.var'

So apparently you must have such a class in your project, or in a referenced assembly.
Naming types or members the same as built-in keywords is a bad idea.
To fix this you should rename your type to something else. Unless the world you're modelling have a concept called "var", I'd say a more descriptive name is probably better anyway, but if you really want the name, consider just uppercasing the V making it Var and the compiler should stop complaining.


text:
Q: Authenticate user using Microsoft Account in .Net backend Azure Mobile service giving error after login I am developing Windows 10 UWP app in that I am Implementing authenticate user using Azure Mobile Services using Microsoft account as provider.
I followed the below article for registering mobile service with the app
https://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-register-microsoft-authentication/
The following are the details I updated in my app live settings

My Mobile service is a .net backend service https://astraniprod.azure-mobile.net/
And also updated the client ID, secret, app SID in Mobile Service.
After that I have written the below code to launch the login popup in my app
private async System.Threading.Tasks.Task<bool> AuthenticateAsync()
    {
        string message;
        bool success = false;
        try
        {
            // Change 'MobileService' to the name of your MobileServiceClient instance.
            // Sign-in using Facebook authentication.
            user = await App.MobileService
                .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount,true);
            message =
                string.Format("You are now signed in - {0}", user.UserId);

            success = true;
        }
        catch (InvalidOperationException)
        {
            message = "You must log in. Login Required";
        }

        var dialog = new MessageDialog(message);
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();
        return success;
    }
}

I am able to see the login dialogue and also entered my Microsoft account and password, After that I am getting the following error

I seen other people also posted about this in forums but I didn't find the solution for the issue, I don't know where the issue is, other Providers like Google, Twitter, Facebook working fine, but only Microsoft account not working.
Thanks.

A: I think the issue is with the redirect URI.
If you open a browser to
http://astraniprod.azure-mobile.net/login/microsoftaccount
You should get a login page, login, and you'll get the "unable to complete your request" page.
In the URL is a parameter, which indicates the issue:
error_description=The+provided+value+for+the+input+parameter+'redirect_uri'+is+not+valid.+The+expected+value+is+'https://login.live.com/oauth20_desktop.srf'+or+a+URL+which+matches+the+redirect+URI+registered+for+this+client+application.
Can you make sure your app is configured to watch for a redirect to https://astraniprod.azure-mobile.net/signin-microsoft
Also, make sure you associated your app with the store as per step 2, 3, 4:
https://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-register-microsoft-authentication/
If you've done the above, it should work.  If not, we'll help look further.


text:
Q: SQL Server : pivot on multiple columns Hmm, only getting the correct title took me 10 minutes and I'm not sure I got it covering my question. Some background info: my table contains backup results from multiple servers. For simplicity some rows for just one server:
hostname    type_id result_id   received
----------------------------------------
SBS2011       5        1      2016-06-28
SBS2011       5        1      2016-06-28
SBS2011       5        1      2016-06-29
SBS2011       5        1      2016-06-29
SBS2011       5        1      2016-06-30
SBS2011       6        1      2016-06-30
SBS2011       5        2      2016-07-01
SBS2011       6        2      2016-07-01
SBS2011       6        2      2016-07-01
SBS2011       5        1      2016-07-02
SBS2011       6        1      2016-07-02
SBS2011       5        1      2016-07-03
SBS2011       6        1      2016-07-03
SBS2011       5        1      2016-07-04
SBS2011       6        1      2016-07-04

Using a PIVOT I can get an overview of the amount of backups for each weekday:
select * from
(
    select [hostname], [type_id], datepart(w, received) as workday from [backups]
) TEMP
pivot (
    count([type_id])
    for workday in
    ([1], [2], [3], [4], [5], [6], [7])
) as pvt;

Results in:
hostname    1   2   3   4   5   6   7
--------------------------------------
SBS2011     2   2   2   2   2   3   2

But this result misses some crucial info. As result_id equals 'success' and result_id equals 'failed', I would like to have the result to look like this:
hostname    1:1 1:2 2:1 2:2 3:1 3:2 4:1 4:2 5:1 5:2 6:1 6:2 7:1 7:2
-------------------------------------------------------------------
SBS2011     2   0   2   0   2   0   2   0   2   0   0   3   2   0

where columnname 1:1 is shorthand for sunday:success and 1:2 equals sunday:failed. For some backup type_id's, there may be also a column 1:3 for sunday:retry.
As I looked around, I found that a DYNAMIC PIVOT may be the key in solving this puzzle. Others suggest a PARTITION BY, but I have not yet found out how. The DYNAMIC PIVOT seems the most promising, but I do not know how. Please help me create this - for me complex - query?

A: Check this out and see if it solves your issue... pretty sure I can simplify this further but need to know what the decodes are for type_id ( 5 and 6  ). will there be more type_id's ?
Also  result_id = 1 = Success and 2 = Failure right ?
Question what happens when the backup is not run at all on a particular day :) ? how do you handle that situation as there will be no records for that day. :)
/* Create table and populate with sample data.
create table Backups (hostname varchar(10),    type_id int , result_id int ,  received datetime)

insert into Backups (hostname ,   type_id ,result_id ,  received ) values
('SBS2011',       5  ,      1      ,'2016-06-28'),
('SBS2011',       5   ,     1      ,'2016-06-28'),
('SBS2011',       5   ,     1      ,'2016-06-29'),
('SBS2011',       5   ,     1      ,'2016-06-29'),
('SBS2011',       5   ,     1      ,'2016-06-30'),
('SBS2011',       6   ,     1      ,'2016-06-30'),
('SBS2011',       5   ,     2      ,'2016-07-01'),
('SBS2011',       6   ,     2      ,'2016-07-01'),
('SBS2011',       6   ,     2      ,'2016-07-01'),
('SBS2011',       5   ,     1      ,'2016-07-02'),
('SBS2011',       6   ,     1      ,'2016-07-02'),
('SBS2011',       5   ,     1      ,'2016-07-03'),
('SBS2011',       6   ,     1      ,'2016-07-03'),
('SBS2011',       5   ,     1      ,'2016-07-04'),
('SBS2011',       6   ,     1      ,'2016-07-04')

select * , DatePart(w, received) from dbo.Backups b

*/

The Query:
SELECT -- S.*, F.*
        S.[hostname],
        S.[1] as [1:1],
        F.[1] as [1:2],
        S.[2] as [2:1],
        F.[2] as [2:2],
        S.[3] as [3:1],
        F.[3] as [3:2],
        S.[4] as [4:1],
        F.[4] as [4:2],
        S.[5] as [5:1],
        F.[5] as [5:2],
        S.[6] as [6:1],
        F.[6] as [6:2],
        S.[7] as [7:1],
        F.[7] as [7:2]

FROM
(
    select * from
    (
        select [hostname], [type_id], datepart(w, received) as workday , result_id as res_type from [backups] where result_id = 1

    ) TEMP
    pivot
    (
        count([type_id])
        for workday in
        ([1], [2], [3], [4], [5], [6], [7])
    ) as pvt

) S
LEFT OUTER JOIN
(
    select * from
    (
        select [hostname], [type_id], datepart(w, received) as workday , result_id as res_type from [backups] where result_id = 2

    ) TEMP
    pivot
    (
        count([type_id])
        for workday in
        ([1], [2], [3], [4], [5], [6], [7])
    ) as pvt

) F ON S.res_type = F.res_type - 1
WHERE F.hostname IS NOT NULL

A: If you don't want to fiddle with dynamic SQL you could just keep it static and alter the column that is pivoted on.
A query like:
select *
from
(
    select
        [hostname],
        [type_id],
        concat(datepart(w, received),':',result_id) as workday
    from [backups]
) TEMP
pivot (
    count([type_id])
    for workday in (
        -- maybe you don't want the :3 option for all days? Adjust as needed
        [1:1],[1:2],[1:3],
        [2:1],[2:2],[2:3],
        [3:1],[3:2],[3:3],
        [4:1],[4:2],[4:3],
        [5:1],[5:2],[5:3],
        [6:1],[6:2],[6:3],
        [7:1],[7:2],[7:3]
    )
) as pvt;

might give a result similar to what you want?


text:
Q: How to use multiple concepts per text gen component in Jetbrains MPS 2017.1? I created a simple DSL in JetBrains MPS for an automation task at hand. The DSL allows defining information objects which in turn shall be used for code generation. I am able to generate my models - but I am struggling to find a way to assign an additional text gen component to the same language concept, i.e. what I am trying to achieve is:

*

*information object to db model (python)

*information object to db access layer methods (python)

*information object to protobuf message

*...

I feel that I got a wrong understanding on how to use this. Any ideas on how to achieve different outputs for the same language concept?

A: MPS will only allow you to have single textgen definition per concept.
The MPS way to do what you want to do is to do this before textgen with a model to model transformation.
Define additional concept for your three objects you want to create. Their content is basically the same as in the root concept that you already have. Theses concept will only be used to define your textgen. So next define the textgen for theses concepts.
Now you still need to create instances of these because of course you don't want the user to specify theses information multiple times. To do this you need to define a generator. Generators are used for model to model transformations in MPS.
By default your language should already have a generator. In the generator is a mapping configuration main. In there you create a root mapping for each of the of the three new concepts you created. Each of this rules has as the input concept the one that the user specifies and as a template one of the new concepts. You can create a new template by pressing alt + enter in the editor and choose the concept you want to create. Make sure you set keep input root to true instead of default.
Inside the template you specify a COPY_SRC to copy all of the contents from the input to the output.
What then happens during generation is that MPS will create three new concepts out of the one that the user created in the original model and after the executes the textgen for all of them. This also allows you to create different files for each root.
I think the DEMO 1 project shows some of the things you will need for this.

A: You may want to consider the plaintextgen plugin: https://plugins.jetbrains.com/plugin/8444-com-dslfoundry-plaintextgen