text:
Q: apache flink DataSet window aggregation I'm using the DataSet API in order to read numerous files and throw them into cassandra.
In one of the steps, I'm doing a lot of HTTP requests and I would like to know how many requests per second I'm sending.
With Stream API it's pretty straight forward using a sliding window but how do you do the same with DataSet API?

A: You might want to have a look at Flink's metrics system. It features a Meter metrics type that measures rates, i.e., how often certain events happen over time.
Unfortunately, Meter metrics are not yet included in an Flink release but only available in the current master branch (Flink 1.2 SNAPSHOT). So you would need to build Flink yourself. See the documentation for details.

A: If you assign the timestamp of the requests to the objects in your DataSet, you can use the .groupBy() transformation with a key extractor that extracts the window identifier (e.g., the second parsed from the timestamp) and then apply a count aggregation.
For example, a count aggregation can be done by extending the tuple with a Integer 1 using with a .map() transformation and summarizing the Integers with the .sum() transformation after the groupBy.


text:
Q: row.names in read.csv vs read.csv.sql (package sqldf) the description for the row.names argument in read.csv.sql simply says "As in 'read.csv'"
However when I try to read in a simple csv file with the first column as the row names the behavior in read.csv.sql is not what I expect.
 d <- data.frame("a"=c(1:10), "b"=c(15:24), "c"=c(21:30), row.names=paste("r", c(1:10), sep=""))
 write.csv(d,"foo.txt", quote=T)
 head(read.csv("foo.txt", row.names=1), 3)
   a  b  c
r1 1 15 21
r2 2 16 22
r3 3 17 23

read.csv gives what I might have hoped for. When I try read.csv.sql however:
 head(read.csv.sql("foo.txt", row.names=1), 3)
 Error in try({ :
 RS-DBI driver: (RS_sqlite_import: ./foo.txt line 2 expected 5 columns of data but found      4)
 Error in sqliteExecStatement(con, statement, bind.data) :
 RS-DBI driver: (error in statement: no such table: file)

I've tried with different little things like whether or not to include quotes in the original csv file, or calling read.csv.sql with just header=T as an argument, and at best I can either get the row names as the first column of my final data frame, which would of course require further modification to get this first column as the row name and remove the first column, or to have a straightforward data frame with the row names being just numbers and the desired row names being completely lost.
Is there something I am missing in either my call to the function or the file format to get the much faster on large datasets read.csv.sql reading in column 1 as the row names without further processing of the data frame?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install odoo 12 enterprise edition in docker? Please I need to run container odoo 12 (entreprise edition) , but not community edition, I try to do:
docker run -p 9012:8069 -itd -v /volumes/odoo:/mnt/extra-addons --name od1 --link pg1:db -t odoo:12

i have tested also:
docker run -p 9012:8069 -itd -v /volumes/odoo:/mnt/extra-addons --name od1 --link pg1:db -t odoo

But when I go to browser, I find that odoo is community version ! How to have odoo enterprise edition (version 12)?

A: add another volume to your container for example -v ./config:/etc/odoo and within this directory add config file odoo.conf with addons_path set to a list containing /mnt/extra-addons in the list. To initialize odoo with enterprise edition, addons_path list must contain the path to the enterprise addons directory.


text:
Q: Type Error in Python function I'm working a small program that calculates the trajectory of an object fired on certain planetary bodies, then plots them with Turtle graphics. Currently, I'm stuck on an issue with a Type Error that I can't seem to figure out.
So, here is the stack:
Traceback (most recent call last):
File "MY FILEPATH", line 174, in <module> main()
File "MY FILEPATH", line 153, in main
    x1,y1 = xtoy(dist(velo,ang,grav),velo,ang,grav,i)
File "MY FILEPATH", line 66, in xtoy
    sety = int(dist*tan(ang)-(grav*dist**2)/(2*velo**2*cos*((cos(ang)))))
TypeError: unsupported operand type(s) for *: 'int' and 'builtin_function_or_method'

and here is a pastebin of the code.
http://pastebin.com/aY0fhGEV
I am absolutely stumped, and have been wracking my brain for a week. Any help would be truly appreciated.

A: You have 2 * cos.  This is trying to multiply the number 2 times the function cos.  You need to take the cosine of something in the second part.  Perhaps you meant 2*cos(ang)*cos(ang)?

A: You have an extra * after the second to last cos, which treats it like a built-in instead of evaluating an argument.


text:
Q: What does size of an inertial frame mean?
It is the equivalence principle that provides the bridge between the ideal $SR$ model and the real world. According to it, we can find at each event a set of local inertial frames (LIFS), which may be small or large depending on
I.) Distribution of nearby masses
ii.) Accuracy we require
Rindler: Relativity, Special, General and Cosmological, page-36

What does Rindler mean here by the smallness or largeness of an inertial frame?

A: I've never seen it phrased like that, but I understand it as the following.
Strictly speaking, the frame is defined locally, on a point. So the further you move from that point, the less inertial the frame becomes.
It's reasonable to assume that, if the mass distribution is too dense, the approximation will become bad very quickly, which would explain point 1.
As for any approximation, deciding when it becomes too bad to be useful is a matter of "taste". So it's up to the scientist to decide how big the neighborhood (in the mathematical sense) of the given point can be before the frame is too far from being inertial. That would be point 2.

A: The Equivalence Principle (EP) is valid locally: if you perform a local experiment in an inertial frame of reference, you can't say if you're freefalling or not falling, you can't say if you're attracted downwards or accelerated upwards. If you perform a nonlocal experiment, you can say what kind of motion you're following.
Of course, no physics experiment is perfectly local: a perfectly local experiment would perfectly follow the EP, and all nonlocal experiments violate the EP to some degree.
The locality of the equivalence principle is then to be meant as "if your experiment room (alias frame of reference) is small enough compared to the precision of the measurements you want to make and the intensity of outside forces, then the EP is valid".
This means that if the elevator in Einstein's gedankenexperiment was a very big elevator, big enough to perform an experiment about Earth's curvature inside it, then the observer inside could have said whether he was freefalling or not falling at all.

A: I don't have the book but I think he means the following. At any point in spacetime you can assign an inertial frame, similar to how you can assign a tangent line to a point on a curve. The size of this local inertial frame is basically the largest region of spacetime that can be reasonably approximated by this inertial frame. To refer back to the curve example: for the curve we would say the largest interval that can be reasonably approximated by a straight line. The larger the curvature at that point, the smaller this region will be.


text:
Q: GUI freezes with long running task in a SwingWorker Thread I have a long running task winch executes when the user  clicks a button in a GUI application:
simplfyButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {

                simplfyAllText();
            }//mouse evebt
        });

