text:
Q: bytebuddy apply advice to interface methods - specifically spring data jpa I am trying to LOG all methods that are invoked in my Springboot application using byte-buddy based java agent.
I am able to log all layers except Spring data JPA repositories, which are actually interfaces. Below is agent initialization:
        new AgentBuilder.Default()
            .type(ElementMatchers.hasSuperType(nameContains("com.soka.tracker.repository").and(ElementMatchers.isInterface())))
            .transform(new AgentBuilder.Transformer.ForAdvice()
                    .include(TestAgent.class.getClassLoader())
                    .advice(ElementMatchers.any(), "com.testaware.MyAdvice"))
            .installOn(instrumentation);

any hints or workaround that I can use to log when my repository methods are invoked. Below is a sample repository in question:
package com.soka.tracker.repository;
.....
@Repository
public interface GeocodeRepository extends JpaRepository<Geocodes, Integer> {
  Optional<Geocodes> findByaddress(String currAddress);
}

Modified agent:
    new AgentBuilder.Default()
            .ignore(new AgentBuilder.RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader().or(isExtensionClassLoader())))
            .ignore(new AgentBuilder.RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.")
                    .and(not(ElementMatchers.nameStartsWith(NamingStrategy.SuffixingRandom.BYTE_BUDDY_RENAME_PACKAGE + ".")))
                    .or(nameStartsWith("sun.reflect."))))
            .type(ElementMatchers.nameContains("soka"))
            .transform(new AgentBuilder.Transformer.ForAdvice()
                    .include(TestAgent.class.getClassLoader())
                    .advice(any(), "com.testaware.MyAdvice"))
            //.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
            .with(AgentBuilder.TypeStrategy.Default.REDEFINE)
            .installOn(instrumentation);

I see my advice around controller and service layers - JPA repository layer is not getting logged.

A: By default, Byte Buddy ignores synthetic types in its agent. I assume that Spring's repository classes are marked as such and therefore not processed.
You can set a custom ignore matcher by using the AgentBuilder DSL. By default, the following ignore matcher is set to ignore system classes and Byte Buddy's own types:
new RawMatcher.Disjunction(
    new RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader().or(isExtensionClassLoader())),
    new RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.")
      .and(not(ElementMatchers.nameStartsWith(NamingStrategy.SuffixingRandom.BYTE_BUDDY_RENAME_PACKAGE + ".")))
      .or(nameStartsWith("sun.reflect."))
      .<TypeDescription>or(isSynthetic())))

You would probably need to remove the last condition.

A: for anybody visiting this question / problem - I was able to go around the actual problem with logging actual queries invoked during execution - Bytebuddy is awesome and very powerful - for ex- in my case I am simply advice'ing on my db connection pool classes and gathering all required telemetry -
.or(ElementMatchers.nameContains("com.zaxxer.hikari.pool.HikariProxyConnection"))


text:
Q: How to determine misprediction penalty?(CPU pipeline) I was reading a textbook which says:
Assume the probability of misprediction is p, the time to execute the code without misprediction is TOK and the misprediction penalty is TMP. Then the average time to execute the code as a function of p is:
Tavg(p) =  (1− p)TOK + p(TOK + TMP)
I'm a little bit confused, isn't it should be:
Tavg(p) =  (1− p)TOK + pTMP
for example, let's say p is 0.5, it takes 10 clock cycles for cpu when branch prediction is correct and it takes 20 clock cycles for cpu when branch prediction is incorrect, isn't the average clock cycles is 0.5(10+20) = 15 clock cycles?