The simplfyAlltext() method performs some GUI calls then a long running task, so I have placed this is SwingWorker:
private void simplfyAllText() {

        /*
         * User has imported a text document for simplfying Depending on the size of the
         * document this could be time consuming So we will perform this on a
         * SwingWorker thread
         */

        // If user selects 'Simplfy' before any import is done
        if (!clearTextArea) {
            message_textArea.setText("");
            clearTextArea = true;
            displayMessage("You must import your text doucument to simplfy.", "Notice!");
            return;
        } else if (message_textArea.getText().length() <= 20) {
            displayMessage("You must import your text doucument to simplfy.", "Notice!");
            return;
        }

        // Set up stuff outside the worker thread
        exchangedText.setText("");
        progressBar.setIndeterminate(false);
        progressBar.setStringPainted(true);
        progressBar.setVisible(true);
        message_textArea.setEditable(false);

        // Create our worker to all heavy tasks off the event dispatch thread
        SwingWorker<String, Integer> sw = new SwingWorker<String, Integer>() {

            String simplifiedText = "";

            @Override
            protected String doInBackground() throws Exception {
                // Simplfy the text form message TA
                int size = message_textArea.getText().length();

                for (int i = 0; i < size; i++) {
                    publish(i);
                }
                simplifiedText = textSimplfier.simplyFullText(message_textArea.getText());
                return "finished";

            }

            @Override
            protected void process(List<Integer> chunks) {
                // define what the event dispatch thread
                // will do with the intermediate results received
                // while the thread is executing

                for (int val : chunks) {
                    progressBar.setValue(val);
                    countButton.setText(Integer.toString(val));
                    System.out.println("PROCESS : " + val);
                }

            }

            @Override
            protected void done() {
                // this method is called when the background
                // thread finishes execution
                outPut_TextArea.setText(simplifiedText);
                String exchanged = textSimplfier.getSwappedWords().toString();
                exchangedText.setText(exchanged);
                // remove 1/3 for : between words
                String wordsWithoutHTML = "";
                try {
                    wordsWithoutHTML = exchangedText.getDocument().getText(0, exchangedText.getDocument().getLength());
                } catch (BadLocationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                int noExchanged = ((wordsWithoutHTML.length() / 3) * 2);
                int noOfWords = message_textArea.getText().length();
                keyWord_TextField.setText(
                        "Complete!. " + noExchanged + "/" + noOfWords + " simplfied. Click /'Clear/' to continue.");

            }
        };

        sw.run();
    }

Even though the long running background task is run on a SwingWorker thread the GUI still frezzes during its execution, and the progress from the SwingWorker.process method does not appar to update the ProgressBar.
Any input appreciated.

A: sw.run();

You should be using:
sw.execute();

To start execution on another Thread.
Read the section from the Swing tutorial on Concurrency for more information and working examples.


text:
Q: How to find a value in a list of python dictionaries? Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists?
label = [{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
          'name': 'Test',
          'pos': 6},
             {'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
              'name': 'Name 2',
          'pos': 1}]

The following did not work:
if 'Test'  in label[name]

'Test' in label.values()

A: You'd have to search through all dictionaries in your list; use any() with a generator expression:
any(d['name'] == 'Test' for d in label)

This will short circuit; return True when the first match is found, or return False if none of the dictionaries match.

A: You might also be after:
>>> match = next((l for l in label if l['name'] == 'Test'), None)
>>> print match
{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
 'name': 'Test',
 'pos': 6}

Or possibly more clearly:
match = None
for l in label:
    if l['name'] == 'Test':
        match = l
        break


text:
Q: Find age(from array(3,5,10)) from min age and max age column in sequelize I am sending array of ages [5,10,52]. I want to search age from two columns :

*

*min_age

*max_age
Suppose i have 3 records in database(MySQL) :

*

*min_age = 4

*max_age = 6

*

*min_age = 7

*max_age = 11
I sent [5,10,52] and it should give me 2 records. (5 and 10).
How can i get these records in sequelize. I tried with OR and its not working properly.
Thanks in Advance

A: I solved it like this.
var condition = {};
var arrNew = []
if (body.ages && body.ages.length) {
    body.ages.forEach(function(age){
        arrNew.push({
            [Op.and]: [{
                'minimum_age': {
                    [Op.lte] :  parseInt(age)
                }
            }, {
                'maximum_age': {
                    [Op.gte] :  parseInt(age)
                }
            }]
        })
    })
    condition[Op.or] = arrNew
}


text:
Q: Load and Performance testing on android and ios app I need to perform a load test with 200+ concurrent devices on the android and ios apps. Is there any tool that can do that?

A: It depends on the network protocol(s) which your application is using for communicating with the backend.
You can identify which protocol(s) are in scope by installing the application into Android Emulator or iOS Simulator and use a sniffer tool like Wireshark to capture the network traffic.
Once you figure out which protocol(s) are being used you can choose a proper load testing tool which supports this(ese) protocol(s), an example comparison of free and open source load testing tools can be found i.e. in Open Source Load Testing Tools: Which One Should You Use? article
After you decide which tool you will be using you will need to replicate mobile device traffic using the tool of your choice to 100% match the network footprint of the mobile device (you might need to perform parameterization of credentials and correlation of dynamic parameters) and as soon as it will be done you should be able to replay the requests with increased number of virtual users.

A: Try AWS Device Farm they have a lot of configurations, devices and global options for testing.

A: Typically

*

*you capture the device network requests using a proxy (we use charles proxy) as you are functional testing the app

*Take out static resources, css, images, scripts (which are served from a cdn) and third party resources

*then parameterise the dynamic requests to create a load test script

While you are perf testing, monitor navigate through the app to see the end-user impact when the back-end is under heavy load.

A: Yes, there are many solutions.  The governing factor is going to be the communications model between your handheld device and the application/system under test.
In most cases (but not all) the protocol for communication is HTTP.  In this case you may leverage a proxy for recording the conversation between client and server to reproduce the conversation of a single session. You may then modify this session to address dynamic server data for session, date, time, account information and user inputs.  Once that is done then you may replay 200++ session representing the load of 200++ users on your system.
I would recommend a network simulator be involved in your test.  Mobile networks are particularly dirty, leading to higher error rates and longer latch times (protocol, layer 3) on sites.  Having the impairment from the network simulator will better allow you to understand the response times for your client.  Look for impairment solutions which can ingest OOKLA data for various locations and times of day matching your high load windows.


text:
Q: Parahoric subgroup over a local field $\DeclareMathOperator\SL{SL}$Let $F$ be a local field and $\mathcal{O}_{F}$ its valuation ring. Let $\pi\in \mathcal{O}_{F}$ be a uniformizer and $\mathfrak{p}=\pi\mathcal{O}_{F}$. Let $G$ be a split semisimple algebraic group over $F$. I think the case $G=\SL_{3}$ as an example. Let us consider a generator system $S=\{s_{1},s_{2},w_{1}\}$ of the affine Weyl group of $\SL_{3}(F)$, where
$$
s_{1}=
\left(
\begin{array}{ccc}
0 & 1 & 0 \\
-1 & 0 & 0 \\
0 & 0 & 1
\end{array}
\right),\quad
s_{2}=
\left(
\begin{array}{ccc}
1 & 0 & 0 \\
0 & 0 & 1 \\
0 & -1 & 0
\end{array}
\right),\quad
w_{1}=
\left(
\begin{array}{ccc}
0 & 0 & -\pi^{-1} \\
0 & 1 & 0 \\
\pi & 0 & 0
\end{array}
\right).
$$
It is well-known that holds the affine Bruhat decomposition $\SL_{3}(F)=B\langle S\rangle B$ and $\SL_{3}(\mathcal{O}_{F})=B\langle s_{1},s_{2}\rangle B$ where $B$ is the standard Iwahori subgroup of $\SL_{3}(F)$.
Question: What is the remaining component $B\langle w_{1}\rangle B=B\cup Bw_{1}B$? I want to know the explicit form of this subgroup.

A: $\DeclareMathOperator\SL{SL}\newcommand\O{\mathcal O_F}\newcommand\P{\pi\mathcal O_F}\newcommand\Pi{\pi^{-1}\mathcal O_F}$I assume that the standard Iwahori is the group of matrices in $\SL_3(\O)$ that are upper triangular modulo $\pi$.  Then $B \cup Bw_1 B$ is
$K \mathrel{:=} \begin{pmatrix} \O & \O & \Pi \\ \P & \O & \O \\ \P & \P & \O \end{pmatrix} \cap \SL_3(F)$.
Indeed, it is clear that this is a subgroup, that it contains (hence is stable under left- and right-multiplication by) $B$, and that it contains $w_1$.  Therefore, it contains $B \cup Bw_1 B$.
On the other hand, suppose $\gamma = \begin{pmatrix} a & b & \pi^{-1} c \\ \pi d & e & f \\ \pi g & \pi h & i \end{pmatrix}$ belongs to $K$ (so that $a, \dotsc, i$ belong to $\O$).  If $c$ belongs to $\P$, then $\gamma$ belongs to $B$.  Otherwise, $b \mathrel{:=} \begin{pmatrix} 1 \\ & 1 \\ \pi i/c && 1 \end{pmatrix}$ and $(b w_1)^{-1}\gamma$ both belong to $B$, so $\gamma$ belongs to $B w_1 B$.


text:
Q: Some inputs not submitted I have an HTML form but some of the inputs in it are not submitted, even though they are active. Live example at http://jsfiddle.net/hbw3/qzcTS/2/.
The form clearly contains a number of divs but only the inputs in one div are submitted. Why is this?
The HTML source:
<form accept-charset="UTF-8" action="whatever" id="map_form" method="post">

                <select id=1 name=col_1 class="column_select">
                    <option value="0">None</option>
                    <option value="1">id (integer)</option>
                    <option value="2">name (string)</option>
                </select>

                <select id=2 name=col_2 class="column_select">
                    <option value="0">None</option>
                    <option value="1">id (integer)</option>
                    <option value="2">name (string)</option>
                </select>

        id (integer)
        <input type='text' id='id' />
        name (string)
        <input type='text' id='name' />

    <input name="commit" type="submit" value="Upload Table" />
</form>

The JS to display the submitted inputs:
$('form#map_form').submit(function () {
    $('div#result').text($(this).serialize());
    return false;
})

A: You're missing name attributes on the inputs in your last div.  I tried adding some to your sample and that seems to have fixed it.


text:
Q: sampling from normal distribution using MCMC doesn't seem correct I'm trying to sample from the normal distribution with a mean of .5 (like flipping a coin) and an arbitrary standard deviation using a markov chain (sequence of numbers where each number is dependent on the previous number of the sequence).
since this is a normal distribution under a markov chain, I expect the sampled values to fluctuate between 0 and 1 but mostly around .5 (like a random walk). I expect a result similar to this:

but when I try to do it my result looks like this:

I don't know why in that example the MCMC iteration never gets negative thetas or thetas greater than 1. all my plots are never contained between 0 and 1. if Normal(proposed_theta) outputs a value greater than 1 or is negative that is very problematic.

A: What's missing in what you are doing is an acceptance step that accepts a proposal based on the normal density $f(x_i)$ at the current state of the chain $x_i$ and that at the proposed value $x_{i+1}'$. This could be based on using an acceptance probability $\min(1, f(x_{i+1}')/f(x_{i}))$ (move to the proposal that probability,  make the previous value the next one otherwise), if you want to use Metropolis Hastings.


text:
Q: Return for a push segue I am new to story boards and I am trying to move between table view controllers.
I understand how to set up a segue and how to send data to the new story board but my question is returning data back.  If I use the push style segue it gives me an automatic back button.  I want a page that will create a "job" and save it if they hit save (a bar button I created on the other side of the title) When I set up the segue to go back to the main page from the save button it made that main table view controller a child (instead of simply going back to it's original state).  The work around I was thinking was saving it to a file when they hit save and whenever they load the main table view it loads from that file.  Is this a common and correct way to do this or should I be trying to return that object and save it in the main table view controller?

A: If you're making a segue to go "back" to a controller, then that segue needs to be an unwind segue. An unwind segue goes back to the same instance of the controller that you came from originally. If you need to send data back to that controller, you can do it in prepareForSegue.

A: A common approach is to use delegation. Since ViewControllers should be as independent as it is possible, we have to minimize dependencies between them. And actually your idea with the file, if I understand it correctly, does it as well. But using files to organize a communication between ViewControllers is not very convinient.
Usually you declare a @protocol SecondViewControllerDelegate for your second ViewController (where you click a "Save" button). With methods like:
@protocol YourSecondViewControllerDelegate <NSObject>
-(void)yourSecondViewControllerDidCancel:(YourSecondViewController*)controller; //if you have a cancel button
-(void)yourSecondViewControllerDidFinish:(YourSecondViewController*)controller yourDataToReturn:(SomeData*)data andSomeMoreData:(AnotherDataType*)data2;
@end

Then you add a property like this to your SecondViewController:
@property (nonatomic, assign) id<YourSecondViewControllerDelegate> delegate; //Do not retain it!

Then you adopt your protocol in your MainViewController.
@interface MainViewController()<YourSecondViewControllerDelegate> //you can do it in the private category to keep the class interface clear.
@end
@implementation
//don't forget to implement those methods here :)
@end

And when you trigger your segue from the MainViewController, you can set your MainViewController as a delegate for the SecondViewController:
SecondViewController *destinationController = [[SecondViewController alloc] init]; //Just for example.
destinationController.delegate = self;
//trigger a segue :)

When the user presses the Save button in the SecondViewController, you call the delegate's yourSecondViewControllerDidFinish:
[self.delegate yourSecondViewControllerDidFinish: self yourDataToReturn: someData andSomeMoreDate: someMoreData];

This way MainController's yourSecondViewControllerDidFinish method will be called. And you can pick someData and someMoreData up there.
You can get more details about it in this tutorial:
Apple's your second iOS app tutorial


text:
Q: linux eclipse: run a shell command as the pre-build command How can I have the pre-build step in eclipse/CDT (Linux) run a simple shell command, echo specifically.  I think eclipse has a screwed up value for PKG_CONFIG_PATH and want to see what Linux thinks the value is.

A: Under the covers, Eclipse uses "make".  You can simly edit the project's makefile:

*

*help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/concepts/cdt_c_makefile.htm

You can also create an:

"External Tool", which is up there beside the Debug and Run buttons in
  the toolbar. Then I tell the external tool to run the shell with the
  configure script and any of it's arguments as arguments to the tool.
http://www.eclipse.org/forums/index.php/t/61866/


text:
Q: Azure Data Factory Copy Activity I have been working on this for a couple days and cannot get past this error.  I have 2 activities in this pipeline. The first activity copies data from an ODBC connection to an Azure database, which is successful. The 2nd activity transfers the data from Azure table to another Azure table and keeps failing.
The error message is:
Copy activity met invalid parameters: 'UnknownParameterName', Detailed message: An item with the same key has already been added..
I do not see any invalid parameters or unknown parameter names. I have rewritten this multiple times using their add activity code template and by myself, but do not receive any errors when deploying on when it is running. Below is the JSON pipeline code.
Only the 2nd activity is receiving an error.
Thanks.
Source Data set
{
"name": "AnalyticsDB-SHIPUPS_06shp-01src_AZ-915PM",
"properties": {
    "structure": [
        {
            "name": "UPSD_BOL",
            "type": "String"
        },
        {
            "name": "UPSD_ORDN",
            "type": "String"
        }
    ],
    "published": false,
    "type": "AzureSqlTable",
    "linkedServiceName": "Source-SQLAzure",
    "typeProperties": {},
    "availability": {
        "frequency": "Day",
        "interval": 1,
        "offset": "04:15:00"
    },
    "external": true,
    "policy": {}
}

}
Destination Data set
{
"name": "AnalyticsDB-SHIPUPS_06shp-02dst_AZ-915PM",
"properties": {
    "structure": [
        {
            "name": "SHIP_SYS_TRACK_NUM",
            "type": "String"
        },
        {
            "name": "SHIP_TRACK_NUM",
            "type": "String"
        }
    ],
    "published": false,
    "type": "AzureSqlTable",
    "linkedServiceName": "Destination-Azure-AnalyticsDB",
    "typeProperties": {
        "tableName": "[olcm].[SHIP_Tracking]"
    },
    "availability": {
        "frequency": "Day",
        "interval": 1,
        "offset": "04:15:00"
    },
    "external": false,
    "policy": {}
}

}
Pipeline
{
"name": "SHIPUPS_FC_COPY-915PM",
"properties": {
    "description": "copy shipments ",
    "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "RelationalSource",
                    "query": "$$Text.Format('SELECT COMPANY, UPSD_ORDN, UPSD_BOL FROM \"orupsd - UPS interface Dtl\" WHERE COMPANY = \\'01\\'', WindowStart, WindowEnd)"
                },
                "sink": {
                    "type": "SqlSink",
                    "sqlWriterCleanupScript": "$$Text.Format('delete imp_fc.SHIP_UPS_IntDtl_Tracking', WindowStart, WindowEnd)",
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                },
                "translator": {
                    "type": "TabularTranslator",
                    "columnMappings": "COMPANY:COMPANY, UPSD_ORDN:UPSD_ORDN, UPSD_BOL:UPSD_BOL"
                }
            },
            "inputs": [
                {
                    "name": "AnalyticsDB-SHIPUPS_03shp-01src_FC-915PM"
                }
            ],
            "outputs": [
                {
                    "name": "AnalyticsDB-SHIPUPS_03shp-02dst_AZ-915PM"
                }
            ],
            "policy": {
                "timeout": "1.00:00:00",
                "concurrency": 1,
                "executionPriorityOrder": "NewestFirst",
                "style": "StartOfInterval",
                "retry": 3,
                "longRetry": 0,
                "longRetryInterval": "00:00:00"
            },
            "scheduler": {
                "frequency": "Day",
                "interval": 1,
                "offset": "04:15:00"
            },
            "name": "915PM-SHIPUPS-fc-copy->[imp_fc]_[SHIP_UPS_IntDtl_Tracking]"
        },
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "SqlSource",
                    "sqlReaderQuery": "$$Text.Format('select distinct ups.UPSD_BOL, ups.UPSD_BOL from imp_fc.SHIP_UPS_IntDtl_Tracking ups LEFT JOIN olcm.SHIP_Tracking st ON ups.UPSD_BOL = st.SHIP_SYS_TRACK_NUM WHERE st.SHIP_SYS_TRACK_NUM IS NULL', WindowStart, WindowEnd)"
                },
                "sink": {
                    "type": "SqlSink",
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                },
                "translator": {
                    "type": "TabularTranslator",
                    "columnMappings": "UPSD_BOL:SHIP_SYS_TRACK_NUM, UPSD_BOL:SHIP_TRACK_NUM"
                }
            },
            "inputs": [
                {
                    "name": "AnalyticsDB-SHIPUPS_06shp-01src_AZ-915PM"
                }
            ],
            "outputs": [
                {
                    "name": "AnalyticsDB-SHIPUPS_06shp-02dst_AZ-915PM"
                }
            ],
            "policy": {
                "timeout": "1.00:00:00",
                "concurrency": 1,
                "executionPriorityOrder": "NewestFirst",
                "style": "StartOfInterval",
                "retry": 3,
                "longRetryInterval": "00:00:00"
            },
            "scheduler": {
                "frequency": "Day",
                "interval": 1,
                "offset": "04:15:00"
            },
            "name": "915PM-SHIPUPS-AZ-update->[olcm]_[SHIP_Tracking]"
        }
    ],
    "start": "2017-08-22T03:00:00Z",
    "end": "2099-12-31T08:00:00Z",
    "isPaused": false,
    "hubName": "adf-tm-prod-01_hub",
    "pipelineMode": "Scheduled"
}

}

A: Have you seen this link?
They get the same error message and suggest using AzureTableSink instead of SqlSink
"sink": {
                    "type": "AzureTableSink",
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                }

It would make sense for you too since your 2nd copy activity is Azure to Azure

A: It could be a red herring but I'm pretty sure "tableName" is a require entry in the typeProperties for a sqlSource. Yours is missing this for the input dataset. Appreciate you have a join in the sqlReaderQuery so probably best to put a dummy (but real) table name in there.
Btw, not clear why you are using $$Text.Format and WindowStart/WindowEnd on your queries if you're not transposing these values into the query; you could just put the query between double quotes.


text:
Q: React Router v4 :param conflicting with 404 I'm currently trying to wrap my head around react router. At the moment I'm trying to accomplish a router that looks something like this:
<BrowserRouter>

        <Switch>
            <Route exact path="/" component={App} />
            <Route exact path="/:pageName" component={Page} />
            <Route component={NotFound}/>
        </Switch>

</BrowserRouter>

The idea is that the Page component will use the :pageName to render the correct title and content. However, if the pageName doesn't exist, it should render the notFound (404) page.
At the moment the 404 page will never render, as all urls matches the Page route.
What is the conventional way to check if the pageName exist, and only match the Page component in cases where it does? should I set up the 's dynamically, or should the Page component check and redirect? How should I think about this?

A: If you would like that parameter pageName lies within certain set of predefined values, I would just list each of those values as separate route:
<BrowserRouter>

        <Switch>
            <Route exact path="/" component={App} />
            <Route exact path="/page1" component={Page} />
            <Route exact path="/page2" component={Page} />
            <Route exact path="/pagexyz" component={Page} />
            <Route path="*" component={NotFound}/>
        </Switch>

</BrowserRouter>