A: TMP is defined as the misprediction penalty, or the amount of time to recognize the processor took a mistaken path and to get back on track executing the correct path, which does not include the time it takes to actually execute the correct path, ie TOK. That's why when there's a misprediction, it takes TMP + TOK rather than just TMP to complete the execution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proof verification, generalized intersection Like the question says: I answered a Question a couple of days ago, someone commentented that it's wrong and didn't give any specifics so i just want someone to verify my proof.
Regards
https://math.stackexchange.com/a/4555599/606249
The question: Prove that $\cap S$ exists for any set $S$.
Here's my answer:
Let $S\neq \emptyset$ be arbitrary, consider two arbitrary sets $S_0,S_1\in S$ such that $S_0\neq S_1$. Either $S_1$ or $S_0$ is empty, but not both.
If $S_0/S_1$ is empty $S_1\cap S_0=\emptyset$. The empty set exist by ZF. (Technically we are running cases here, but we know what's going on so I will skip the technicality).
If $S_0/S_1$ is not empty, either  $S_1 \cap S_0= S_{\cap}$, meaning the two sets $S_1$ and $S_0$ share an element, and, therefore, $S_{\cap}$ exists.
Or, $S_0/S_1$ is not empty, but $S_1\cap S_0=\emptyset$ (empty set exists). Therefore, it holds for the base case.
Suppose that $\cap_{0\leq i\leq n}S$ exists.
By the inductive assumption $\cap_{0\leq i\leq n}S=S'$, consider the set $S_{n+1}\in S$ such that $S_{n+1}\neq S_i, i\in[0,n]$;
Either $S_{n+1}$ is empty or not. If it's empty $S'\cap S=\emptyset$ so we are done.
Or, $S_{n+1}$ is not empty:
Then either $S'\cap S_{n+1}=S^*$, hence the intersection exists. Or, $S'\cap S_{n+1}=\emptyset$.
Hence, $\cap_{0\leq i\leq n+1}S$ exists.
Therefore, $\forall S, \cap S$ exists.


text:
Q: Difficulty Integrating Powerapps, Flow, and SharePoint I built a form in Powerapps that I want to workflow and placed it in SharePoint 2013.  When trying to add email addresses of employees, I get an error and it wont pull in outlook email address.  i type in the email addresses manually, and it wont accept them.
Also, I'm unable to save my progress because of the erros.  The errors have to be resolved in order to save.
The errors are simply fields (email address field) that is highlighted in red.  But it doesn't explain why it is an error / why field is highlighted in red.  only that you have to fix it somehow


text:
Q: android studio emulator hangs on startup on m1 I'm trying to run Android Studio emulator version 31.3.13.0 on MacOS 12.5.1 with M1. The emulator hangs with no error message after the following lines:
~/Library/Android/sdk/emulator$ ./emulator -avd Pixel_5_API_33 -verbose -show-kernel
INFO    | Android emulator version 31.3.13.0 (build_id 9189900) (CL:N/A)
INFO    | Found AVD name 'Pixel_5_API_33'
INFO    | Found AVD target architecture: arm64
INFO    | argv[0]: './emulator'; program directory: '/Users/x/Library/Android/sdk/emulator'
VERBOSE |  Found directory: /Users/x/Library/Android/sdk/system-images/android-33/google_apis/arm64-v8a/
emulator: INFO: Found systemPath /Users/x/Library/Android/sdk/system-images/android-33/google_apis/arm64-v8a/
INFO    | emuDirName: '/Users/x/Library/Android/sdk/emulator'
INFO    | try dir /Users/x/Library/Android/sdk/emulator
INFO    | Trying emulator path '/Users/x/Library/Android/sdk/emulator/qemu/darwin-aarch64/qemu-system-aarch64'
INFO    | Found target-specific 64-bit emulator binary: /Users/x/Library/Android/sdk/emulator/qemu/darwin-aarch64/qemu-system-aarch64
INFO    | Adding library search path: '/Users/x/Library/Android/sdk/emulator/lib64'
INFO    | Adding library search path: '/Users/x/Library/Android/sdk/emulator/lib64/gles_angle'
INFO    | Adding library search path: '/Users/x/Library/Android/sdk/emulator/lib64/gles_angle9'
INFO    | Adding library search path: '/Users/x/Library/Android/sdk/emulator/lib64/gles_angle11'
VERBOSE | Adding library search path for Qt: '/Users/x/Library/Android/sdk/emulator/lib64/qt/lib'
VERBOSE | Silencing all qWarning(); use qCWarning(...) instead: QT_LOGGING_RULES=default.warning=false
VERBOSE | Setting Qt plugin search path: QT_QPA_PLATFORM_PLUGIN_PATH=/Users/x/Library/Android/sdk/emulator/lib64/qt/plugins
VERBOSE | Setting Qt to use software OpenGL: QT_OPENGL=software
VERBOSE | Setting QML to use software QtQuick2D: QMLSCENE_DEVICE=softwarecontext
VERBOSE | Overriding pre-existing bad Qt high dpi settings...
VERBOSE | emulator: Running :/Users/x/Library/Android/sdk/emulator/qemu/darwin-aarch64/qemu-system-aarch64
VERBOSE | qemu backend: argv[00] = "/Users/x/Library/Android/sdk/emulator/qemu/darwin-aarch64/qemu-system-aarch64"
VERBOSE | qemu backend: argv[01] = "-avd"
VERBOSE | qemu backend: argv[02] = "Pixel_5_API_33"
VERBOSE | qemu backend: argv[03] = "-verbose"
VERBOSE | qemu backend: argv[04] = "-show-kernel"
VERBOSE | Concatenated backend parameters:  /Users/x/Library/Android/sdk/emulator/qemu/darwin-aarch64/qemu-system-aarch64 -avd Pixel_5_API_33 -verbose -show-kernel

Any help would be appreciated.


text:
Q: PHP conditions depending on window width (media queries?) I have a responsive website and I need some PHP conditions depending on the windows width (or media queries).
Example:
if ($window_width > 1400px) {
    echo 'Your window is wider than 1400px';
}

elseif ($window_width > 1000px) AND ($window_width < 1399px) {
    echo 'Your window is between 1000px and 1399px';
}

else {
    echo 'Your window is narrower than 1000px.';
}

Thanks for your help!

A: check this
Goolgle Mobile Detect
Try to use http://www.php.net/get_browser and check for isMobileDevice field. It might help only, of course, if the path to browscap.ini is set up in php.ini. If not, you can use php classes like https://github.com/garetjax/phpbrowscap

A: Nope you can not do it with php.
php is strictly  server side
user javascript instead.
Below is my code to get device resolution using javascript

A: In views you can show/hide divs, something like this:

    <?php echo "is mobile"; //include("page_mobile.phtml"); ?>

    <?php echo "is web"; //include("page_web.phtml"); ?>

A: I'm assuming this is for device detection. I'm not sure if you can detect window width using PHP alone. If you can then this information would appear in the HTTP headers. I would recommend using an open source PHP class built for this: http://mobiledetect.net/

A: Here is the trick:
Evaluate the window width with js, then load your PHP in a frame and put the width in a parameter. Your PHP script then can read that parameter and perform different conditions depending on that value.
Here is the js part:

Within your content.php file just read the width parameter and do something with it:
<?php
    //Get width of browser window
    $width = $_GET['w'];
    echo ('width: '.$width);
?>


text:
Q: How to draw the interactions between source and destination countries using ip address? I am trying to create a clickable world map with one marker for each country. When a marker of a source country is being clicked, interactions should be shown with other countries in a aggregated way. I was able to draw the world map but I am not sure about how to draw the interactions between 2 countries using ip addresses which are given in the CSV files. I tried looking for solutions but in vain. I am new to d3.js. Would be great if someone could throw some light into this.
A suggestion would be of really helpful. suggestion about how to go forward using any relative library(if needed) or any other suggestion would be as helpful as any direct answers. Thank you.
Here is the plnkr
Here is the Script
var app = angular.module("chartApp", []);
app.controller("SalesController", function($scope, $http) {
$http.get("countries.csv").then(function(response) {
    $scope.salesData = response;
    });
});

app.directive("linearChart", function($window) {
return {
    restrict: "EA",
    // template: "<svg width='1024' height='728'></svg>",
    link: function(scope, elem, attrs) {
        // canvas resolution
        var margin = { top: 50, left: 50, right: 50, bottom: 50 },
            height = 900 - margin.top - margin.bottom,
            width = 1400 - margin.left - margin.right;

        // defines "svg" as data type and "make canvas" command
        var svg = d3.select("#map")
            .append("svg")
            .attr("height", height + margin.top + margin.bottom)
            .attr("width", width + margin.left + margin.right)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        // var width = 1500,
        //     height = 900;

        d3.queue()
            .defer(d3.json, "https://unpkg.com/world-atlas@1.1.4/world/110m.json")
            .defer(d3.csv, "countries.csv")
            .await(ready);

        // projection-settings for mercator
        var projection = d3.geoMercator()
            // .translate([width / 2, height / 2])
            // where to center the map in degrees
            .center([-30, 60])
            // // zoomlevel
            .scale(200);
        // // map-rotation
        // .rotate([0, 0]);

        /* Create a Path using projection */

        var path = d3.geoPath()
            .projection(projection);

        function ready(error, data, country_name) {
            console.log(data);

            var countries = topojson.feature(data, data.objects.countries).features;
            console.log(countries);
            console.log(country_name);

            /* Add a path for each country
                 Shapes -> Path
            */

            svg.selectAll(".country")
                .data(countries)
                .enter().append("path")
                .attr("class", "country")
                .attr("d", path)
                .on('mouseover', function(d) {
                    d3.select(this).classed("selected", true);
                })
                .on('mouseout', function(d) {
                    d3.select(this).classed("selected", false);
                });

            svg.selectAll(".country-circles")
                .data(country_name)
                .enter().append("circle")
                .attr("class", "circle")
                .attr("r", 2)
                .attr("cx", function(d) {
                    var coords = projection([d.longitude, d.latitude]);
                    return coords[0];
                })
                .attr("cy", function(d) {
                    var coords = projection([d.longitude, d.latitude]);
                    return coords[1];
                });

            svg.selectAll(".countries")
                .data(country_name)
                .enter().append("marker")
                .attr("class", "countries")
                .attr("x", function(d) {
                    var coords = projection([d.longitude, d.latitude]);
                    return coords[0];
                })
                .attr("y", function(d) {
                    var coords = projection([d.longitude, d.latitude]);
                    return coords[1];
                })

                // .text(function(d) {
                //     return d.country_name;
                // })
                .attr("dx", 5)
                .attr("dy", 2);
           }
         }
      };
  });

A: To point you in the right direction:
You have a CSV file with IP addresses, but in my opinion, you need the longitude and latitude of the countries.
You could try to batch convert these here or maybe you could use an api like this in order to get the right long and lat with the corresponding IP addresses.
In order to show the interaction between those points, I think this example here is most helpfull to get you on your way.


text:
Q: A specific fancy chapter heading So, basically I'm working on my memoir. TeX and LaTeX are rather new for me. I really looked everywhere to be able to design the same chapter heading as Walter Appel does in his brilliant book called "Mathematics For Physics and physicists !".
This is how it looks:

I tried using the titlesec package like this:
\documentclass[11pt, a4paper,oneside]{book}
\usepackage{titlesec}
\titleformat{\chapter}[display]
  {\normalfont\huge\bfseries\centering}
  {\begin{adjustbox}{angle=90}\hbox{\chaptertitlename}\end{adjustbox}\ \color{gray}\thechapter}{20pt}{\Huge}

But I don't know how I can make it look more like Walter Appel does.
I would really appreciate your help. Also, I apologize in advance for my bad English (I'm French) and for the code I provided which is rather not that advanced.

A: Without using titlesec but with manually redefining the internal \@makechapterhead. This comes pretty close, the fonts differ and maybe the sizes aren't perfect.
\documentclass[11pt, a4paper, oneside]{book}

\usepackage[french]{babel}

\usepackage{duckuments}
\usepackage{xcolor}
\usepackage{graphics}

\colorlet{chapnum}{black!40}

\makeatletter
\renewcommand\@makechapterhead[1]
  {%
    \vspace*{50\p@}%
    \begingroup
      \centering
      \normalfont
      \bfseries
      \rotatebox{90}{\Large\sffamily\chaptername}
      \begingroup
        \scalebox{3.5}{\Huge\color{chapnum}\thechapter}\par\vskip10\p@
      \endgroup
      \interlinepenalty\@M
      \Huge
      #1\par
      \nobreak\vskip40\p@
    \endgroup
  }
\makeatother

\begin{document}
\chapter{Convergence et limites}
\blindduck

\duckument
\end{document}

A: A simple solution with titlesec:
\documentclass[11pt, a4paper,oneside]{book}
\usepackage{graphicx}
\usepackage[svgnames]{xcolor}
\usepackage{titlesec}
\titleformat{\chapter}[display]
  {\normalfont\bfseries\Huge\filcenter}
{\sffamily\rotatebox{90}{\normalsize\chaptertitlename}\,\scalebox{2.24}{\color{Gainsboro}\thechapter}}
  {20pt} {}

  \begin{document}

    \chapter{Some Fancy Chapter}

  \end{document}


text:
Q: How can I improve the performance of HDF5 reading data? What I need is to get the unique date value as soon as possible.
I use the code df = store.df.date.drop_duplicates() to retrieve. This line of code takes 6 seconds. However, if I use mysql and save the same data to mysql, I use mysql for the date column After indexing, using sql:select distinct date from table, it only takes 80ms to retrieve the unique date value, which is 60 times faster than HDF5.
Is there any way to make the function read_unique_date read HDF5 faster than MySQL uses indexes?
My code is as follows:
import pandas as pd
import numpy as np
from itertools import product
from time import time

def generate_data():
    np.random.seed(202108)

    # date = pd.date_range(start="19900101", end="20210723", freq="D")
    #The above is my original code, you can use the following code to speed up the operation.
    date = pd.date_range(start="20210101", end="20210723", freq="D")
    date = pd.DataFrame(date, columns=["date"])

    # code = pd.DataFrame(range(5000), columns=["code"])
    #The above is my original code, you can use the following code to speed up the operation.
    code = pd.DataFrame(range(50), columns=["code"])

    # generate product of the two columns:
    df = pd.DataFrame(product(date["date"], code["code"]), columns=["date", "code"])
    df['data'] = np.random.random(len(df))
    return df

def save_data(filename, df):
    store = pd.HDFStore(filename)
    store['df'] = df
    store.close()
    return

def read_unique_date(file_name):
    store = pd.HDFStore(file_name)
    start = time()
    df = store.df.date.drop_duplicates()
    store.close()
    stop = time()
    print(stop - start)
    return df

def main():
    path = 'd:\\'
    file = 'large data.h5'
    file_name = path + file
    df = generate_data()
    save_data(file_name, df)
    df1 = read_unique_date(file_name)
    print(df1)
    return df1

if __name__ == '__main__':
    main()

The result is:
0.015624761581420898
0       2021-01-01
50      2021-01-02
100     2021-01-03
150     2021-01-04
200     2021-01-05
           ...
9950    2021-07-19
10000   2021-07-20
10050   2021-07-21
10100   2021-07-22
10150   2021-07-23
Name: date, Length: 204, dtype: datetime64[ns]

%timeit df1 = read_unique_date(file_name)
16.9 ms ± 200 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The result of my original code:
%timeit df1 = read_unique_date(file_name)
4.89 s ± 119 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: The short answer is that HDF5 simply does not have indexes apart from the keys to datasets (dataset names) and contiguous array indices. So the only lookup operations directly from a file that you can expect to perform sublinearly is retrieving the Nth value in an dataset. To find unique values directly from a file HDF5 has to read the whole file. You might be able to cook up something messy but functional with HDF5 groups and references but then you're just implementing indexing yourself and I don't advise going that route.
On the otherhand Pandas uses hashtables, trees and binary search to speed up various lookup operations. You could load the data into a dataframe for the queries. But generally you want to move to a proper database at some point. Pandas and HDF5 can only take you so far.

A: pandas has a method named read_hdf documented here. You can simply read your stored .h5 saying:
read_df = pd.read_hdf('./large data.h5')

and you can access read_df as a pandas data frame.
Now if you'd ask me, it would not be a great idea to store a file and read it again for periodical loop use. I'd keep the data in the form of a data frame and write it only when necessary (i.e. I need the space in the memory or I need to update the database with some shared access). I would say strategizing the write and read should be considered to optimize the code run.
btw, your code crashed my debug at:
    df = pd.DataFrame(product(date["date"], code["code"]), columns=["date", "code"])

you might want to look into it again.

A: Your code is running as-is so it is difficult to tell what you are trying to get at here without an example of the output you desire. Your nearly 1.8 GB of data that is generated by this code is not relevant to your issue unless I am missing something and this is really a performance related question. If the following does not solve your issue, I recommend you significantly pare down your generated data and provide an example of the desired output so people can help you without having to assume what you are trying to get to.
Taking a guess as to what you are wanting, I think the issue lies in how you are eliminating duplicates. You are dropping duplicates from the series of dates contained within the dataframe setting df equal to this pared down series. Instead, I believe what you want is to drop duplicates from the dataframe using df.drop_duplicates() and specifying the date column as the subset.
Example: df.drop_duplicates(subset="date").
Does this solve your issue?


text:
Q: Testng Tests is igored   @DataProvider(name = "Standard_ask")
   public Iterator<Object[]> txtReader() throws  IOException{
       File asks = new File("src/test/resources/testdata/standard_ask.txt");
       FileReader reader = new FileReader(asks);
       BufferedReader bufferReader = new BufferedReader(reader);
       String[] c =new String[1000];
       String s = null;
       ArrayList all = new ArrayList();
       while ((s = bufferReader.readLine()) != null)
           all.add(s);
       Iterator ask = all.iterator();
       System.out.println(ask.next());
       return ask;
   }
   // just add test assertion to test why this test is igored
   @Test(dataProvider = "Standard_ask", alwaysRun = true)
   public void testSimilarityFaqTest(Iterator<Object[]> a) throws IOException {
       System.out.println(a.next());
       if (a.hasNext() == true){
           String strResponse = httpClientUtil.doGetForSingleParam(url,a.next());
           JSONObject jsonResponse = JSONObject.parseObject(strResponse);
           Assert.assertEquals(jsonResponse,1);
       }

I got below test result
 可以教我怎么使用吗

java.lang.ClassCastException: java.lang.String cannot be cast to
[Ljava.lang.Object;

at org.testng.internal.Parameters$2.next(Parameters.java:537)
at org.testng.internal.Parameters$2.next(Parameters.java:522)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1165)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:73)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)

Test ignored.
===============================================
Default Suite
Total tests run: 1, Failures: 1, Skips: 0
anybody has any testng issus above,or could you please tell me why?

A: It should be
    @Test(dataProvider = "Standard_ask", alwaysRun = true)
    public void testSimilarityFaqTest(Object a) throws IOException {
    //omitted


text:
Q: Regular Expressions: Remove character before match I was wondering if there was a way to use Regular expressions to remove n occurrences of characters right before n matches of [removebefore]
Might be unclear, but an example explains everything:
This is a teststring[removebefore][removebefore][removebefore]. blablabla[removebefore][removebefore]
should be changed into
This is a teststr. blablab
Of course this can be done by matching and replacing /.\[removebefore\]/ a dozen of times, but is there a way to do this in one regexp?
EDIT:
I was trying to do this in PHP. And indeed I am searching for a regular expression that matches [anychar]{n}\[removebefore\]{n} where n is the number of removebefore's.

A: One possible solution using perl
Regular expression:
s<([^\[]+)((?:\[removebefore\])+)><substr( $1, 0, length($1) - scalar(split(/]\[/, $2)) )>ge

Test:
Content of script.pl:
use warnings;
use strict;

while ( <DATA> ) {
    s<([^\[]+)((?:\[removebefore\])+)><substr( $1, 0, length($1) - scalar(split(/]\[/, $2)) )>ge;
    print;
}

__DATA__
This is a teststring[removebefore][removebefore][removebefore]. blablabla[removebefore][removebefore]

Running script:
perl script.pl

And result:
This is a teststr. blablab

A: As far as I know, regex match things. They don't delete or modify input.
A pretty straightforward algorithm would be:
1 - Read your input counting the characters until you get to a [removebefore].
2 - When you get to [removebefore], count the number of [removebefore] in another variable.
3- Subtract the number of [removebefore] from the number of characters and save it in a variable, let's call it "n".
4 - Go again through your input, printing the first "n" number of characters.
There is some error handling to be done in this algorithm, but that's basically it.


text:
Q: How I get a by name a property of an System.Object I have an object of type Microsoft.Azure.EventGrid.Models.EventGridEvent. It has a property named Data of type System.Object. I want to access the value of the itemId property of Data. How do I get the value of a System.Object property?

A: You have to down cast to the actual type of the object. Since you know the type of the object that you expect, this should work in most cases, but I recommend you have some error handling to detect the case where some code has set the value of Data to a type you didn't expect, or to null. Personally I like to do checked downcasts with the as operator, because I find that concise, so something like this:
int GetItemId(EventGridEvent ev)
{
    T dt = ev.Data as T // where T is the known concrete type that you've set
    if(dt == null)
    {
        // ... error handling: what will you do if you find an unexpected type?
    }
    else
    {
        return dt.itemId;
    }
}

A: MS docs imply that data for data property is stored in JSON format.
In that case  - in addition to dynamics - one could also go with Newtonsoft to get the value of itemId:
JToken itemIdToken = JObject.Parse((string)event.Data)["itemId"];

A: System.Object has no properties. However, assuming that there is another object derived from object (so basically any object) you can access it's properties by name using the dynamic keyword:
Microsoft.Azure.EventGrid.Models.EventGridEvent event = GetEvent();
dynamic data = event.Data;
dynamic itemId = data.itemId;

However, I would recommend you look for the proper classes and datatypes, that is much safer and easier than guessing and seeing whether it works at runtime.


text:
Q: How to use parentheses in .bat files, set command and IF EXIST Ok, I have  batch file, just a simple one that hides and unhides folders.
I don't see why it cannot seem to execute accordingly;
Here is extended sample code:
@echo off
color a
title Folder/Drive hider Service

:jiki
echo Loading...
TIMEOUT /T 2 >nul
goto inputs
:inputs
echo Enabling security...
TIMEOUT /T 2 >nul
cls
goto menu

:menu
if EXIST "%~dp0\Encryption" (set status=Folder is locked.)
if EXIST "%~dp0\Logan_Documents" (set status=Folder is unlocked, to open it, enter open as your            `action.)`
cls
echo.
echo STATUS: %status%
echo.
echo ----------------------------------------
echo  FOLDER PROTECTOR by Logan
echo ----------------------------------------
echo.
echo  Lock      = Lock the folder(s)
echo  Unlock    = Unlock the folder(s)
echo  Credits   = For more info
echo  V         = Display your current version
echo  Exit      = Close the program
echo.
echo ----------------------------------------
echo For more info, just ask Logan!
echo ----------------------------------------
echo.
echo Select your action, %USERNAME%.
echo.
set /p "menu=>"
if /I %menu%== lock goto lock
if /I %menu%== unlock goto unlock
if /I %menu%== credits goto credits
if /I %menu%== v goto version
if /I %menu%== exit goto exit
goto invalid

and also a lot more, and every time I go to execute the script, it just leaves the status variable blank.
Here's what I've tried.

*

*Reconfiguring all variables through a port, which then sorts based on if exist. doesn't work, just leaves status blank.

*Using different variables. (Kinda stupid but I didn't want to think that I have all these errors because of a small typo.) Still left error blank.

Appreciate all efforts to resolve my problem and get this program working!
-Logan

A: if exist should work fine exactly as you use it. You don't strictly need the quotes, since the names don't include spaces. Also you don't need the parentheses since it is a single command.
But then again, it should work with them as well (I actually tested this), so the only thing I can imagine is that the files or folders are not found because the script is running in the wrong directory. After all you use just the names without any path, so the current directory should contain those files.
The 'current directory' isn't necessarily the directory in which the script is saved. If you are in 'C:\Foo' and you call 'C:\Bar\Script.bat', the current directory will still be 'C:\Foo'. The same goes for starting scripts through a shortcut.
To try this, you can use echo %CD% in your script to echo the current directory.
As a possible solution, you can use %~dp0 to use the actual directory in which the batch script is saved, so you always have a starting point to start from:
REM Check if 'Encryption' exists in the same folder as the batch file.
if EXIST "%~dp0\Encryption" (set status=Folder is locked.)

A: probably neither of the ifs are true, maybe because the active directory is not what you think it is. you can test this easily by inserting a set status=none above the ifs. or insert dir to see what the scrips actually sees at this point.


text:
Q: Se retornar dados da base de dados o else fica inválido Criei uma tabela para ser preenchida com Datatables. Se retornar dados da base de dados, pretendo que pegue na última data do campo data e preencha com a data do dia seguinte ao existente na base de dados, se não retornar dados pretendo que preencha com o primeiro dia do mês seguinte o campo data.
Tenho o código da seguinte forma:
HTML:

     <button type="button" name="add" id="add" class="btn btn-info"></button>

      Data
      Resp. de Turno
      Apoio
      Elementos ALA A
      Elementos ALA B

JavaScript:
$(document).ready(function(){

  fetch_data();

  function fetch_data()
  {
   var dataTable = $('#user_data').DataTable({
    "processing" : true,
    "serverSide" : true,
    "oLanguage": {
    "sProcessing": "Aguarde enquanto os dados são carregados ...",
    "sLengthMenu": "Mostrar _MENU_ registros por pagina",
    "sZeroRecords": "Nenhum registro correspondente ao criterio encontrado",
    "sInfoEmtpy": "Exibindo 0 a 0 de 0 registros",
    "sInfo": "Exibindo de _START_ a _END_ de _TOTAL_ registros",
    "sInfoFiltered": "",
    "sSearch": "",
    "oPaginate": {
       "sFirst":    "",
       "sPrevious": "",
       "sNext":     "",
       "sLast":     ""
     }
    },
    "order" : [],
    "ajax" : {
     url:"./fetchmapa",
     type:"POST"
    }
   });
  }
function novaData(d){
   var dia  = d.getDate().toString();
   dia = (dia.length == 1) ? '0'+dia : dia;
   var mes  = (d.getMonth()+1).toString();
   mes = (mes.length == 1) ? '0'+mes : mes;
   var ano = d.getFullYear();
   return dia+"-"+mes+"-"+ano;
}

  class CellDate {
    constructor(start_date) {
        this.date = start_date;
    }
    getNextDate() {
   //here the change for if condition
   if ($('#user_data tbody tr') != null && $('#user_data tbody tr').length > 0) {
            var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
            var ultimo_dia = +ultima_data[0];
            var ultimo_mes = +ultima_data[1];
            var ultimo_ano = +ultima_data[2];
            this.date.setDate(ultimo_dia);
            this.date.setMonth(ultimo_mes - 1);
            this.date.setYear(ultimo_ano);
            this.date.setDate(this.date.getDate() + 1);
            console.log('if', this.date);
        } else {
            this.date.setMonth(this.date.getMonth() + 1);
            this.date.setDate(1);
            console.log('else', this.date);
        }
        return novaData(this.date);
    }
}

  var DateIndexer = new CellDate(new Date(Date.now()));

 $('#add').click(function(){

   var html = '
';
   html += ''+DateIndexer.getNextDate()+'	';
   html += '	';
   html += '	';
   html += '	';
   html += '	';
   html += '<button type="button" name="insert" id="insert" class="btn btn-success btn-xs"></button>	';
   html += '
';
   $('#user_data tbody').prepend(html); //<--- right here

});

 $(document).on('click', '#insert', function(){
   var data = $('#data1').text();
   var responsavel = $('#data2').text();
   var apoio = $('#data3').text();
   var elementos = $('#data4').text();
   var elementos1 = $('#data5').text();
   if(data != '' && responsavel != '' && apoio != '' && elementos != '' && elementos1 != '')
   {
    $.ajax({
     url:"./insert",
     method:"POST",
     data:{data:data, responsavel:responsavel, apoio:apoio, elementos:elementos, elementos1:elementos1},
     success:function(data)
     {
      $('#alert_message').html('
'+data+'
');
      $('#user_data').DataTable().destroy();
      fetch_data();
     }
    });
    setInterval(function(){
     $('#alert_message').html('');
    }, 5000);
   }
   else
   {
    alert("Os campos são de preencimento obrigatório!");
   }
  });

Desta forma se já existir dados na tabela de dados, preenche o campo data com a data do dia seguinte, mas se a tabela da base de dados estiver vazia e não retornar dados, recebo a seguinte mensagem na consola:

if Invalid Date

Mas se retirar no javascript o fetch_data(); já funciona, mas não mostra os dados que já existem na base de dados e vai sempre iniciar no primeiro dia do mês seguinte.
Deixo aqui os dois exemplos.
Exemplo com o problema:
Com o fetch_data(); onde não inicia no primeiro dia do mês seguinte uma vez que não retorna dados inserir a descrição do link aqui
Exemplo que funciona:
Sem o fetch_data();, mas se existir dados na base de dados não os mostra ao utilizador inserir a descrição do link aqui
Pretendia colocar o exemplo que não funciona a funcionar, porque pretendo mostrar os dados ao utilizador, caso exista em base de dados.

A: É porque o Datatables, quando não há dados vindos do Ajax, cria automaticamente uma linha com apenas uma coluna informando que não existe dados a mostrar, e ao entrar no if irá tentar puxar uma data que não existe.
Para resolver isso, basta verificar no if se a primeira linha da tabela possui mais de uma coluna, ou seja, que pelo menos 1 linha com dados foram acrescentados na tabela, se existe mais de uma coluna na primeira linha:
if ($('#user_data tbody tr:first td').length > 1) {


text:
Q: How can I get the return value of /bin/ls -R if I run it using execl()? So I have an assignment for Uni, in Linux C. The program has to call a child process, that has to run the /bin/ls -R command, then write out the return value in the parent process, that can't be 0. So far I could only get it working using the system() call, but I can't use that. The wait(&value) line works with the system() function, but not with execl. The code I've come up with so far:
int main(){
    int value=0;
    if(fork() == 0){
        printf("Running command, please wait..\n");
        sleep(2);
        char *path = "/bin/ls";
        char *arg1 = "-R";
        execl(path, arg1, NULL);
        exit(1);
    }

    wait(&value);
    printf("\nProcessing return value, please wait..\n");
    sleep(2);
    printf("\nThe return value of the child: %d \n", value);
}

A:
How can I get the return value of /bin/ls -R if I run it using execl()?

If you wait() correctly (see bottom of my answer) then you are getting the return value of /bin/ls -R.

that can't be 0

Not sure what you mean by this, but an exit status of 0 means that the process exited correctly. Something different than 0 means an error occurred, so you usually want things to exit with 0, not something else.
The exec*() family of functions does not return when the execution succeeds. Read the manual page to know more.
If you want the child to fail then pass an invalid path to execl to make it fail or just return 1 straight away. In order to make ls -R return something different than 0 you might want to pass a third argument to execl() pointing to a path to which you do not have access to, like for example /root.

I am also not entirely sure what's wrong about your code, since it compiles and works correctly on my machine, but, here's some rules of thumb to follow both to find the problem and to avoid it in the first place:

*

*Always read the manual (in this case man 2 wait):
If  wstatus  is  not NULL, wait() and waitpid() store status information in the int to which it points.  This
integer can be inspected with the following macros (which take the integer  itself  as  an  argument,  not  a
pointer to it, as is done in wait() and waitpid()!):

WIFEXITED(wstatus)
      returns  true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by return‐
      ing from main().

WEXITSTATUS(wstatus)
      returns the exit status of the child.  This consists of the least significant 8  bits  of  the  status
      argument  that  the  child  specified in a call to exit(3) or _exit(2) or as the argument for a return
      statement in main().  This macro should be employed only if WIFEXITED returned true.

*Always check for errors on functions that might fail. Hint: basically 99% of syscalls can fail, fork and wait are some of those.
pid_t child_pid = fork();
if (child_pid == -1) {
    perror("fork() failed");
    return 1;
}

// ...

pid_t res = wait(&child_status);
if (res != child_pid) {
    perror("wait() failed");
    return 1;
}

*Always compile enabling warnings: gcc -Wall -Wextra -pedantic.
Applying the above rules is most of the times all you need to figure out what's the problem. Here's a working version of your program after applying them:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) {
    pid_t child_pid, res;
    int child_status;

    child_pid = fork();
    if (child_pid == -1) {
        perror("fork() failed");
        return 1;
    }

    if(child_pid == 0) {
        sleep(123);
        execl("/bin/ls", "-R", NULL);
        perror("execl() failed");
        exit(1);
    }

    res = wait(&child_status);
    if (res != child_pid) {
        perror("wait() failed");
        return 1;
    }

    if (WIFEXITED(child_status))
        printf("Child exited with status %d.\n", WEXITSTATUS(child_status));
    else if (WIFSIGNALED(child_status))
        printf("Child killed by signal %d.\n", WTERMSIG(child_status));
    else {
        puts("This should never happen! Something's really wrong.");
        return 1;
    }

    return 0;
}


text:
Q: Collect date+hour on every status change Is there a way to write date and hour on a column on every status change in sharepoint?
Example:
STATUS A -> write date+hour on column A
STATUS B -> write date+hour on column B
STATUS C -> write date+hour on column C
Like:
=IF(Status=READY;"DATE+HOUR";"")

I need to record date and hour on every status change.
Regards


text:
Q: jQuery, AJAX and Codeigniter - form submit does not work I'm new to all this AJAX thing so I thought that good learning will be to build simple TODO list. Below is index.php and corresponding controller. Index gets loaded without errors, but when I submit my task nothing is happening. Only page gets reloaded. Database is still empty.
index.php

Todo

<form id="add" >
    <input type="input" name="task" />
    <input type="submit" value="Add" />

</form>

Załadowano w {elapsed_time}

controller/todo.php
<?php
class Todo extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('todo_model');
    }

    public function index($type = NULL)
    {
        $this->load->view('todo/index');
    }

    public function add($data)
    {
        $this->Todo_model->add($this->input->xss_clean($data));
    }
}
?>

Update:
todo_model.php:
  <?php
  class Todo_model extends CI_Model {

      public function __construct()
      {
          parent::__construct();
          $this->load->database();
      }

      public function add($data)
      {
          $this->db->insert('todo', $data);
      }

      public function get()
      {
          return $this->db->get('todo')->result();
      }
  }
  ?>

A: Try using this:
public function add($data)
    {
        $this->Todo_model->add($data);
    }

instead of:
public function add($data)
    {
        $this->Todo_model->add($this->input->xss_clean($data));
    }

UPDATE:
JAVASCRIPT:
$.ajax({
method: 'POST',
url: '<?php echo base_url(); ?>todo/add/',
data: 'data=' + $("input:first").val(),
success: function(resp) {
             //rest processing
         }
});

CONTROLLER:
public function add()
    {
        $this->Todo_model->add($this->input->post('data'));
    }

A: *

*You'll need to use a debugger like Firebug console to see what the reply of the server is to your request.

*In your script section

$(function(){}

is missing, which should be wrapped around your jQuery

*

*use something like this to stop the form from submitting:

if (evt.preventDefault()) {
evt.preventDefault();
}else{
evt.returnValue = false;
}

A: Try this one then debug with firebug by clicking on firebug icon then clicking on Console to see what you submit and how the response is
var id = 1;
$.ajax({
    type: "POST",
    url: "<?php echo base_url(); ?>todo/add/",
    data: {id : id},
    success: function()
    {
        var newP = $('
').text(value);
        $(".todos").append(newP).fadeIn(1000);
    }
});


text:
Q: Costs of canceling repair? After cracking my iPhone, I contacted apple support, started a service request, and filled out the ""Send in for Service" option. However, I am now trying to cancel (which apparently is done by simply not sending the package), but I need to know if there are any costs from a cancelled request.
iPhone 5s, iOS 8.4

A: Contact Apple Support (In USA & Canada its 1-800-MY-APPLE or go to support.apple.com) and let them know that you change your mind. Just make sure ask if you do receive the packaging, did they want you to send it back.

A: Call 1-800-APL-CARE and give them your case number. If you have a specific repair quote and phone number to call, you could try that as well.
Cost depends on if they have done the repair and/or can reverse what they did in my experience.

A: In my experience Apple typically doesn't charge for cancelled repairs or returns however you should check your local area by contacting Apple Support.
You can find your local Apple Support number here.


text:
Q: How do I find out what constraints are on properties of objects in the Facebook Graph API? For example what is the character limit of the 'title' of an Event object. Or what data formats are allowed for the 'place' property of a Checkin. Can't find this is any of the online documentation.

A: You are right that there are a lot of open areas around the Facebook API.  Field limits being one of them.  One reason for the lack of field limits may be to the way Facebook manages their data.  Many of their input fields allow for extremely large inputs, if they are restricted at all.  Although, that obviously does not apply to all fields as you can see by just using their website.  If you max out their limit, you will typically be presented with a very basic error message.
From my own personal testing, I have found that the specific limit for the Event.title is 75 characters.
As for the place property, it is documented in the publishing section of the 'Checkin' object that the place parameter for a checking publish is the ID of the PAGE to which you are performing a checking.  It would be better for them to define the publish parameters in a similar fashion to the read object, but for some reason they did not do so.  As a result it is easy to confuse the two.
For most publishing operations you mostly want to look at the publishing examples at the bottom of the object documentation (Post, Checkin, etc) and then compare them with the descriptions of the read objects presented above.  Sometimes they are the same, but as in the case of Checkin, there can be differences.


text:
Q: jquery attr("href") returning the same values I have two links called "Read More" (bottom of code) that contain different values. When clicked, they call a jquery function that send it to demo_search.php. Problem is, no matter which link I click, I keep getting the same values. If I were to use
var searchString = ($(this).attr("href"))

instead of
var searchString = ($(".more_info").attr("href"))

things work fine. But I cant use (this). How to solve this?
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test Search</title>
<link rel="stylesheet" type="text/css" href="my.css">

<form method="post">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" />

</form>

Search results for

Read More
Read More

A: You have multiple elements with a class of more_info. This means that your selector yields multiple elements. There's no way you're getting the href of two different elements.
The reason the code works when you use this, is because there is only one clicked on element at a time.
Either you need to continue using this, or you need to write a unique selector, like giving the span an id of more_info_1.
Furthermore, your comments dont seem to make any sense. You write:
        // getting the value that user typed
        var searchString    =($(".more_info").attr("href"));
Do you mean to write?
        var search = $(".search_box").val();

A: ($(".more_info") will return you a collection of all elements with this class. Unless you specify a specific position in the array  invoking further functions will always target the first element in this collection.
Compare the change between searchStringA and searchStringB in the fiddle below when you click on the two different "read more".
this of an invoked function is a JavaScript object and therefore it does not have a method .attr() wich belongs to jQuery scope. See searchStringC in the fiddle
So you have to cast this to a jQuery object via $(this) and then you can call
$(this).attr("href")

I stripped down the original code and replaced the  tags with  to make it more click friendly :) You can find the fiddle here.
I highly recommend it running with an open console to observe the error in the line:
var searchStringC    = this.attr("href");


text:
Q: Nash Embedding Theorems for Pseudo-Riemannian Manifolds? Are there analogs of the Nash Embedding Theorems for Pseudo-Riemannian Manifolds?

A: Not clear where you are headed with your concise question,
but if you have any interest in Lorenzian manifolds as instances of pseudo-Riemannian manifolds,
then this might be of interest, especially for the theorem of Campbell:
"The embedding of General Relativity in five dimensions."
Carlos Romero, Reza Tavakol, Roustam Zalaletdinov.
General Relativity and Gravitation.
March 1996, Volume 28, Issue 3, pp 365-376. (Springer link.)

Abstract.
  We argue that General Relativistic solutions can always be locally embedded in Ricci-flat 5-dimensional spaces. This is a direct consequence of a theorem of Campbell (given here for both a timelike and spacelike extra dimension, together with a special case of this theorem) which guarantees that any $n$-dimensional Riemannian manifold can be locally embedded in an $(n+1)$-dimensional Ricci-flat Riemannian manifold. [...]

And there are many papers in some sense following, e.g.: "The embedding of space–times in five dimensions with nondegenerate Ricci tensor,"
F. Dahia and C. Romero, J. Math. Phys. 43, 3097 (2002). (AIP link.)

A: See here:
MR0262980  Reviewed Greene, Robert E. Isometric embeddings of Riemannian and pseudo-Riemannian manifolds. Memoirs of the American Mathematical Society, No. 97 American Mathematical Society, Providence, R.I. 1970 iii+63 pp. (Reviewer: W. F. Pohl)


text:
Q: How do i get all twig templates to inherit from master? NB: i´m using Twig in a non-Symfony context.
I want to register a master layout that all templates should inherit, so that i don´t have to forget to preface them with:
{% extends 'layout.html.twig' %}
I know i have seen this somewhere, and Symfony makes use of it.

A: It is possible!
After some experimenting i came up with this solution:
{# index.html.twig #}
{% block title %}Hello world{% endblock%}

Wrap global layout in a block:
{# layout.html.twig #}
{% block layout %}
    <html>
        <head>
            <title>{% block title %}{% endblock%}</title>
        </head>
    <html>
{% endblock %}

Pass child template to twig:
// index.php
...
$twig->display(array('template'=>'index.html.twig'));
...

Inject child template via a proxy template:
{# proxy.twig #}
{% extends 'layout.html.twig' %}
{% block layout %}
    {# Get extended block #}
    {{ parent() }}
    {# inject template into master layout #}
    {% include template %}
{% endblock %}


text:
Q: Topologist's sine curve When we will spread the topologist's sine curve into components will receive part
$\{(x,\sin \frac{1}{x}:x \in (0,1]\}$
How to argue that part is a borel set?

A: Since $\sin\frac1x$ is a continuous function $\Bbb R\setminus\{0\}\to \Bbb R$, its graph $\Gamma$ is closed in $(\Bbb R\setminus\{0\})\times\Bbb R$. Your set $A$ is precisely $\Gamma \cap ((0,1]\times\Bbb R)$, which is a closed subset of $(\Bbb R\setminus\{0\})\times\Bbb R$. Since $(\Bbb R\setminus\{0\})\times\Bbb R$ is open in $\Bbb R^2$, $A$ is the intersection of an open subset with a closed subsets. Hence Borel.


text:
Q: Return Tuple from EF select How can I retrieve Tuples at Select using EF4?
        var productCount = (from product in context.products
                    select new Tuple<Product, int>(product, products.Orders.Count));

Or
        var productCount = (from product in context.products
                    select Tuple.Create(product, products.Orders.Count));

Entity framework says that cant use not empty constructor for first case, and not recognize Tuple.Create method for second.

A: How about switching to LINQ-to-Objects for the projection:
var productCount = from product in context.products
                select new {Product = product, Count = products.Orders.Count };
var final = from item in productCount.AsEnumerable()
            select Tuple.Create(item.Product, item.Count);

A: Try
 var productCount = from product in context.products
                    select new { product, Count = products.Orders.Count };

This will return an anonymous type which is very close to a tuple
http://msdn.microsoft.com/en-us/library/bb738512.aspx


text:
Q: Spring AMQP Listener Timeout I have a requirement for handling SpringAMQP listener timeout capability i.e We sends a message from producer , The consumer listener thread of Spring AMQP receives the message but say takes lot of time to execute itself and get hanged , Which will eventually lead to Listener thread being rendered unusable.
So is there any way that we have any consumer timeout setting provided by Spring AMQP so that the listener thread is freed again after given timeout time

A: Indeed you can mention the timeout using spring-amqp, here is how.
<bean id="connectionFactory"  class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
    <property name="connectionTimeout"      value="1000" />
    <property name="concurrency"            value="16" /> <!-- in milliseconds -->
    <property name="recoveryInterval"       value="5000" />
</bean>

NOTE: If you are having limited consumer count and using manual ack and not sending the ack signal back for some reason, timeout might occur; it means you are holding the thread and not releasing it which will also impact your performance.
More here

*

*doc

*api

A: If the thread is stuck in your code, there is nothing the container can do to free it up. If it's in interruptible code, you could interrupt the thread.
If it's stuck in uninterruptible code, you are out of luck.


text:
Q: D3.js - building a force directed hierachical tree from csv data So I´m trying to create a hierarchical tree diagram using D3.js. It's supposed to work on top of a QtWebView, and so far, so good: it works. Now I need to tackle the data handling bit of the app. My data is stored in CSV format (not my choice, nor do I have any opinion on that matter) and is described below.
My question is: how to output JSON from this CSV?
I have been looking around for examples for a few days, but I'm stuck. I just wondered if someone could point me in the right direction, since I'm only getting examples on how to produce the tree with data in JSON format and people talking about how to use plugins to output JSON with Qt.
I have no trouble in reading from/writing to the CSV/JSON files. I just really need to know how to make an algorithm that would allow me from this data to output JSON.
This is my example CSV file (node_type and node_size are just for show):

node_id,name,node_size,node_type,parent_node
1,node1,122,4,17
2,node2,127,4,20
3,node3,64,2,5
4,node4,147,5,14
5,node5,146,5,12
6,node6,57,4,10
7,node7,149,1,20
8,node8,141,6,10
9,node9,65,5,10
10,node10,108,2,10
11,node11,97,6,2
12,node12,102,2,5
13,node13,79,6,3
14,node14,90,2,2
15,node15,129,1,8
16,node16,76,1,8
17,node17,68,6,13
18,node18,53,5,7
19,node19,112,6,20
20,node20,147,5,6

EDIT:
I tried Pablo Navarro's tip and produced the following script for D3.js to handle. It's not producing any errors, but nothing is displayed. Can anyone hint on why?
EDIT2: Fixed typo in code.
    var width = 960, height = 500;
    var color = d3.scale.category20();
    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);
    var nodesArray = [], edgesArray = [];

    d3.csv('nodes.csv', function(data) {
        for (var k = 0, n = data.length; k < n; k += 1) {
            nodesArray.push({name: data[k].name, size: data[k].node_size, id: data[k].node_id}),
            edgesArray.push({source: data[k].node_id, target: data[k].parent_node});
        }
    });

    var force = d3.layout.force()
       .nodes(nodesArray)
       .links(edgesArray)
       .size([width, height])
        .start();

    var link = svg.selectAll(".link")
        .data(edgesArray)
        .enter().append("line")
        .attr("class", "link")
    var node = svg.selectAll(".node")
        .data(nodesArray)
        .enter().append("circle")
        .attr("class", "node")
        .attr("r", nodesArray.size)

EDIT3: One small detail that I thinks might be making all the difference: I'm calling this locally, and by locally I don't mean in a "localhost" webserver of sorts, but in a file. From what I read in Jerome Crukier's tutorial:

This will no longer work in a local file system (ie opening a file in the browser). The resulting file can only run on a webserver, which can be local (ie the page has a url).

I'm not sure if this is exactly the case with my code, but once more, if someone has any insight, it will be appreciated.
EDIT 4:
Ok, after some searching online, I sadly have to admit to not knowing how to use Google & Stackoverflow: I found out everything I needed to know here, ironically, explained by mbostock (of D3.js) himself. I now understand that I had no idea on what I was actually looking for, but somehow I found it.
Not really sure what to do now regarding this (still open) question.

A: You can use the csv file. In order to show a tree, you will need to create an array for the nodes and another for the edges:
d3.csv('url.csv', function(data) {

    var nodes = [], edges = [];

    for (var k = 0, n = data.length; k < n; k += 1) {
        nodes.push({name: data[k].name, size: data[k].size, id: data[k].id}),
        edges.push({source: data[k].id, target: data[k].parent});
    }
});

with this structure, you will be able to use the force layout, or convert the nodes, edges arrays to a tree structure.


text:
Q: How to Trigger Error On Windows With Node JS Child Process Exec I am building a cross-platform node utility to read the filesystem (devices, partitions) details, and in my tests I need to test the behaviour when an error is thrown from the shelled commands that the utility runs to obtain its data.
Unfortunately I have very little knowledge of dos or PowerShell and I do not know how to write a batch command that throws an error and exits with an error.
How can I throw an error in batch so that the child process can catch it?
Here's example code for you to fiddle with:
import os from 'os';
import child from 'child_process';
import { expect } from 'chai';

const cmd = os.platform() === 'win32'
   // This command should result in throwing an error to exec
   ? `1>&2 echo 'Echoed Error'\nexit /b 1`
   // This has the expected behaviour on linux and osx
   : `>&2 echo 'Echoed Error'; exit 1`;

expect(child.execSync.bind(child, cmd)).to.throw();
child.exec(cmd, (err) => {
  expect(err).to.be.an.instanceof(Error);
});

A: I found a way to cause an error in the cmd, which is to call a non-existing external or internal command. Hence a command like error or iamnotanexistingcommand will throw an error, which is sufficient for what I am trying to reproduce.


text:
Q: c# search in list for two string in the same line i have a list named simple and all its objects are in the form below:
Tag:  textbook - sacred texts   Rec Id: 10011095
Tag:  advocacy  Rec Id: 10037815
Tag:  advocacy  Rec Id: 10043396
Tag:  advocacy  Rec Id: 10037795
Tag:  advocacy  Rec Id: 10031437
Tag:  advocacy  Rec Id: 10035721
Tag:  advocacy  Rec Id: 10024853

and i have a second list called fullList with objects like:
10055853    What's the Matter with the Internet? by Mark Poster      academic    1       0,083

10055853    What's the Matter with the Internet? by Mark Poster      computers       1       0,083

10055853    What's the Matter with the Internet? by Mark Poster      internet    2       0,167

i split every line of the simpe list in order to get two strings.
The first one has the word(s) after "Tag:" and before "Rec Id:" and the second the numbers after Rec id.
Example: tagGB  = textbook - sacred texts
rec_idGB = 10011095

And then i want to search if there IS'NT any line(object) from list fullList that contains BOTH (in the same line) that two strings.
I tried that:
 foreach (String line in nonZeroList)
        {

            foreach (String line2 in Gblist)
            {

            rec_idGB = line.Split('\t')[0].Substring(4).Trim();
            tagGB = line.Split('\t')[2].Substring(7).Trim();

            if (line.Contains(rec_idGB) == false && line.Contains(tagGB) == false)
            {

            }

        }
    }

but i get a lot of lines that doesnt contain that strings.
I want to get as a resutl only the rec_idGB and tagGB that are not BOTH in the same line of the fullList. Any suggestions?

A:
I want to get as a resutl only the rec_idGB and tagGB that are not BOTH in the same line of the fullList.

So you want all lines in simpleList that can't be matched with any line in fullList? (Or do you want for each line in fullList get all lines in simpleList that doesn't match? I guess not.)
foreach (string line in simpleList)
{
    string rec_idGB = line.Split('\t')[0].Substring(4).Trim();
    string tagGB = line.Split('\t')[2].Substring(7).Trim();
    bool thereIsAMatch = false;
    foreach (string line2 in fullList)
    {
        if (line2.Contains(rec_idGB) && line2.Contains(tagGB))
        {
            thereIsAMatch = true;
            break;
        }
    }
    if(!thereIsAMatch)
    {
        // This is what you want?
    }
}

A: Try mine thread about this:
filtering values from string after/before certain word in c#
The solution was to use regular expressions
Not exactly the same problem, but I think you'll find out the solution easily as I did

A: Shouldn't you be comparing against line2 instead of line?  Your parsing out from line and then checking if it is contained in line which you just parsed it out of.
Eg:
 if (line2.Contains(rec_idGB) == false && line2.Contains(tagGB) == false)

Or it could be the other way around... you want to parse from line2 and compare to line, not really sure.


text:
Q: Missing } inserted error My equation is giving me an error

Missing } inserted. \end{split} error.

I had imported the code from Mathtype.
\begin{equation}
\begin{split}
$$ - {\delta _{max}} \le \delta (k) \le {\delta _{max}}$$ \\
$$ - {{\dot \delta }_{\max }} \le \delta (k + 1) - \delta (k) \le {{\dot \delta }_{\max }}$$ \\
\end{split}
\end{equation}

A:
Note that this answer addresses the original question asked and not the quite different question which replaced it after this answer was posted.

equation already puts you in maths mode, so you don't need to switch into it. Moreover, you don't want to try to fit an unnumbered display environment into split inside equation. Furthermore, $$ ... $$ ought not be used in LaTeX anyway. Use \[ ... \] instead. But not here, of course:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
\begin{split}
 - {\delta _{max}} \le \delta (k) \le {\delta _{max}} \\
 - {{\dot \delta }_{\max }} \le \delta (k + 1) - \delta (k) \le {{\dot \delta }_{\max }} \\
\end{split}
\end{equation}
\end{document}

But did you really want the sequence of variables m, a and x? Or did you mean
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
\begin{split}
 - {\delta _{\max}} \le \delta (k) \le {\delta _{\max}} \\
 - {{\dot \delta }_{\max }} \le \delta (k + 1) - \delta (k) \le {{\dot \delta }_{\max }} \\
\end{split}
\end{equation}
\end{document}

A: I suppose that, for the new version of your equation, you want one of these:
\documentclass{article}
\usepackage{mathtools}
\DeclareMathOperator\obstacle{Obstacle}

\begin{document}

\begin{equation}
  \obstacle(k) = \begin{cases}
  0 & \text{if}\quad  x(k),y(k)  \in   \bigcup _{q = 1}^Q  A(q),    \\[1ex]
  \infty & \text{if}\quad x(k),y(k)  \notin  \bigcup _{q = 1}^Q  A(q) .
  \end{cases}
\end{equation}
\bigskip
\begin{equation}
  \obstacle(k) = \begin{dcases}
  0 & \text{if}\quad  x(k),y(k)  \in \bigcup _{q = 1}^{\smash{Q}}  A(q),   \\[-2ex]
  \infty & \text{otherwise. }
  \end{dcases}
\end{equation}

\end{document}

A:
Note that this answer addresses the form of the posting after some major interim edits were rolled back. I believe the current form of the posting is fairly close to its original form.

You obviously have to remove the utterly inappropriate $$ directives: TeX is already in display math mode after \begin{equation}; there is no sense in having $$ inside an equation environment.
In addition, you should rethink the equations' layout so as to maximize the chances that you readers will immediately "get" what this pair of grouped inequalities is about. In particular, you may want to pursue one of the following two layouts. The first uses a simple array environment and doesn't require loading any special LaTeX packages. The second, which uses a split environment (provided by the amsmath package) is a bit more terse but should be able to convey its content even more efficiently.

\documentclass{article}
\usepackage{amsmath}

\begin{document}
\begin{equation}
\renewcommand\arraystretch{1.3}
\setlength\arraycolsep{0pt}
\begin{array}{r @{{}\le{}} c @{{}\le{}} l}
-\delta_{\max}       & \delta(k)             & \delta_{\max} \\
-\dot{\delta}_{\max} & \delta(k+1)-\delta(k) & \dot{\delta}_{\max}
\end{array}
\end{equation}

\begin{equation}\begin{split}
|\delta(k)| &\le \delta_{\max} \\
|\delta(k+1)-\delta(k)| &\le \dot{\delta}_{\max}
\end{split}\end{equation}
\end{document}


text:
Q: Conditionally show image in a repeater if the database is not null I have a repeater that includes as image. However, there is an image that may not be in all of the Promotions in this repeater

<%# ((Promotion)Container.DataItem).Title %>

<img src="/Uploads/<%# ((Promotion)Container.DataItem).Image %>" alt="" class="promoImg" /><%# ((Promotion)Container.DataItem).Description %>

<%# ((Promotion)Container.DataItem).Restrictions %>

Can someone show me how to make the  only show up if that entry does not have a null field?

A: I prefer do something in server side, so, my sugestion is:
Add a event handler to your repeater
 <asp:Repeater ID="myRpt" runat="server" onitemdatabound="myRpt_ItemDataBound" >
    <ItemTemplate>

                <%# ((Promotion)Container.DataItem).Title %>

                <asp:Image ID="imgTest" CssClass="promoImg" ImageUrl="" runat="server" />
                <%# ((Promotion)Container.DataItem).Description %>

                    <%# ((Promotion)Container.DataItem).Restrictions %>

    </ItemTemplate>
</asp:Repeater>

i will "bind" the image source in code behind, you could do it for other controls too.
So, the code behind is:
protected void myRpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==     ListItemType.AlternatingItem)
        {
            Image imgTest = (Image)e.Item.FindControl("imgTest");
            Promotion pActual = (Promotion)e.Item.DataItem;
            bool needToShowImage = !String.IsNullOrEmpty(pActual.Image)

            if (needToShowImage)
            {
                imgTest.ImageUrl = "Uploads/" + pActual.Image;
            }
            else
            {
                imgTest.Visible = false;
            }
        }
    }

It will do the trick. If it dont work, please, let me know.

A: This should do the trick:
For C#.Net:

<%# ((Promotion)Container.DataItem).Title %>

<img runat="server" visible='<%# Information.IsDBNull(((Promotion)Container.DataItem).Image) %>' src=""/Uploads/<%# ((Promotion)Container.DataItem).Image.ToString %>" alt="no image found" class="promoImg" /><%# ((Promotion)Container.DataItem).Description %>

<%# ((Promotion)Container.DataItem).Restrictions %>

A: I've added some jquery to check each image on the page to make sure there is a image associated with that promotion:
$(document).ready(function () {

$('.promoImg').each(function (index) {

    if ($(this).attr('src') == "/Uploads/") {
        $(this).hide();
    }
});

});
I'm still interested in a server side solution

A: I think you can use panel to do this.

<%# ((Promotion)Container.DataItem).Title %>

<asp:Panel ID="pnlImage" runat="server">

<img src="/Uploads/<%# ((Promotion)Container.DataItem).Image %>" alt="" class="promoImg" /><%# ((Promotion)Container.DataItem).Description %>

</asp:Panel>

<%# ((Promotion)Container.DataItem).Restrictions %>

In ItemDataBound event, do this
 if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
 if (((Promotion)e.Item.DataItem).Image == null) {
    ((Panel)e.Item.FindControl("pnlImage")).Visible = false;
 }

when panel is invisible, it will not be rendered.

A: why not use the
<% if()%>

to judge either there is a image source? if not ,then didn't response.so we can save more


text:
Q: What are "nested attributes" in rails? I'm a newbie in rails.Can anyone tell me what exactly nested attributes are and when to use them, with a good example?

A: I will say check these two railscast

*

*Nested Model Form Part 1

*Nested Model Form Part 2
If you want to read check this


text:
Q: Creating a Person class with Name and Address subclasses? For an assignment I am designing a simple "chatroom" system. It is very rudimentary and simply involves objects of a Person class sending messages to each other through a separate Chatroom object.
Below is my Person class (did not include getter/setter methods for sake of brevity).
public class Person {

protected String firstName;
protected String lastName;
protected String message;

Person(String fn, String ln)
{
    firstName = fn;
    lastName = ln;
}
public void sendMessage(String msg, Person rec)
{
    rec.receiveMessage(msg);
}

public String receiveMessage(String msg)
{
    message = msg;
}

}

these Person objects are instantiated and send messages to each other through the Chatroom class using the sendMessage method.
Now I am supposed to design a larger Person class, into multiple classes by adding Address, Name and Contact classes to the multi class system. The problem is I don't know how to associate these classes with the Person class. At first I tried to make an inheritance relationship with the Name class adding the middleInitial field, but i dont see the utility in this.
public class Name extends Person {

    protected String middleInitial;

    Name(String fn, String ln) {
    super(fn, ln);
}

    public static void main(String args[])
    {

    }

    public String getMI()
    {
        return middleInitial;
    }

    public void setMI(String mi)
    {
        middleInitial = mi;
    }

I don't understand the need for these separate classes, couldn't all this information be stored in the Person object? Can someone help me understand a way to design these classes separately but all be part of the Person object?

A: In this case - yes name should be part of Person. In OOP (Object Oriented Programming) "extends" means "is-a". In your case "Name" is definitely not "is-a" Person. Person should contain name - so "Name" should be a property and not "extend" person.


text:
Q: Go Modules management While I try to build I am getting the following error:
go.mod requires settings-management-service  but vendor/modules.txt does not include it.
run 'go mod tidy; go mod vendor' to sync

I tried running go mod tidy; go mod vendor, but didn't help.

A: First, try deleting your vendor folder, and then running go mod vendor again.
If settings-management-service is a local dependency, check if you are importing it correctly.
The first line of your go.mod file should show the name of your module. Considering the name is app, and settings-management-service is a internal module, it should be imported as :
import "app/settings-management-service"

Do check if all deps are being downloaded correctly, and run go mod download.


text:
Q: Scanning available bluetooth devices for Android in Eclipse I would like to scan available bluetooth deivces and display them in a list. I am newbie to andriod development. I guess that there is some problem with the ArrayAdapter, but not able to figure out the exact problem.
When I run the program, I am getting an exception The application stops unexpectedly. Can you help me in solving this.
     button2.setOnClickListener(new View.OnClickListener()
            {
                @SuppressWarnings("null")
                public void onClick(View v)
                {
                    ListView lv1 = (ListView) findViewById(R.id.myListView1);
                    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    // TODO Auto-generated method stub

                    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                    // If there are paired devices
                    if (pairedDevices.size() > 0)
                    {
                        // Loop through paired devices
                        for (BluetoothDevice device : pairedDevices)
                        {
                            ArrayAdapter<String> mArrayAdapter = null;
                            // Add the name and address to an array adapter to show in a ListView
                            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                            /*final ArrayList<String> btDevices = new ArrayList<String>();
                            ArrayAdapter<String> aa = new ArrayAdapter<String>(CalcActivity.this,
                                    android.R.layout.simple_list_item_1,
                                    btDevices);
*/
                            lv1.setAdapter(mArrayAdapter);
                        }
                    }
                }
            });

I am getting exception at mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Edit:
 Refrained my code but still I am not able to figure out the problem.
Discovering available bluetooth devices in android

A: Make sure you have included the Bluetooth and Bluetooth_Admin permissions in your manifest file.

A: Your mistake I guess so is that the arrayadapter is not yet initialized
so initialize it(assign it a valid reference of arrayadapter a class) like this
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,android.R.id.text1,list_names);

so now use this to populate your list view of bluetooth devices...


text:
Q: connect to a WCF web service using asp.net I'm new to WCF web services never done anything with them before and I'm being asked to create a page to connect to a WCF web service
I have no idea where to start and I've searched the internet with no success.
Does anybody have an example of an asp.net page connecting to a WCF web service?
I've set up the WCF web service on my server but do not have a clue on how to actually connect or query it to get my XML data back.
The WCF web service is set up as it's own URL and only has 2 files within the root one being the web.config.
I somehow need to query this URL and get some XML data back from it.
Any ideas?

A: You need to create a service reference from your asp.net project to your WCF project. Right-click on the ASP.NET and click on "add service reference", set the URL of the service and VS will generate a proxy class for you.
Asking your favorite search engine for "asp.net add service reference" should give you a good selection of starting points.

A: Look into WCF connections and web.config.  This link should provide you some direction:  http://msdn.microsoft.com/en-us/library/bb332338.aspx#msdnwcfhc_topic5


text:
Q: space between Currency and Value How to add a space between Currency and Value LIKE CAD 0.00 instead of CAD0.00 in lightning when 'ui:inputCurrency' is used

A: To override the default currency format make use of  "format" attribute to change as per your need.
Example:
   <ui:inputCurrency aura:id="amount" label="Amount" class="field" value="50" format="CAD #.##"/>


text:
Q: Migrating code from OpenLaszlo 3.3 to 5.0: TypeError #1007 Instantiation attempted on a non-constructor. I ported some parts of the code from OL 3.3 to OL 5.0 recently. I thought that everything will work but when i try to run it using the ant script i have I am getting this error.
 [echo] C:\Program Files\OpenLaszlo Server 5.0.x\Server\lps-5.0.x/WEB-INF/lps/server/bin/lzc.bat
 [exec] Compiling: C:\Workspace\application\client\src\TestClient.lzx to TestClient.swf10.swf
 [exec] compiler output is Loading configuration file C:\Program Files\OpenLaszlo Server 5.0.x\Server\lps-5.0.x\WEB-INF\frameworks\flex-config.xml
 [exec] C:\Documents and Settings\310773\Local Settings\Temp\lzswf9\Workspace\application\client\src\build\TestClient\app.swf (289808 bytes)

So, I took the folder and i compiled it directly in Laszlo. It's not showing any error but when the swf is about to load the main page I am getting this error. Any idea why?
TypeError: Error #1007: Instantiation attempted on a non-constructor.
    at $lzc$class__mvz/$mvx()
    at LzNode/__LZresolveReferences()
    at LzNode/__LZcallInit()
    at LzCanvas/__LZcallInit()
    at LzCanvas/__LZinstantiationDone()
    at LzInstantiatorService/makeSomeViews()
    at LzInstantiatorService/checkQ()
    at Function/http://adobe.com/AS3/2006/builtin::call()
    at LzEvent/sendEvent()
    at LzIdleKernel$/__update()

A: That's the error message you get when you try to instantiate a class which is not defined. Here is an example:
<canvas>

  <class name="myclass">
    <handler name="oninit">
      // Instantiate a class which is not defined
      var x = new lz.missingclass();
    </handler>
  </class>

  <myclass />

</canvas>

Check for missing <includes> of classes which are being instantiated through scripts. You can always check the list of Adoboe Flash Run-Time Errors as well, sometimes there is useful information contained here.
Edit: Solution to problem added
This commment pointed to the problem:

I found that this line is causing the problem. <attribute name="dp"
  value="$once{new lz.Datapointer()}" />. Any idea why?

If you check the OpenLaszlo reference for 5.0, you will see that the class names (on the left side in the class browser) use different case; some classes use camel case (lz.Browser, lz.DataElement), others use all lowercase (lz.view, lz.datapointer). In your case, you should have used lz.datapointer instead of lz.Datapointer.
Therefore this code will compile and run without any problems:
<canvas>

  <class name="my_class" extends="node">
      <attribute name="dp" value="$once{new lz.datapointer()}" />
  </class>

  <my_class oninit="Debug.inspect(this.dp)" />

</canvas>

A good way to test for the correct name of a class is to use the JavaScript in console in DHTML runtime, where you have auto-completion for lz.??? classnames:

Debugging SWF #1007 errors in OpenLaszlo
If you run into a #1007 error in the SWF runtime, I would compile the application for DHTML with the debugger disabled and the JavaScript error console open. Try this:

*

*Change the line of with the $once{} constraint to
<attribute name="dp" value="$once{new lz.Datapointer()}" />

*Compile the app in Chrome using DHTML runtime and debug=false. You should see the following error in the JavaScript console:

*Click on the right side on error-1007.lzx:3, and you'll see the generated JavaScript code with the line causing the error

This line fails:
this.setAttribute("dp",new (lz.Datapointer)())

and you can even reproduce the error by typing new (lz.Datapointer) into the console.

A: Just as a point of info:  The case of class names was "regularized" in 4.0 so that the case of a class that implements a tag is the same as that tag.  See Mapping Class and Tag Names.

A: Here is an example of the problem and a workaround:
1) PROBLEM:
Here is the code of a short OpenLaszlo application demonstrating the problem:
<canvas width="1000" height="584">

  <view name="myContainer" width="500" height="500">

    <handler name="oninit">
      var objCB = new lz.combobox(this);
    </handler>

  </view>

</canvas>

In this example there is no <combobox> tag in the application so the compiler does not think it needs to include the OpenLaszlo <combobox> class code in the application. Hence, when we try to instantiate a combobox with the line "var objCB = new lz.combobox(this);" the compiler throws the following error:

ERROR @test1007error.lzx≈5: TypeError: Error #1007: Instantiation
  attempted on a non-constructor.

2) WORKAROUND:
The solution for the problem is to add an include in your application for <combobox>:
<canvas width="1000" height="584">

  <include href="lz/combobox.lzx" />

  <view name="myContainer" width="500" height="500">

    <handler name="oninit">
      var objCB = new lz.combobox(this);
    </handler>

  </view>

</canvas>

This time the error is not thrown and we see the combobox appear at the top left of the application when we run it.


text: Q: Stripe subscription in android How to integrate stripe subscription in android.we have to use payment intent check out method.but that type not able to subscription.so any one recommend exact way of doing this.


text:
Q: Changing the volume of a simple soundchannel I would like to change the volume of a soundchannel, instead of turning it off/ starting it from the beginning.
Here is a bit of my code dealing with the soundchannel, musicIcon toggles the sound.
    function musicToggle(e:TouchEvent){
    if(musicIcon.alpha != 1){
        Chn_musicLoop = musicLoop.play(0,int.MAX_VALUE);
//Instead of restarting the music, I would like to set the volume to it's max (1)
        musicIcon.alpha *= 2;
    }
    else{
        musicIcon.alpha *= .5;
        Chn_musicLoop.stop();
//Instead of stopping the music, I would like to set the volume to 0.
    }}

What code would I need to do this?

A: I believe you are looking for SoundTransform class.
Basically:
var st:SoundTransform = new SoundTransform(0.5, 0);

Chn_musicLoop.soundTransform = st;

The SoundTransform parameter of 0.5 would put your "volume" at halfway. The parameter is a range from 0 to 1.
Here's a reference in AS3 from adobe:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d1f.html


text:
Q: How do I sort a doubly-linked list in ascending order? I am trying to perform an insertion-sort function on a doubly linked list in the C programming language. When I run the code with this function on a doubly linked list of
1<-->3<-->7<-->4<-->9 I get a sorted output. However, When I run this code on a doubly linked list of 5<-->3<-->7<-->4<-->9 I get a blank output (and yes it still compiles and runs).
I cannot figure out why it is returning a blank output when the first node has greater value than the second. I would guess it has something to do with my if statement?
void insertion_sort_increasing(struct List *list)
{
    struct Node *current_node = list->head; //initialize current_node
    struct Node *tempA;
    struct Node *tempB;
    struct Node *tempC;
    struct Node *tempD;

    if (current_node == NULL) {
        printf("Empty List.");
    } else {
        current_node = current_node->next;
        while (current_node != NULL) { //iterates doubly linked list
            if (current_node->prev->StudentID > current_node->StudentID) {
                tempA = current_node; //(3 in this case)
                tempB = current_node->prev->prev; //(NULL in this case)
                tempC = tempA->next->prev;
                tempD = tempB->next;

                tempA->next->prev = tempA->prev; // 5<--7
                tempB->next->prev = tempC;       // 3<--5
                tempB->next = tempA->prev->next; // NULL-->3
                tempA->prev->next = tempA->next; // 5-->7
                tempA->next = tempD;             // 3-->5
                tempA->prev = tempD->prev;       // NULL<--3
                if (tempB == NULL) {
                    list->head = tempB->next;    // 3 = head
                }
            }
            current_node = current_node->next;
        }
    }
}

A: There are multiple problems in your code:

*

*you perform a single scan through the list, swapping adjacent nodes that are out of order. This loop does not handle the case of a node that should move left by more than one position.

*the code crashes if tempB is null, ie: if the 2 initial nodes of the list should be swapped.

*list->head should be updated if the first node changes.

*the temporary variable names are confusing, esp tempC that is equal to tempA, and the initial order is not tempA -> tempB -> tempC -> tempD.

*for insertion sort, you should move the current node to its position among the nodes sorted so far and skip to the next node until you reach the end of the list.

Here is a modified version:
void insertion_sort_increasing(struct List *list)
{
    struct Node *current_node = list->head;

    while (current_node != NULL) {
        struct Node *next = current_node->next;
        while (current_node->prev && current_node->prev->StudentID > current_node->StudentID) {
            // swap current_node and its predecessor (tempC and tempB)
            struct Node *tempA = current_node->prev->prev;
            struct Node *tempB = current_node->prev;
            struct Node *tempC = current_node;
            struct Node *tempD = current_node->next;

            if (tempA) {
                tempA->next = tempC;
            } else {
                list->head = tempC;
            }
            tempC->prev = tempA;
            tempC->next = tempB;
            tempB->prev = tempC;
            tempB->next = tempD;
            if (tempD) {
                tempD->prev = tempB;
            } else {
                list->tail = tempB;
            }
        }
        current_node = next;
    }
}

A: You need to learn to separate concerns in your code. An insertion sort takes an input list or array and returns an output list or array. So to start with, you need a function that either takes a List** and returns void, or it takes a List* and returns a List*. Logically you need to do three things correctly, 1) iterate over the input list, 2) Remove a node from the input list without breaking 1, 3) insert into the output list at the correct position for the sort order. That amounts to three functions.
List *InsertionSort(List * pList) {...}
List *SortedInsert(List *pList, List *pNode) {...}
List *Remove(List *pNode) {...}

InsertionSort just loops over the it's input, calling Remove, without loosing track of the head or tail pointer, depending on which way you're moving through the list, and then calls SortedInsert with the node it just removed from the head or tail of the pList. SortedInsert then iterates through pList looking for the correct place to insert pNode and then returns the new head of the list, which might just be pNode.
It's just easier to think about one operation at a time, and the code you write will be simpler and easier to understand and debug. In fact, you can test SortedInsert first, to make sure it's working, then test Remove, and then move on to to InsertionSort. You'll need to learn how to use your debugger and make yourself familiar with stepping through your code and checking the state of your variables. A fourth function, PrintList is probably on order here as well.
I am not going to write a bunch of code or be really explicit about the algorithm details, because you can get that with an SO or Google search, and this seems like an obvious homework assignment.


text:
Q: Yahoo Finance - Historical Intraday Download does anybody know why the code below does not bring data after 16:55hr? The market actually closes at 18:00 in Brazil. This happens for all tickers ending in ".SA" in Yahoo Finance.
      import yfinance as yf

      data = yf.download("PETR4.SA", group_by="Ticker", period='1mo', interval='5m',prepost = True)
      data['ticker'] = "PETR4.SA"
      data

Thanks!

A: This is kind of an interesting question. I checked the code. I've been working with several providers, including Yahoo Finance, and I believe it could be more a "pre definition" on the API than a programming/requisition mistake.
As the stock negotiations at B3 normally take place until 17:00 pm (-3 UTC, São Paulo Timezone), the function is returning the last valid computed value i.e. 16:55 pm.
As an exercise I tried to change the time in-between the data from "5m" to "2m" and I spotted the last value at 16:58 pm (same logic).  I don't know how to bypass that.
It appears to be the way it works.


text:
Q: Executing a binary on an App Service Application I want to migrate my PHP web app (which is on Azure Repos) from Azure VM to Azure Web App Service (python, not php though) + Azure SQL + Azure Storage + Azure Redis.
But there was a shell_exec() I was doing in my Azure VM in my PHP app when a specific button was clicked on the portal - now how do I execute this in Azure Web App Service ? This would not be possible since I can only push code to Web App Service by connecting to the Repos - and I don't think I can push an executable to the repo which will get executed on clicking on the button on the UI form ?
So what's the alternative ?
Creating a VM for this purpose alone defeats the purpose of migrating from VM to App Service.


text:
Q: Let $f$ be a continuous function on an interval around $0$ and let $a_i=f(\frac{1}{i})$ (for large enough $i$) Let $f$ be a continuous function on an interval around $0$ and let $a_i=f(\frac{1}{i})$ (for large enough $i$)
i) Suppose $\sum a_i$ converges. Must $f'(0)$ exist?
ii) Suppose $f(0) = f'(0) = 0$. Must $\sum a_i$ converge?
This is question #6 from Spivak Calculus 4th edition. I already showed that, if $\sum a_i$ converges, $f(0) = 0$, and also that, if $f'(0)$ exists and $\sum a_i$ converges, then $f'(0) = 0$, and also that if $f''(0)$ exists and $f'(0) = f(0) = 0$ then $\sum a_i$ converges.

A: Hint for (i): What if $a_n=1/n$ for a sparse subsequence and $0$ otherwise? Easier: If I tell you the answer is "no," can you concoct a function $f$ that'll work?
Hint for (ii): Think about some of the "borderline" series that are close to converging but diverge. (Note by what you've shown that you want to contemplate $f'(0)=0$ but $f''(0)\ne 0$ or non-existent.) The number of derivatives of $f$ that vanish at $0$ dictate how quickly $a_n\to 0$ as $n\to\infty$.

A: Given that you already did 2 all that is left is to do 1. I can construct a function $f(x)$ such that it is not differentiable(let it be piecewise with the same value at 0, but vastly different slope like say -10000) therefore it might not be differentiable.


text:
Q: Can I manually slot an input neuron into a hidden layer in Keras? I have a CNN and I want to sneak in some extra information into one of the final layers.
Here's a simplified version of the code. Watch for the comment
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3,3))
    model.add(Conv2D(32, (3,3))
    model.add(MaxPooling2D((2,2))
    model.add(Conv2D(64, (3,3))
    model.add(Conv2D(64, (3,3))
    model.add(MaxPooling2D((2,2)))
    model.add(Flatten())
    # this next layer is where I want to sneak the neuron(s) in
    model.add(Dense(1024))
    model.add(Dropout(rate=0.4))
    model.add(Dense(168))
    model.compile()
    return model

So I have some additional information about the input image which might be able to help the network. Think of it as a clue which may or may not deserve a reasonable amount of weighting.
The clue is in the form of an integer which technically is in [0, inf) but practically is probably in [0, 20].
So my questions are

*

*What's the appropriate way to represent that hint speaking in terms of NN architecture in general.

*How do I tweak the Keras model to make that happen in practice?

*Bonus: If I wanted to, could I prevent the subsequent dropout from ever dropping out this added feature?

A: This could work by using Keras' functional API:
def define_model():
    inputs = Input(input_shape=(...))
    hints = Input(input_shape=(...))

    x = Conv2D(32, (3,3))(inputs)
    x = Conv2D(32, (3,3))(x)
    x = MaxPooling2D((2,2))(x)
    x = Conv2D(64, (3,3))(x)
    x = Conv2D(64, (3,3))(x)
    x = MaxPooling2D((2,2))(x)
    x = Flatten()(x)

    x = Add()([x, hints])

    x = Dense(1024)(x)
    x = Dropout(rate=0.4)(x)
    outputs = Dense(168)(x)

    model = Model([inputs, hints], outputs)

    model.compile()
    return model

I don't know about protecting it from the dropout using Keras though.


text:
Q: iOS. How to draw complex images on a UIButton? I need to make something like this (rectangles mean various pictures):

I know that it is possible to do this by making one image from two and assigning it to a UIButton. But is there another way to do it by using insets?

A: If you want the "button pressed" highlighted state for both images you could

*

*Make it one image and one button

*Make two buttons and assign images and implement a method (add to both buttons as target for UIControlEventAllEvents) that sets button1.highlighted & button2.highlighted = ((UIButton*)sender).highlighted


text:
Q: javac and java are in wrong encoding and locale I'm on Windows 7. The system locale is zh_CN and there's no way to change the OS's locale. When install java, it detected the system locale and therefore java and javac will, supposedly print its output in localized language (Chinese in this case). I don't want this behaviour but there's no way to change it.
However, it doesn't work. I tried Cygwin, git bash and Win CMD, all print just question marks. See below sample output (from Cygwin):

Anyone has any idea how to make it output English? Any help is much appreciated!

A: I believe you can do this with this command:
java -Duser.language=en -Duser.country=US ...

A: I compared your and my output of javac and saw that in your case the  text is much shorter. So I believe that your javac prints messages in Chinese that is not supported by your terminal. So, you should either teach your terminal Chinese or re-install JDK and choose English as a current interface language (if it is possible) or probably download English version of JDK.
See the following discussion. Try their recommendations how to turn command prompt to be UTF8-compliant.


text:
Q: Passing two arrays in a jQuery .post() , how do I catch this data in PHP and use it there? I'm making a jQuery .post() with the following arrays:
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray

The data inside these arrays:
cleanedPermaLinkArray looks like this: ["2012","10","30","hello-world"]
and cleanedLinkStructureArray like this: ["year","monthnum","day","postname"]
Javascript code:
var ajaxPost = $.post(
            enableAJAX.ajaxurl,
            { action: 'ajaxRequest',
            'ajaxRequestNonce' : enableAJAX.ajaxRequestNonce,
            'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
            'cleanedPermaLinkArray[]': cleanedPermaLinkArray },
            'json'
    );

    ajaxPost.done(function(responseText) {
        alert(responseText);
        console.log(responseText);
    });

    ajaxPost.fail(function() {
        alert("Oops, I'm afraid we've broken something");
    });

I don't understand how I catch the two arrays in PHP? and use the data from the arrays inside PHP? Preferably I would create new PHP array with them, where the values inside cleanedLinkStructureArray become the keys for the array and the values inside cleanedPermaLinkArray the values for that new array.
I guess it must be something with this, but I need someone more experienced to tell me what I need to do here.
$_POST['cleanedPermaLinkArray[]']
$_POST['cleanedLinkStructureArray[]'];

Any help would be appreciated.
Kind regards,
Marnix

A: Your arrays will be in
$_POST['cleanedPermaLinkArray']
$_POST['cleanedLinkStructureArray'];

you can do a simple var_dump($_POST) to see how the data is formed

A: First, in $.post, you do not need the square brackets, so this is one of your params:
'cleanedLinkStructureArray': cleanedLinkStructureArray,

Then in PHP, you have to first catch it like such:
$cleanedLinkStructureArray = $_POST["cleanedLinkStructureArray"];

Now, you can use the following:
foreach ($cleanedLinkStructureArray as $item) {
    // Do something with $item
}

Another way is to pass all your params from $.post to php is setting them as json object.

A: This is all coming down from the server as JSON, right?  Just use json_decode on the values and the'll be converted to arrays, natively inside of php.
$cleanedPermaLinkArray = json_decode($_POST['cleanedPermaLinkArray[]']);
echo cleanedPermaLinkArray[0]; // some value..


text:
Q: How to permanently remove a charm from the juju charms store? I have already added a charm in juju charms store. Now I want to remove from the charms store.  Can anyone explain how to do this?

A: There is a subtle difference between the official Juju Charm Store and charms in the personal name space.
Once a charm has been accepted into the Juju Charm Store by the review process it is maintained by the community and can not be removed from the store.
If however you have a charm in your personal name space (lp:~username/charms/ubuntu-series/charm-name/trunk) you can delete it from Launchpad.
Go to:  https://code.launchpad.net/~username/charms/ubuntu-series/charm-name/trunk
If you own the branch and are logged in, you can delete the branch by clicking on "Delete branch" button.  The next screen will warn you that Branch deletion is permanent. and ask you to confirm.

A: I think this is really answered in Jorge Castro's comment:

The charm store is a community maintained store, indivuduals really can't remove charms from the store.

A: The Charm Store has changed since my original answer over 2 years ago.
Users can not remove charms, but they can revoke permissions on the charm so no one other than the author can see them. To remove permissions from the charm use charm revoke cs:~username/charm-name --acl read everyone
Hope that helps.