If you insist to have just one route for all pages, according to this article you can use regexp to specify path so ou can write regexp that will accept only page names you will have and reject others.
If set of existing pages is not predefined but contained in array I would use map to generate routes like in:
pageNames.map((name) => (<Route exact path={'/'+name} component={Page} />


text:
Q: Error: Validation of SOAP-Encoded messages not supported I'm attempting to connect to a vendor's webservice (Soap 1.1), but I get this error:
line -1: Validation of SOAP-Encoded messages not supported
The vendor's support person with whom I'm communicating is using the same tool (SoapUI v4, I've tried both v4 and v5, and we've confirmed we're using identical XML), but he has no trouble, and a Google search of the error message hasn't uncovered anything helpful. Does anyone have any thoughts what the problem could be? Perhaps a program setting?
<soapenv:Envelope
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:web="http://webservice.uesas._321forms">
   <soapenv:Header/>
   <soapenv:Body>
      <web:GetKey soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <Username xsi:type="xsd:string">[Username]</Username>
         <Password xsi:type="xsd:string">[Password]</Password>
      </web:GetKey>
   </soapenv:Body>
</soapenv:Envelope>

A: Your settings are more strict than you expect/need:

*

*Just open "File > Preferences",

*then "Editor Settings",

*and uncheck the "Abort on invalid requests".

(as by my SoapUI v5.3)
So you will not get the message "Cancelled request due to invalid content." any more.
Also see this defect in SoapUI: Cancelled request due to invalid content from year 2011.


text:
Q: Unable to run protractor using jenkins I am able to run the protractor using command prompt.
However, when I try to run protractor using jenkins, it started the selenium server but does not execute the browser and will fail due to timeout.
Is there any configuration that I need to do at jenkins side aside from the project path?
I also have tried to install the package manually to makesure its updated.
Below is the error when I try to build/run protractor using jenkins:
> webhis_jasmine@ protractor C:\Users\user1\.jenkins\HISWEBJASMINE
> protractor conf.js

[12:06:44] I/launcher - Running 1 instances of WebDriver
[12:06:44] I/local - Starting selenium standalone server...
[12:06:46] I/local - Selenium standalone server started at http://10.190.40.39:56419/wd/hub
Started
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m

i tried to run webdriver-manager update only using jenkins just to check and it is giving below error:
C:\Users\user1\.jenkins\HISWEBJASMINE>webdriver-manager update
'webdriver-manager' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\user1\.jenkins\HISWEBJASMINE>exit 9009

Here is config file:
// conf.js
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
exports.config = {

  capabilities: {
      'browserName': 'chrome'
  },
  specs: ['Patient_positive.js','Visit_positive.js'],
  suites:{
        Smoke: ['ChainLocators.js', 'Dropdown.js'],
            Regression: 'ElementBasics.js',
            Testbed: 'testbed.js',
            PatientPositive: 'Patient_positive.js',
            PatientNegative: 'Patient_negative.js',
            VisitPositive: 'Visit_positive.js',
            VisitNegative: 'Visit_negative.js',
            EpisodeCPOEPositive: 'EpisodeCPOE_positive.js'
    },
  onPrepare:function(){
      browser.driver.manage().window().maximize();
      jasmine.getEnv().addReporter(
                new Jasmine2HtmlReporter({
                  savePath: './test/reports/',
                  screenshotsFolder: 'images',
                  takeScreenshots: true,
                  fixedScreenshotName: true,
                  takeScreenshotsOnlyOnFailures: false,
                  cleanDestination: false,
                  showPassed: true,
                  fileName: 'Test_Report',
                  fileNameSuffix: '',
                  fileNameDateSuffix: true
                })
              );
             },

        jasmineNodeOpts:{
            showColors: true
        }
};

Is it related?
Update: I strip the spec to have to only 1 'it' and run. Manage to get a success result and report is generated, but i see the browser not launched as when running using cmd prompt.
C:\Users\hafizan.abdmulok\.jenkins\HISWEBJASMINE>npm run protractor

> webhis_jasmine@ protractor C:\Users\hafizan.abdmulok\.jenkins\HISWEBJASMINE
> protractor conf.js

[15:14:40] I/launcher - Running 1 instances of WebDriver
[15:14:40] I/local - Starting selenium standalone server...
[15:14:43] I/local - Selenium standalone server started at http://10.190.40.39:52793/wd/hub
Started
Successfully open patient page
Successfully enter name
Successfully select title
Successfully select gender
Successfully enter date of birth
Successfully select ID type
Successfully enter idno= 850921141112
Successfully select Nationality= Malaysia
Successfully enter mobile no
Successfully enter patient address line 1
Successfully enter patient address line 2
Successfully enter patient address line 3
Successfully enter patient postcode= 57000
Successfully enter patient city= Bukit Jalil
Successfully select patient State= Kuala Lumpur
Successfully select patient State= Malaysia
[32m.[0m

1 spec, 0 failures
Finished in 63.169 seconds

CGM
[15:15:52] I/local - Shutting down selenium standalone server.
[15:15:52] I/launcher - 0 instance(s) of WebDriver still running
[15:15:52] I/launcher - chrome #01 passed
Finished: SUCCESS

A: Try using directConnect:true in your config file instead of seleniumAddress: 'http://localhost:4444/wd/hub',
before runing the test do the below activities
webdriver-manager clean

node node_modules/protractor/bin/webdriver-manager update --standalone --versions.standalone=3.8.0

Hope it helps you


text:
Q: WCF vs WEb api vs Web services for new ecommerce website I am creating a new ecommerce application in MVC and sql server as database.I want to use Entity framework for the same. I am confused in selection of my data access layer. Which one should I use among WCF vs Web api vs Web services. It may be possible that in future we may required android and IOS app. I think Web api will be the best option for this.
I try to find the difference between web api and WCF, what did i found is that.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
There are thousand of links telling about Rest, TCP, FTP, soap, Http.
But no where I found my answer. I am still confused Which one will fulfill my problem.
One more thing if I choose Web api, can entity framework integrate with Web api. I am new to dot net. any help will be very helpful.
Edit: @win thanks for your help. I want to know, How to decide which one should i choose, RESTFull(Web api) or WCF(Soap). Which factors in application decide, which one to use.

A: WCF provides a lot of functionality, but at the cost of crazy-mad configuration setup.  Crazy mad.  It involves defining an "ABC", Address, Binding, Contract.  I always tell people "with WCF: its the configuration, not the code".  There are just ~so many options for configuring it.
If you need to push/pull small amounts of data to "clients" (browser, android, iphone), then WebApi is the best bet.
One feature, WebApi will give you xml OR json via how the request is setup (in the 'header').
With WCF, you have to "code up" either/or/both for json and xml and it isn't super trivial.  Aka, you have to put attributes on the Service-Methods (the "Contract" of the ABC) to say "this method will send back xml" or "this method will send back json".
Your WebApi layer will provide services.  This usually means providing json data or consuming json data. And MS has taken care of the "plumbing" for you, so on the services side, this happens auto-magically.
I've coded both since 2005 (well, WCF in 2005 and following, and then later with WebApi).
WebApi is much easier to deal with, especially for a beginner.
So unless you have a very concrete reason to use WCF, I would use WebApi.
As far as an ORM, that happens completely on the "server side", so you can pick whichever one you want.
I would pick Poco/Code-First/Entity-Framework OR NHibernate (for "full" ORM's) or Dapper (for a micro ORM).  Which ORM to use is a full discussion in itself.  But quick advice, don't choose one willy-nilly, do a little research.  Search things like "Entity-Framework vs NHiberate" or "Entity-Framework vs ADO.NET" or "Dapper vs NHiberate" (you get the drill, any combination, and sometimes you'll find a comparison that does all three plus others.
Here is a little explanation of the auto-magic wire up...where you are not hand-parsing json on the SERVER side.
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
and here
http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
Outside of my opinions here, here is a Microsoft comparison article :
https://msdn.microsoft.com/en-us/library/jj823172.aspx
and the quote:
Use WCF to create reliable, secure web services that accessible over a variety of transports. Use ASP.NET Web API to create HTTP-based services that are accessible from a wide variety of clients. Use ASP.NET Web API if you are creating and designing new REST-style services. Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API. If you have an existing WCF service and you want to expose additional REST endpoints, use WCF and the WebHttpBinding.


text:
Q: How to access the directories outside the subdomain folder How do I access a folder outside my subdomain folder.
For example, my domain is localhost and I have a subdomain m.localhost. And their folders are:
Server Root:
    /cdn/
    /contents/
    /mobile/
    .htaccess

And the folder /mobile/ is the root directory of my m.localhost. From the m.localhost, how do I access the /contents/ directory and it's contents using PHP?
$_SERVER['DOCUMENT_ROOT'] only selects the subdomain directory root.

A: Try this.
realpath(dirname(__FILE__).'/../../../contents/nav/quicklinks.txt');


text:
Q: removing packages I need to remove the debian files of these packages from /var/cache/apt/archives/:
 attr cabextract fonts-horai-umefont fonts-unfonts-core fonts-wqy-microhei gcc-4.8-base gcc-4.9-base libasn1-8-heimdal libasound2  libasound2-plugins libasyncns0 libavahi-client3 libavahi-common-data libavahi-common3 libc6 libcapi20-3 libcapi20-3  libcgmanager0 libcomerr2 libcups2 libdb5.3 libdbus-1-3 libdrm-intel1 libdrm-nouveau2 libdrm-radeon1 libdrm2 libelf1  libexif12 libexpat1 libffi6 libflac8 libfontconfig1 libfreetype6 libgcc1 libgcrypt11 libgd3 libgif4  libgl1-mesa-dri libgl1-mesa-glx libglapi-mesa libglib2.0-0 libglu1-mesa libgnutls26 libgpg-error0 libgphoto2-6  libgphoto2-port10 libgpm2 libgssapi-krb5-2 libgssapi3-heimdal libgstreamer-plugins-base0.10-0 libgstreamer0.10-0 libhcrypto4-heimdal  libhdb9-heimdal libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal libice6 libieee1284-3 libjack-jackd2-0 libjbig0  libjpeg-turbo8 libjpeg8 libjson-c2 libk5crypto3 libkdc2-heimdal libkeyutils1 libkrb5-26-heimdal libkrb5-3 libkrb5support0  liblcms2-2 libldap-2.4-2 libllvm3.4 libltdl7 liblzma5 libmpg123-0 libmpg123-0 libncurses5 libnih-dbus1 libnih1 libodbc1  libogg0 libopenal1 liborc-0.4-0 libosmesa6 libosmesa6 libp11-kit-gnome-keyring libp11-kit0 libpciaccess0 libpcre3  libpng12-0 libpulse0 libroken18-heimdal libsamplerate0 libsane libsasl2-2 libsasl2-modules libsasl2-modules-db libselinux1  libsm6 libsndfile1 libspeexdsp1 libsqlite3-0 libssl1.0.0 libstdc++6 libtasn1-6 libtiff5 libtinfo5 libtxc-dxtn-s2tc0  libudev1 libusb-1.0-0 libuuid1 libv4l-0 libv4lconvert0 libvorbis0a libvorbisenc2 libvpx1 libwind0-heimdal libwrap0  libx11-6 libx11-xcb1 libxau6 libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0 libxcb-present0 libxcb-sync1 libxcb1  libxcomposite1 libxcursor1 libxdamage1 libxdmcp6 libxext6 libxfixes3 libxi6 libxinerama1 libxml2 libxpm4  libxrandr2 libxrender1 libxshmfence1 libxslt1.1 libxt6 libxxf86vm1 ocl-icd-libopencl1 ocl-icd-libopencl1 p11-kit-modules p7zip  python-dnspython samba samba-dsdb-modules samba-vfs-modules tdb-tools ttf-mscorefonts-installer ttf-wqy-microhei unixodbc winbind wine-gecko2.21 wine-gecko2.21  wine-mono0.0.8 wine1.6 wine1.6-amd64 wine1.6-i386 winetricks zlib1g  glibc-doc locales isdnutils-doc isdnutils-doc rng-tools libgd-tools libglide3 gnutls-bin gphoto2 gtkam gpm  krb5-doc krb5-user libvisual-0.4-plugins gstreamer-codec-install gnome-codec-install gstreamer0.10-tools gstreamer0.10-plugins-base  jackd2 liblcms2-utils libmyodbc odbc-postgresql tdsodbc unixodbc-bin libportaudio2 libroar-compat2 pulseaudio hplip hpoj   libsane-extras libsasl2-modules-otp libsasl2-modules-ldap libsasl2-modules-sql libsasl2-modules-gssapi-mit libsasl2-modules-gssapi-heimdal opencl-icd opencl-icd bind9 bind9utils ldb-tools ntp smbldap-tools libnss-winbind libpam-winbind dosbox   xml-core unixodbc wine-mono0.0.8 attr cabextract fonts-horai-umefont fonts-unfonts-core fonts-wqy-microhei gcc-4.8-base gcc-4.9-base libasn1-8-heimdal libasound2  libasound2-plugins libasyncns0 libavahi-client3 libavahi-common-data libavahi-common3 libc6 libcapi20-3 libcapi20-3   libcgmanager0 libcomerr2 libcups2 libdb5.3 libdbus-1-3 libdrm-intel1 libdrm-nouveau2 libdrm-radeon1 libdrm2 libelf1  libexif12 libexpat1 libffi6 libflac8 libfontconfig1 libfreetype6 libgcc1 libgcrypt11 libgd3 libgif4   libgl1-mesa-dri libgl1-mesa-glx libglapi-mesa libglib2.0-0 libglu1-mesa libgnutls26 libgpg-error0 libgphoto2-6  libgphoto2-port10 libgpm2 libgssapi-krb5-2 libgssapi3-heimdal libgstreamer-plugins-base0.10-0 libgstreamer0.10-0 libhcrypto4-heimdal   libhdb9-heimdal libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal libice6 libieee1284-3 libjack-jackd2-0 libjbig0  libjpeg-turbo8 libjpeg8 libjson-c2 libk5crypto3 libkdc2-heimdal libkeyutils1 libkrb5-26-heimdal libkrb5-3 libkrb5support0  liblcms2-2 libldap-2.4-2 libllvm3.4 libltdl7 liblzma5 libmpg123-0 libmpg123-0 libncurses5 libnih-dbus1 libnih1 libodbc1  libogg0 libopenal1 liborc-0.4-0 libosmesa6 libosmesa6 libp11-kit-gnome-keyring libp11-kit0 libpciaccess0 libpcre3   libpng12-0 libpulse0 libroken18-heimdal libsamplerate0 libsane libsasl2-2 libsasl2-modules libsasl2-modules-db libselinux1    libsm6 libsndfile1 libspeexdsp1 libsqlite3-0 libssl1.0.0 libstdc++6 libtasn1-6 libtiff5 libtinfo5 libtxc-dxtn-s2tc0  libudev1 libusb-1.0-0 libuuid1 libv4l-0 libv4lconvert0 libvorbis0a libvorbisenc2 libvpx1 libwind0-heimdal libwrap0  libx11-6 libx11-xcb1 libxau6 libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0 libxcb-present0 libxcb-sync1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxdmcp6 libxext6 libxfixes3 libxi6 libxinerama1 libxml2 libxpm4  libxrandr2 libxrender1 libxshmfence1 libxslt1.1 libxt6 libxxf86vm1 ocl-icd-libopencl1 ocl-icd-libopencl1 p11-kit-modules p7zip python-dnspython samba samba-dsdb-modules samba-vfs-modules tdb-tools ttf-mscorefonts-installer ttf-wqy-microhei unixodbc winbind wine wine-gecko2.21 wine-gecko2.21 wine-mono0.0.8 wine1.6 wine1.6-amd64 wine1.6-i386 winetricks zlib1g

how can I do this using a command?

A: I don't know of any apt command that will only remove cached files for specific packages, but given that you know which packages have to be removed:
for package in attr cabextract fonts-horai-umefont fonts-unfonts-core fonts-wqy-microhei gcc-4.8-base gcc-4.9-base libasn1-8-heimdal libasound2  libasound2-plugins libasyncns0 libavahi-client3 libavahi-common-data libavahi-common3 libc6 libcapi20-3 libcapi20-3  libcgmanager0 libcomerr2 libcups2 libdb5.3 libdbus-1-3 libdrm-intel1 libdrm-nouveau2 libdrm-radeon1 libdrm2 libelf1  libexif12 libexpat1 libffi6 libflac8 libfontconfig1 libfreetype6 libgcc1 libgcrypt11 libgd3 libgif4  libgl1-mesa-dri libgl1-mesa-glx libglapi-mesa libglib2.0-0 libglu1-mesa libgnutls26 libgpg-error0 libgphoto2-6  libgphoto2-port10 libgpm2 libgssapi-krb5-2 libgssapi3-heimdal libgstreamer-plugins-base0.10-0 libgstreamer0.10-0 libhcrypto4-heimdal  libhdb9-heimdal libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal libice6 libieee1284-3 libjack-jackd2-0 libjbig0  libjpeg-turbo8 libjpeg8 libjson-c2 libk5crypto3 libkdc2-heimdal libkeyutils1 libkrb5-26-heimdal libkrb5-3 libkrb5support0  liblcms2-2 libldap-2.4-2 libllvm3.4 libltdl7 liblzma5 libmpg123-0 libmpg123-0 libncurses5 libnih-dbus1 libnih1 libodbc1  libogg0 libopenal1 liborc-0.4-0 libosmesa6 libosmesa6 libp11-kit-gnome-keyring libp11-kit0 libpciaccess0 libpcre3  libpng12-0 libpulse0 libroken18-heimdal libsamplerate0 libsane libsasl2-2 libsasl2-modules libsasl2-modules-db libselinux1  libsm6 libsndfile1 libspeexdsp1 libsqlite3-0 libssl1.0.0 libstdc++6 libtasn1-6 libtiff5 libtinfo5 libtxc-dxtn-s2tc0  libudev1 libusb-1.0-0 libuuid1 libv4l-0 libv4lconvert0 libvorbis0a libvorbisenc2 libvpx1 libwind0-heimdal libwrap0  libx11-6 libx11-xcb1 libxau6 libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0 libxcb-present0 libxcb-sync1 libxcb1  libxcomposite1 libxcursor1 libxdamage1 libxdmcp6 libxext6 libxfixes3 libxi6 libxinerama1 libxml2 libxpm4  libxrandr2 libxrender1 libxshmfence1 libxslt1.1 libxt6 libxxf86vm1 ocl-icd-libopencl1 ocl-icd-libopencl1 p11-kit-modules p7zip  python-dnspython samba samba-dsdb-modules samba-vfs-modules tdb-tools ttf-mscorefonts-installer ttf-wqy-microhei unixodbc winbind wine-gecko2.21 wine-gecko2.21  wine-mono0.0.8 wine1.6 wine1.6-amd64 wine1.6-i386 winetricks zlib1g  glibc-doc locales isdnutils-doc isdnutils-doc rng-tools libgd-tools libglide3 gnutls-bin gphoto2 gtkam gpm  krb5-doc krb5-user libvisual-0.4-plugins gstreamer-codec-install gnome-codec-install gstreamer0.10-tools gstreamer0.10-plugins-base  jackd2 liblcms2-utils libmyodbc odbc-postgresql tdsodbc unixodbc-bin libportaudio2 libroar-compat2 pulseaudio hplip hpoj   libsane-extras libsasl2-modules-otp libsasl2-modules-ldap libsasl2-modules-sql libsasl2-modules-gssapi-mit libsasl2-modules-gssapi-heimdal opencl-icd opencl-icd bind9 bind9utils ldb-tools ntp smbldap-tools libnss-winbind libpam-winbind dosbox   xml-core unixodbc wine-mono0.0.8 attr cabextract fonts-horai-umefont fonts-unfonts-core fonts-wqy-microhei gcc-4.8-base gcc-4.9-base libasn1-8-heimdal libasound2  libasound2-plugins libasyncns0 libavahi-client3 libavahi-common-data libavahi-common3 libc6 libcapi20-3 libcapi20-3   libcgmanager0 libcomerr2 libcups2 libdb5.3 libdbus-1-3 libdrm-intel1 libdrm-nouveau2 libdrm-radeon1 libdrm2 libelf1  libexif12 libexpat1 libffi6 libflac8 libfontconfig1 libfreetype6 libgcc1 libgcrypt11 libgd3 libgif4   libgl1-mesa-dri libgl1-mesa-glx libglapi-mesa libglib2.0-0 libglu1-mesa libgnutls26 libgpg-error0 libgphoto2-6  libgphoto2-port10 libgpm2 libgssapi-krb5-2 libgssapi3-heimdal libgstreamer-plugins-base0.10-0 libgstreamer0.10-0 libhcrypto4-heimdal   libhdb9-heimdal libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal libice6 libieee1284-3 libjack-jackd2-0 libjbig0  libjpeg-turbo8 libjpeg8 libjson-c2 libk5crypto3 libkdc2-heimdal libkeyutils1 libkrb5-26-heimdal libkrb5-3 libkrb5support0  liblcms2-2 libldap-2.4-2 libllvm3.4 libltdl7 liblzma5 libmpg123-0 libmpg123-0 libncurses5 libnih-dbus1 libnih1 libodbc1  libogg0 libopenal1 liborc-0.4-0 libosmesa6 libosmesa6 libp11-kit-gnome-keyring libp11-kit0 libpciaccess0 libpcre3   libpng12-0 libpulse0 libroken18-heimdal libsamplerate0 libsane libsasl2-2 libsasl2-modules libsasl2-modules-db libselinux1    libsm6 libsndfile1 libspeexdsp1 libsqlite3-0 libssl1.0.0 libstdc++6 libtasn1-6 libtiff5 libtinfo5 libtxc-dxtn-s2tc0  libudev1 libusb-1.0-0 libuuid1 libv4l-0 libv4lconvert0 libvorbis0a libvorbisenc2 libvpx1 libwind0-heimdal libwrap0  libx11-6 libx11-xcb1 libxau6 libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0 libxcb-present0 libxcb-sync1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxdmcp6 libxext6 libxfixes3 libxi6 libxinerama1 libxml2 libxpm4  libxrandr2 libxrender1 libxshmfence1 libxslt1.1 libxt6 libxxf86vm1 ocl-icd-libopencl1 ocl-icd-libopencl1 p11-kit-modules p7zip python-dnspython samba samba-dsdb-modules samba-vfs-modules tdb-tools ttf-mscorefonts-installer ttf-wqy-microhei unixodbc winbind wine wine-gecko2.21 wine-gecko2.21 wine-mono0.0.8 wine1.6 wine1.6-amd64 wine1.6-i386 winetricks zlib1g
do
    sudo rm /var/cache/apt/archives/$package*.deb -f
done

You can do it without a loop, but this should be enough.


text:
Q: Conversion failed because the DateTime data value overflowed the type specified for the DateTime value part in the consumer's buffer i have a stored procedure in Sybase ASE with date params in it, so when i created a OLE DB Connection and passing the date parameters to the OLE DB Command,And we are mapping to the parameter with OLEDBType.DBTimeStamp type, datetime param type in stored procedure is smalldatetime.
Here is the sample code.
OLEDBConnection  con = new OLEDBConnection(connectionstring);
con.open;

OLEDBCommand cmd = new OLEDBCommand(con);
cmd.QueryString = "dbo.job_xb_new"
cmd.QueryType = "Stored Procedure";

cmd.Parameters.Add("@signoff",OLEType.DBTimeStamp);
cmd.Parameters("@signoff").Value = Datetime.now;

cmd.executeNonQuery(); -----------> ERROR HERE

while executing the store-procedure i am receiving the error.
"Conversion failed because the DateTime data value overflowed the type specified for the DateTime value part in the consumer's buffer" ?
Please help!!!

A: With the only information given there may be a solution to try.

*

*Change the datatype of your input value to the stored proc to a char/varchar

create procedure dbo.myProc
@inDate varchar(20)
AS
BEGIN
..

END

*Perform internal conversion from that with CONVERT before passing to your query.

SET @inDate = CONVERT(datetime,@inDate,[style parameter number])

*For troubleshooting, just comment out everything in the procedure and SELECT @inDate first to determine what the data coming in from the OLE DB app looks like. You may be in for a surprise there...


text:
Q: Javascript modularity I am studying the possibility of building Javascript applications in the Java / OSGi modularity style. I am sure I will not manage to actually reach the kind of flexibility that OSGi provides, but I would need to get to at least the following list:

*

*split javascript code as modules, each module would lay in its own git repository

*ideally, as little as possible dependencies between modules and definitely no circular dependencies between modules

*have 2 or more "main" javascript applications that will use the modules described above

If I will manage to setup the above then I will probably want to be able to organize modules as layers like: core layer with several modules, ui layer, applications layer.
Are there any javascript libraries that help building the above setup? Is something like this possible in javascript?
Note: When I say javascript, I don't actually mean plain javascript. I am going to use a library like ExtJS or jQuery for the UI part at least.

A: Checkout RequireJS an implementation of Asynchronous Module Definition

A: Since this question was answered javascript now has native implementaitons of classes and modules that can give you what you need without having to use a 3rd party library.
js modules alow you to have a module or code and import methods (or everything) from it (a bit like in python and ruby)
// utilities.js
function something () {
 // some great code
}

export function util() {
  something();
}

//import a method
import {util} from "utilities.js";

// or import everything
import "utilities.js";

you can find more on es6 modules here
js classes are syntax suger over prototypal structure in js and can be used the same way as in more trandtional OOP languages
class MyClass {
  constructor() {
    // constructor code
  }

  add() {
    // some method
  }
}

var myObject = new MyClass();

You can find out more about es6 classes here


text:
Q: How can i split my integer inputs into 2 digits and remaining one digit as one? My integer input is suppos 2233445, I want to split and put it into an array as 22, 33, 44, 5.And append them to a list. How will I be able to do it?

A: Simply split the string
data="2233445"
split_strings = [] # final list
n = 2 # length of spliting
for index in range(0, len(data), n):
    split_strings.append(data[index : index + n])
print(split_strings)

A: One way to do it with regex and get result as list,
import re
result = re.findall('..?','2233445')
print(result)

WORKING DEMO: https://rextester.com/PWV44308

A: s = str(2233445)
output = [int(s[i:i+2]) for i in range(0, len(s), 2)]

output
>>> [22, 33, 44, 5]

A: Try this;
number = 2233445
number = str(number)
pairs = [int(number[i: i + 2]) for i in range(0, len(number), 2)]
print(pairs)

[22, 33, 44, 5]


text:
Q: Copy vba code to another xlsm file using Open XML from a template xlsm file I use this code to add VbaPart of the template xlsm file into another.
When I open the vb section duplicate entries get added for each sheet as well as the "ThisWorkBook".
Below is the screen shot of how it looks in the developer tab
And below is the code that I use:
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(convertDocumentFile, true))
{
    VbaProjectPart extendedPart = FindPart(myDoc);

    if (extendedPart != null)
      myDoc.DeletePart(extendedPart);
    if (vbaPart != null)
      myDoc.WorkbookPart.AddPart<VbaProjectPart>(vbaPart);
}

private static VbaProjectPart FindPart(SpreadsheetDocument mainPart)
{
    if (mainPart != null)
    {
        foreach (IdPartPair partPair in mainPart.WorkbookPart.Parts)
        {
            if (partPair.OpenXmlPart.RelationshipType == _wnsRelationShip.NamespaceName)
            {
               return partPair.OpenXmlPart as VbaProjectPart;
            }
        }
    }
    return null;
}

Where the variable "convertDocumentFile" is the file where the vbaProject part needs to be added and the "vbaPart" is the vbaProjectPart from the template.

A: The reason my code did not execute was that the "CodeName" attribute was missing when I converted to xlsm format hence I need to add the following code:
myDoc.WorkbookPart.Workbook.WorkbookProperties.CodeName = "ThisWorkbook";

After pointing to the correct workbook, the vb code executed correctly.


text:
Q: Looping through columns then doing UCase I have some code that loops through columns to find a specific ending in a column (_END). If it finds that, then it will loop through the rows in that column, changing date formatting. This works as intended and I am having no issues with it. However, I need to UCase the rows as well. Right now, it would output a date like "01-Jan-2016". However, I need it to be "01-JAN-2016". I have code below that is giving me trouble.
    lngColHeaders = Cells(5, Columns.Count).End(xlToLeft).Column
For X = 1 To lngColHeaders
If (Right(Cells(5, X), 4)) = "_END" Then
    LastRowDates = Cells(Rows.Count, X).End(xlUp).Row
    For ZZ = 6 To LastRowDates Step 1
        Cells(ZZ, X).NumberFormat = "dd-MMM-YYYY"
        UCase (Cells(ZZ, X))
    Next ZZ
End If
Next X

Like I said, it seems to format them correctly, but UCase (Cells(ZZ,X)) seems to do nothing. Any help is much appreciated.

A: I think you'll need to format the cell as text, and then do your UCase, along with a Format.
Cells(ZZ, X).NumberFormat = "@"
Cells(ZZ, X).Value = UCase(Format(Cells(ZZ, X).Value, "dd-MMM-YYYY"))


text:
Q: How to fix 'ERROR TypeError: data.slice is not a function'? I am trying to display JSON from my backend on my Angular dashboard with angular material mat-table.
I have done this successfully a lot in the past where my JSON response was a string or a list, but I struggle here with a dictionary.
I have tried to follow the advice shown on Question 51304884, with no luck.
I found a solution that works, i.e. putting my dict into a list in the backend, but I would like to understand how to do it with a dict.
The code for my dashboard looks like this:
component.ts
export class RunningContainersComponent {

  containers = new MatTableDataSource<Containers>();
  displayedColumns: string[] = ['serverName', 'containerCount'];

  @ViewChild(MatSort) sort: MatSort;

  constructor(private cadenzaService: CadenzaService) {
  }

  onUploadResponse(response) {
    this.containers.data = response;
  }

  ngOnInit() {
    this.containers.sort = this.sort;
    this.cadenzaService.getRunningContainers().subscribe(response => this.onUploadResponse(response));
  }
}

service.ts
  getRunningContainers(): Observable<Containers[]> {
    const url = backendUrl + `/running-containers`;
    return this.http.get<Containers[]>(url, {
      headers: new HttpHeaders().set(
        'Authorization', `Bearer ${localStorage.getItem('access_token')}`)
    })
      .pipe(
        tap(response => CadenzaService.log(`${response.length} containers received`)),
        catchError(this.handleError('getRunningContainers', []))
      );
  }

component.html

      <ng-container matColumnDef="serverName">
        Engine name
        {{row.serverName}}
      </ng-container>

      <ng-container matColumnDef="containerCount">
        Running containers
        {{row.containerCount}}
      </ng-container>

The error I get
core.js:15724 ERROR TypeError: data.slice is not a function
    at MatTableDataSource.push../node_modules/@angular/material/esm5/table.es5.js.MatTableDataSource._orderData (table.es5.js:706)
    at MapSubscriber.project (table.es5.js:639)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at CombineLatestSubscriber.push../node_modules/rxjs/_esm5/internal/observable/combineLatest.js.CombineLatestSubscriber.notifyNext (combineLatest.js:83)
    at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:15)
    at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at CombineLatestSubscriber.push../node_modules/rxjs/_esm5/internal/observable/combineLatest.js.CombineLatestSubscriber.notifyNext (combineLatest.js:83)

What I would like to see
I have two keys (name of the server and number of Docker containers running on each server) that I would like to display in a table. One column showing the name, the other the number.
Thanks!

A: this is how you do it
let str = 'hi how are you';
let array = [];
array = str.split(' ').map(function (word) {
                   return word
                })


text:
Q: Scalacheck always generates the same UUID for an arbitrary of List[UUID] I'm trying to generate a list of arbitrary UUIDs using scalacheck (version 1.12.2). For some reason, every UUID in the generated list is the same. This is not the case for other types such as List[String] or List[Int]. Here is the code I've written:
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Arbitrary
import java.util.UUID

case class SomeUUIDClass(field: List[UUID])
case class SomeOtherClass(field: List[Int])

object Arb {
    implicit def arbUUID: Arbitrary[UUID] = Arbitrary {
        UUID.randomUUID()
    }

    implicit def arbUUIDClass = Arbitrary {
        for {
            field <- arbitrary[List[UUID]]
        } yield SomeUUIDClass(field)
    }

    implicit def arbOtherClass = Arbitrary {
        for {
            field <- arbitrary[List[Int]]
        } yield SomeOtherClass(field)
    }

    def main(args: Array[String]) {
        println("without uuids:")
        arbitrary[SomeOtherClass].sample.get.field.foreach(println(_))
        println("")

        println("with uuids:")
        arbitrary[SomeUUIDClass].sample.get.field.foreach(println(_))
    }
}

And a sample run:
without uuids:
-1
0
2147483647
-1
-2147483648
527079214
-698179980
1192016877
-1001957700
0
682853458
-1
-2147483648
109314552
1130736291
1080418
1771214863
1164874892
-1306566270
2147483647
-2009106057
2147483647
-2147483648
-1
-1
-1
945958506
777623735
-490377345
-272177229
0
-2147483648
-1753697474
-1
736327057
415072340
0

with uuids:
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6
a49540b4-29ce-464f-946d-3649f38fb8a6

A: Use Gen.wrap() and it should work.
So on the first implicit in your sample code you would change it to:
import org.scalacheck.Gen

implicit def arbUUID: Arbitrary[UUID] = Arbitrary {
  Gen.wrap(UUID.randomUUID)
}

Update: From version 1.13.0, wrap is deprecated, you can use Gen.delay instead:
import org.scalacheck.Gen

implicit def arbUUID: Arbitrary[UUID] = Arbitrary {
  Gen.delay(UUID.randomUUID)
}

A: From Scalacheck version 1.13.0, you can simply use Gen.uuid:
import org.scalacheck.{Arbitrary, Gen}

implicit def arbUUID: Arbitrary[UUID] = Arbitrary {
        Gen.uuid
    }


text:
Q: Getting clipboard data from remote computer Using C#, is there a way to get the clipboard data that is on a remote machine ?
I am remoting into another computer using Remote Desktop, I run an application on it that copies some text onto the clipboard, from my desktop I have a C# winform application that needs to make use of the clipboard data on that remote machine.
Is there a way to do that ?

A: You can use the Clipboard object in C#, Refer: https://msdn.microsoft.com/en-us/library/c2thcsx4(v=vs.110).aspx
//Set data to clipboard
Clipboard.SetData(format, users);
//Get data from clipboard
List<User> result = null;
if (Clipboard.ContainsData(format)){
    result = (List<User>)Clipboard.GetData(format);
}
//Clear clipboard
Clipboard.Clear();


text:
Q: In Ruby / Rails, what if a gem Foo depends on Bar 1.2.2, and cannot be Bar 2.0, but Wala depends on Bar 2.0? In other words, can't the versions have conflicts and is there a way to solve it?
Such as Foo depends on Bar and Foo doesn't support Bar 2.0, but Wala need to have at least Bar 2.0, so can Rubygems or Bundler or any mechanism handle it?

A: It's open-source, check it out with Git and fix Foo, then contribute your fix back to the community!

A: This can be a problem, if each gem really needs that specific version.  But most of the time, you can fix this quickly.  Vendor your gems:
rake rails:freeze:gems

Now go into vendor/gems, and find the *.gemspec files for the gems you're trying to reconcile.  Update the add_dependency line, and set the dependency in both gems to the same version.  Use the more recent version for both.
Chances are good this will fix your problem.  If not, there may be more work involved :)


text:
Q: Python plot of force in Lennard-Jones system gives TypeError I am trying to plot the force on the ith particle as function of its distance from the jth particle (ie. xi-xj) in a Lennard-Jones system. The force is given by

where sigma and epsilon are two parameters, Xi is a known quantity and Xj is variable. The force directs from the ith particle to the jth particle.
The code that I have written for this is given below.
from pylab import*
from numpy import*

#~~~ ARGON VALUES ~~~~~~~~(in natural units)~~~~~~~~~~~~~~~~
epsilon=0.0122      # depth of potential well
sigma=0.335         # dist of closest approach
xi=0.00
xj=linspace(0.1,1.0,300)

f = 48.0*epsilon*( ((sigma**12.0)/((xi-xj)**13.0)) - ((sigma**6.0)/2.0/((xi-xj)**7.0)) ) * float(xj-xi)/abs(xi-xj)

plot(xj,f,label='force')
legend()
show()

But it gives me this following error.
f = 48.0*epsilon*( ((sigma**12.0)/((xi-xj)**11.0)) - ((sigma**6.0)/2.0/((xi-xj)**5.0)) ) * float(xj-xi)/abs(xi-xj)
TypeError: only length-1 arrays can be converted to Python scalars

Can someone help me solve this problem. Thanks in advance.

A: The error is with this part of the expression:
float(xj-xi)

Look at the answer to a related question. It appears to be conflict between Python built-in functions and Numpy functions.
If you take out the 'float' it at least returns. Does it give the correct numbers?
f = 48.0*epsilon*( ((sigma**12.0)/((xi-xj)**11.0)) - ((sigma**6.0)/2.0/((xi-xj)**5.0)) ) * (xj-xi)/abs(xi-xj)

A: Instead of the term float(xj-xi)/abs(xi-xj) you should use
sign(xj-xi)

If you really want to do the division, since xi and xj are already floats you could just do:
(xj-xi)/abs(xi-xj)

More generally, if you need to convert a numpy array of ints to floats you could use either of:
1.0*(xj-xi)
(xj-xi).astype(float)

Even more generally, it's helpful in debugging to not use equations that stretch across the page because with smaller terms you can identify the location of the errors more easily.  It also often runs faster.  For example, here you calculate xi-xj four times, when really it only needs to be done once.  And it would be easier to read:
x = xi -xj

f = 48*epsilon*(s**12/x**13 - s**6/2/x**7)
f *= sign(-x)

A: The TypeError is due to float(xi-xj). float() cannot convert an iterable to a single scalar value. Instead, iterate over xj and convert each value in xi-xj to float. This can be easily done with
x = [float(j - xi) for j in xj)]


text:
Q: Working with big text files I have a file in following format:
[1]
Parameter1=Value1
.
.
.
End
[2]
.
.

The number between brackets presents id of the entity. There're around 4500 entites. I need to parse through all entites and pick the ones matching my parameters and values. Size of file is around 20mb. My first approach was to reading file line by line and storing them in a struct array like:
struct Component{
    std::string parameter;
    std::string value;
};
struct Entity{
    std::string id;
    std::list<Component> components;
};
std::list<Entity> g_entities;

But this approach took enormous amount of memory and was very slow. I've also tried storing only the ones that match my parameters/values. But that also was really slow and took quite some memory. Ideally i would like to store all data in memory so that i won't have to load the file everytime i need to filter my parameters/values if it's possible with reasonable amount of memory usage.
Edit 1:
I read file line by line:
            std::ifstream readTemp(filePath);
            std::stringstream dataStream;
            dataStream << readTemp.rdbuf();
            readTemp.close();

            while (std::getline(dataStream, line)){
                    if (line.find('[') != std::string::npos){
                        // Create Entity
                        Entity entity;

                        // Set entity id
                        entity.id = line.substr(line.find('[') + 1, line.find(']') - 1);

                        // Read all lines until EnumEnd=0
                        while (1){
                            std::getline(dataStream, line);
                            // Break loop if end of entity
                            if (line.find("EnumEnd=0") != std::string::npos){
                                if (CheckMatch(entity))
                                    entities.push_back(entity);
                                entity.components.clear();
                                break;
                            }

                            Component comp;
                            int pos_eq = line.find('=');
                            comp.parameterId = line.substr(0, pos_eq);
                            comp.value = line.substr(pos_eq + 1);

                            entity.components.push_back(comp);
                        }
                    }
                }

A: PS: After your edit. and Comment concerning memory consumption
500MB / 20MB = 25.

If each line is 25 chars long, the memory consumption looks ok.
OK you could use a look-up table for mapping parameter-names to numbers.
If the names-set is small, this will save the consumption up to 2 times.
Your data structure could look like this:
std::map<int, std::map<int, std::string> > my_ini_file_data;
std::map<std::string, int> param_to_idx;

(provided the parameter names within sections (entities as you call it) are not unique)
Putting the data is:
std::string param = "Param";
std::string value = "Val";
int entity_id = 0;
if ( param_to_idx.find(param) == param_to_idx.end() )
  param_to_idx[param] = param_to_idx.size();
my_ini_file_data[entity_id][ param_to_idx[param] ] = value;

getting the data is:
    value = my_ini_file_data[entity_id][ param_to_idx[param] ];

If the values-set is also considerably smaller than the number of entries,
you could even map values to numbers:
std::map<int, std::map<int, int> > my_ini_file_data;
std::map<std::string, int> param_to_idx;
std::map<std::string, int> value_to_idx;
std::map<int, std::string> idx_to_value;

Putting the data is:
std::string param = "Param";
std::string value = "Val";
int entity_id = 0;
if ( param_to_idx.find(param) == param_to_idx.end() )
      param_to_idx[param] = param_to_idx.size();
if ( value_to_idx.find(value) == value_to_idx.end() )
{
      int idx = value_to_idx.size();
      value_to_idx[value] = idx;
      idx_to_value[idx] = value;
}

my_ini_file_data[entity_id][ param_to_idx[param] ] = value_to_idx[value];

getting the data is:
value = idx_to_value[my_ini_file_data[entity_id][ param_to_idx[param] ] ];

Hope, this helps.
Initial answer
Concerning memory, I wouldn't care unless you have a kind of embedded system with very small memory.
Concerning the speed, I could give you some suggestions:
Find out, what is the bottleneck.

*

*Use std::list! Using std::vector you re-initialize the memory each time the vector grows. If for some reason you need a vector at the end, create the vector reserving the requires number of entries, which you'll get by calling list::size()

*Write a while loop, there you only call getline. If this alone is
already slow, read the entire block at once, create a reader-stream
out of the char* block and read line by line from the stream.

*If the speed of the simple reading is OK, optimize your parsing code. You
can reduce the number of find-calls by storing the position. e.g.
int pos_begin = line.find('[]');
if (pos_begin != std::string::npos){
    int pos_end = line.find(']');
    if (pos_end != std::string::npos){
        entity.id = line.substr(pos_begin + 1, pos_begin - 1);

        // Read all lines until EnumEnd=0
        while (1){
            std::getline(readTemp, line);
            // Break loop if end of entity
            if (line.find("EnumEnd=0") != std::string::npos){
                if (CheckMatch(entity))
                    entities.push_back(entity);
                break;
            }

            Component comp;
            int pos_eq = line.find('=');

            comp.parameter= line.substr(0, pos_eq);
            comp.value = line.substr(pos_eq + 1);

            entity.components.push_back(comp);
        }
    }
}

*Depending on how big your entities are, check if CheckMatch is slow. The smaller the entities, the slower the code - in this case.

A: You can use less memory by interning your params and values, so as not to store multiple copies of them.
You could have a map of strings to unique numeric IDs, that you create when loading the file, and then just use the IDs when querying your data structure. At the expense of possibly slower parsing initially, working with these structures afterwards should be faster, as you'd only be matching 32-bit integers rather than comparing strings.
Sketchy proof of concept for storing each string once:
#include <unordered_map>
#include <string>
#include <iostream>

using namespace std;

int string_id(const string& s) {
  static unordered_map<string, int> m;
  static int id = 0;

  auto it = m.find(s);
  if (it == m.end()) {
    m[s] = ++id;
    return id;
  } else {
    return it->second;
  }
}

int main() {
  // prints 1 2 2 1
  cout << string_id("hello") << " ";
  cout << string_id("world") << " ";
  cout << string_id("world") << " ";
  cout << string_id("hello") << endl;
}

The unordered_map will end up storing each string once, so you're set for memory. Depending on your matching function, you can define
struct Component {
    int parameter;
    int value;
};

and then your matching can be something like myComponent.parameter == string_id("some_key") or even myComponent.parameter == some_stored_string_id. If you want your strings back, you'll need a reverse mapping as well.


text:
Q: How can I switch time_now in a time interval? Or a better approach for this program?     Calendar c = Calendar.get Instance();
            String time_now = c.get(Calendar.HOUR_OF_DAY) + ":"
                    + c.get(Calendar.MINUTE);
    switch (time_now) {
              case 10:00 - 10:59
                 t x t.set Text("hi");
                 break;
              case 11:00 - 11:59
                 t x t.set Text("by");
                  break;

    }

A: Since you are covering the whole hour, from 00 to 59 minutes, there is no need to consider the minutes at all. Just switch on the hour itself. Your code should look like:
Calendar c = Calendar.getInstance();
int time_now = c.get(Calendar.HOUR_OF_DAY);
switch (time_now) {
          case 10:
             t x t.set Text("hi");
             break;
          case 11:
             t x t.set Text("by");
              break;

}

A: try this code......
if(c.get(Calendar.HOUR_OF_DAY)==10){
      if(c.get(Calendar.MINUTE)>=0 && c.get(Calendar.MINUTE)<59){
           //do your work here ...
       }

 }


text:
Q: Automatic upgrade/update of .NET and Silverlight With the upcoming release of .NET 4 in mind, what are the reasons that Microsoft doesn't automatically update and upgrade the .NET Platform on all installed Windows System? Is it a legal issue?
Even Windows 7 doesn't ship with Silverlight on board and it hurts my heart everytime a customers doesn't want to install a new release of my software on his/her system because even a .NET Update takes ages to complete.

A: It's because Microsoft doesn't want to break existing applications. That's why IE6 was never upgraded in the service packs for Windows XP.
Shipping Silverlight with Windows would result in yet another lawsuit because it 'hurts' the competition/Adobe.


text:
Q: Bug ao adicionar elementos à lista e transforma-la em string Estou tento dor de cabeça no decorrer de um mini-projeto para desenvolver um jogo da forca, na função que retornaria a string contendo a palavra escondida, mostrando apenas as letras adivinhadas. Já tentei de tudo, já pesquisei sobre transformar em string com a função str() e join(), caso tenham uma outra sugestão para o código, também vai ajudar muito. Segue o código:
def char_check(char, word):
    newWord_list = []
    newWord_ = ''
    for i in range(0, len(char)-1):
        if char == word[i]:
            newWord_list.append(char)
        else:
            newWord_list.append('_'))
    newWord_ = ''.join(newWord_list)
    return newWord_

A: Além do já explicado sobre o laço de iteração...
for i in range(0, len(char) - 1):

...que deveria ser modificado para...
for i in range(0, len(word) - 1):

... seu código está desproporcionalmente verboso a dificuldade da tarefa a ser realizada.
Use uma expressão regular para esconder as letras ainda não descobertas de uma string.
A função re.sub(pattern, repl, s, count=0, flags=0) faz a substituição na string s dos caracteres encontrados pelo padrão de correspondência pattern pela string repl.
O padrão de correspondência [^caracteres] instrui a expressão a corresponder todos os caracteres exceto aos caracteres entre [^ e ].
A flag re.IGNORECASE executa uma correspondência que não diferencia maiúsculas de minúsculas.
A função re.escape(pattern) escapa caracteres especiais no padrão pattern aqui usada para prevenir a injeção de metacaracteres no padrão para evitar trapaças.
import re

def char_check(char, word):
    return re.sub(fr"[^{re.escape(char)}]", "_", word, flags=re.IGNORECASE)

Exemplo:
>>> print(char_check("p","Paralelepipedo"))
P_______p_p___

Teste o exemplo abaixo no ideone.com
import re
import random

def char_check(char, word):
    return re.sub(fr"[^{re.escape(char)}]", "_", word, flags=re.IGNORECASE)

palavra = random.choice(["Python", "Haskell", "Javascript", "Scheme", "Lisp", "Visual Basic", "Clipper", "Assembly", "Cobol", "Forth" ])
tentativas = " "

print("Você tem cinco tentativas.\n")
print(char_check(tentativas, palavra))
print("\n")
for i in range(1,6):
    tentativas += input(f"Tentativa {i}: ")
    jogada = char_check(tentativas, palavra)
    print(jogada)
    if jogada == palavra:
        print("!!!TEMOS UM VENCEDOR!!!")
        break
else:
    print("Você morreu enforcado")

#Você tem cinco tentativas.

#_____

#Tentativa 1: p
#_____
#Tentativa 2: m
#_____
#Tentativa 3: o
#_o___
#Tentativa 4: frth
#Forth
#!!!TEMOS UM VENCEDOR!!!

A: O problema do seu código está no bloco de repetição. Você está utilizando o tamanho da string char — que teoricamente deve conter apenas um caractere — na função range() como ponto de parada, quando deveria estar utilizando o tamanho da string word.
for i in range(0, len(word) - 1):
    ...

Além disso, um outro problema do seu código, ainda na mesma linha, é a utilização da subtração -1 no ponto de parada da função. Você não deve subtrair o valor do stop, porque a função define esse valor como o seu limite "definitivo". Veja o exemplo abaixo:
list(range(5))      # [0, 1, 2, 3, 4]
list(range(5 - 1))  # [0, 1, 2, 3]

Dito isso, o seu código deveria ficar assim:
def char_check(char, word):

    newWord_list = []
    newWord_ = ''

    # O valor padrão de "start" é zero. Sendo assim, não precisa especificá-lo.
    for i in range(len(word)):

        if char == word[i]:
            newWord_list.append(char)
        else:
            newWord_list.append('_')

    newWord_ = ''.join(newWord_list)
    return newWord_

Além disso, é possível melhorar ainda mais a sua função, sem precisar criar uma nova lista. Para isso, percorra cada caractere da sua string através do laço for e verifique se a letra é a mesma de char. Se sim, adicione-a para a nova string. Se não, adicione a string "_". Veja como ficaria:
def char_check(char, word):

    new_word = ""

    for letter in word:
        if char == letter: new_word += char
        else: new_word += "_"

    return new_word

É possível também fazer tudo isso em apenas uma única linha, utilizando list comprehension, da seguinte forma:
 def char_check(char, word):

    return "".join([char if char == letter else "_" for letter in word])


text:
Q: test if a certain type of file exists I have a script in bash that is supposed to classify all the text files of my working directory and put them in specified directories. It works fine but once used, I get this error message when I try to use it again :
ls: cannot access '*.txt': No such file or directory

I understand that is it basically because I have no longer any text files in my working directory, but what I'd like to do then is to be able to check first if any '.txt' file exist in my current directory before doing anything else in my script, so that instead of having this message I just exit the script.
I know it can be done for a specific file with this :
FILE=/myfile.txt
if test -f "$FILE"; then
    ...
else
     exit 1
fi

But i'd like to do it with any file ending with ".txt"

A: You could use null globbing, but stat can do the job too:
if stat -t -- *.txt >/dev/null; then
    echo 'found text files'
else
    exit 1
fi

A: You can avoid the problem by using the nullglob option.  For example:
shopt -s nullglob

for txtfile in *.txt ; do
    # Put code for classifying "$txtfile" here
done

*

*shopt -s nullglob causes glob patterns (e.g. *.txt) that match nothing to expand to nothing.

*for txtfile in *.txt ... will execute the body of the loop for every .txt file in the current directory.  With nullglob enabled, it will do nothing if there are no .txt files in the directory.


text:
Q: CouchDB sort doesn't work I recently started using CouchDB but I have no success with the sort-option using mango query.
My database is a simple person dataset and for this example I'd like to show all documents with the type "person" and sort it by the "firstName".
{
  "selector": {
    "type": "person"
  },
  "sort" : ["firstName"]
}

But it doesnt work. I just get the documents without any particular order.

This is the list of my indexes:
special: _id
json: gender
json: firstName
json: lastName

Is there something I forgot?

Edit:
As Alexis also pointed out, the docs say that the sorted field has to be present in the selector.
After testing around I figured out that the best way would be adding a greater than null condition to the field. That works in my case.


text:
Q: Display \n characters as newlines when using tail? I have a file that I am trying to read by using tail -f. I was wondering if there was a way to have the terminal output an actual line break instead of the \n character.

A: tail -f file | sed 's/\\n/\n/g'

A: tail -1 file | awk '{gsub(/\\n/,"")}1'


text:
Q: How to count the java process of specific user in ps aux Currently am executing this
ps aux | grep java

It is returning
root 4589 <some process>
user1 4218 <some process1>
user1 4248 <some process2>
user1 4258 <some process3>

Here how we can count the processes which is running by "user1"?

A: This is a bit more direct and should do what you want:
pgrep -u user1 java


text:
Q: Cannot create new project on Sublime Text 3 [MAVENSMATE]: response from mm: /bin/sh: 1: : Permission denied] I am making my first steps as a Salesforce developer and I am trying to create a new project with MavensMate on Sublime Text 3 and still, I am stuck with this permission issue.
This is the output message from the Sublime Text console.
[MAVENSMATE]: OPERATION: new_project
[MAVENSMATE]: {}
[MAVENSMATE]: mm command:
[MAVENSMATE]: '' -o new_project --ui -c SUBLIME_TEXT_3
[MAVENSMATE]: {}
[MAVENSMATE]: response from mm: /bin/sh: 1: : Permission denied

I'm running on Ubuntu 15.04 and I have overriden the MavensMate User settings and set the "mm_subl_location" : "/usr/local/bin/subl" i.e a symlink that points to the sublime text installation directory(in my case, i.e /opt/sublime_text/sublime_text .
Moreover, I have provided the following permissions for the symlink.
/usr/local/bin/subl :
lrwxrwxrwx 1 root root 30 may 23 12:59 local/bin/subl -> /opt/sublime_text/sublime_text

I have also tried to unistall and re-install both Sublime Text 3(build 3083) and MavensMate(v4.0.5), but still, the same problem occurs.
Is this some Unix basic knowledge about file permissions that I am missing here or something else that cannot see?
Any suggestions?
Thanks in advance.


text:
Q: GCD doesn't work in custom keyboard please can anyone help me? I have next problem. I created custom keyboard in xcode and want to use the GCD to load gifs async in array. But when i do this my app crash. My code
@implementation KeyboardViewController

in viewDidLoad ()

dispatch_queue_t myQueue = dispatch_queue_create("identifier", NULL);

    dispatch_async(myQueue, ^{

        @synchronized (self.gifsArray){
            @autoreleasepool {
                for (int i = 0; i < NUMBER_OF_GIFS; i++) {
                    FLAnimatedImage *gifImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%i", i] ofType:@"gif"]]];
                    [self.gifsArray addObject:gifImage];
            }

        }
        }
    });


text:
Q: Select2 Fill Drop down with ajax Web Method not working CSS
User select2  version Select2-4.0.13
and bootstrap4
   <link href="Styles/Select2-4.0.13/select2.min.css" rel="stylesheet" type="text/css" />
   <link href="Styles/Select2-4.0.13/select2-bootstrap4.min.css" rel="stylesheet" type="text/css" />

ASPX
Created Dropdown list Name with class js-data-example-ajax
<form id="form1" runat="server">
    <asp:DropDownList runat="server" class="js-data-example-ajax" style="width: 300px">
    </asp:DropDownList>
</form>

JAVA SCRIPT
loaded data to select2 dropdown using ajax web method call in document ready method
but its raising error and not working properly
    <script src="Scripts/jquery-3.4.1/jquery-3.4.1.min.css" type="text/javascript"></script>
    <script src="Scripts/Select2-4.0.13/select2.full.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.js-data-example-ajax').select2({
                theme: 'bootstrap4',
                minimumInputLength: 1,
                containerCssClass: ':all:',
                allowClear: true,
                ajax: {
                    url: 'WebForm1.aspx/getsource',
                    dataType: 'json',
                    //type: "POST",
                    params: {
                        contentType: 'application/json; charset=utf-8'
                    },
                    data: function (params) {
                        var query = {
                            q: params.term,
                            page: params.page
                        }
                        return query;
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        data = jQuery.map(data.results, function (obj) {
                            obj.id = obj.id;
                            obj.text = obj.text;
                            return obj;
                        });
                        return {
                            results: data,
                            pagination: {
                                more: params.page * 30 < 4//total records
                            }
                        };
                    },
                    success: function (data) {
                        console.log("SUCCESS: ", data);
                    },
                    error: function (data) {
                        console.log("ERROR: ", data);
                    },
                    cache: true
                }
            });
        });
    </script>

.CS File
Created Method as web method to load data to dropdown list with select2
  [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string getsource(string q, int page)
        {
            Select2ModelMain obj = new Select2ModelMain();
            obj.results = new List<SelectResult>();

            SelectResult objdata1 = new SelectResult();
            objdata1.id = 1;
            objdata1.text = "INDIA";
            obj.results.Add(objdata1);

            objdata1 = new SelectResult();
            objdata1.id = 2;
            objdata1.text = "AMERICA";
            obj.results.Add(objdata1);

            objdata1 = new SelectResult();
            objdata1.id = 3;
            objdata1.text = "CHINA";
            obj.results.Add(objdata1);

            objdata1 = new SelectResult();
            objdata1.id = 4;
            objdata1.text = "SRILANKA";
            obj.results.Add(objdata1);

            obj.pagination = new SelectPage();
            obj.pagination.more = "true";

            if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
            {
                obj.results = obj.results.Where(x => x.text.ToLower().StartsWith(q.ToLower())).ToList();
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string test = serializer.Serialize(obj);
            return test;
        }

        public class Select2ModelMain
        {
            public List<SelectResult> results { get; set; }
            public SelectPage pagination { get; set; }
        }

        public class SelectResult
        {
            public int id { get; set; }
            public string text { get; set; }
            public string disabled { get; set; }
        }

        public class SelectPage
        {
            public string more { get; set; }
        }

output

A: Step 1:
On Select2ModelMain change
public List<SelectResult> results { get; set; }

to (I'm having an issue on if it is name results)
public List<SelectResult> items { get; set; }

Step 2:
Try this javascript as an initial to check if it's working.
Note: Make sure that the action method is 'POST' instead of 'GET' i'm not sure what is the issue on if GET for select2 for a normal ajax call it works.

Side Note:
When using GET on normal ajax request this should be set to UseHttpGet = true
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]

For other options when using select2 remote query
$(document).ready(function () {
        $('.js-data-example-ajax').select2({
            ajax: {
                url: 'TestSelect2Page.aspx/getsource',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                delay: 250,
                data: function (params) {

                    var search = '';

                    if (params.term !== undefined) {
                        search = params.term;
                    }

                    return "{'q': '" + search + "'}";
                },
                processResults: function (data) {
                    var items = JSON.parse(data.d).items

                    if (items == null) {
                        return null;
                    }

                    return {
                        results: items
                    };
                }
            },
            placeholder: 'Search here',
            minimumInputLength: 1
        });
    });

OUTPUT 1:

OUTPUT 2:

I hope this helps. Happy coding.

A: Thank you so much its working...
enter image description here
but we are facing another issue
i.e. selected event changed OnSelectedIndexChanged is not working
so we added another line "<asp:ListItem Selected="True"></asp:ListItem>"
after this it fires OnSelectedIndexChanged  but its not showing selected Item
2
3
 <asp:Label ID="LblItemName" runat="server" Style="font-weight: bold;" Text="Product Name"></asp:Label>
                                <asp:DropDownList runat="server" ID="txtItemName" data-width="100%" CssClass="select2-single input-sm w-100"
                                    AutoPostBack="true" OnSelectedIndexChanged="txtItemName_SelectedIndexChanged">
                                    <asp:ListItem Selected="True"></asp:ListItem>
                                </asp:DropDownList>


text:
Q: How to performe deep packet inspection using Ryu controller fot Qos Perposes I am trying to prioritize voice & video traffic over other types of traffic , i am using scapy to inspect and capture the traffic , i cant find a way to distinguish between those types. the field tos is always tos=0x0 .
i am doing this to send a set of rules to SDN edges using Ryu Controller


text:
Q: Check usable components for model models.py:
class CarType(models.Model):
    engine = models.CharField()
    transmission = models.CharField()

class Car(models.Model):
    car_type = models.ForeignKey(CarType,)
    color ...

class Details(models.Model):
    car = models.ForeignKey(Car, blank=True, null=True, related_name='details')
    engine = models.CharField()
    transmission = models.CharField()

For example, we have BMW car. This type of car need to install only engine class A+.
Then, when we add a new details to our car (we can add new car with details too), we need to check - is a detail, that we want to install, is the same, that this car type support.
So, we need always and everywhere check, what details we add of which car type, what car we create with what details.
If we add engine class B to our BMW (needs engine class A+), raise some exception.
The save method in Car class not enough, because we can add new detail to car  through Detail class.
How would you solved this problem?
Thanks!

A: You can use a custom validator.
from django.core.exceptions import ValidationError

def validate_a(instance):
    if instance.engine != 'A+':
        raise ValidationError('Instance requires A+ class engine')

Then in models.py
...
class Car(models.Model):
    ...
    car = models.ForeignKey(Car,
                            blank=True,
                            null=True
                            related_name='details',
                            validators=[validate_a])