text:
Q: Eclipse - Reference file in another Project Edit: My solution at bottom of post.
I have 2 projects that share the same XML/XSD data in eclipse.  I've tried many different things to break the data into a separate project and just reference that instead through various methods, with not much luck.  My goal is so I can click run in eclipse for each project separately and they both load from the same data.
When the project is finally built, there will be 3 jars (the two projects,+ a lib), which will be in the same directory with the xml and xsd folders.  So any file references to the XSD/XMLs are currently in the format like this:
File file = new File("xml/pixtilemaps.xml");

This doesn't work in eclipse, but works during export because of the file structure is sound.  I tried using virtual folders in each of the projects, but it doesn't look like runtime references to relative files use the virtual folders in the way I was expecting.  I've tried adding each as a linked resource, added the project on the build path, etc, but whatever I do, it doesn't seem to treat the xml folder as a relative folder.  I get an error like : file:/F:/workspace/com.myoid.editor/xsd/pixtilemaps.xsd does not exist.  Because it takes it relative to the project. I've also tried to find a run configuration solution to this, but there is obviously something I'm not understanding to get this to work the way I want.
So in summary, have an xsd folder, xml folder in a 3rd eclipse project, that I want 1 and 2 to be able to access through relative file paths like
File file = new File("xml/pixtilemaps.xml");

How I fixed it:
Okay.. so.. maybe there is a better solution but this is what I came up with... In Eclipse under run configurations you can specify the working directory that the launch will run from.  So I put all xml/xsd in for both projects in the same "working directory".  In the run configuration for each project I point the working directory to the 3rd project, and viola, it works like I had expected.

A: Add third project n the build path of first two projects as project reference.
Use ClassLoader.getResourceAsStream in place of File in first two projects as below:
    this.getClass().getClassLoader().getResourceAsStream("/xml/pixtilemaps.xml");

A: Did you try to reference project 3 in project 1 and 2 via project menu -> properties -> java build path -> add project?


text:
Q: Reducer is recieving parameters but is doing nothing ReactJS This is my reducer :
case action.DELETE_COMMENT:
        return {
            ...state ,
            comments : comments.filter((item : any) => item.commentid !== action.id)
        }

It is recieving id correctly but in Redux dev tools I'm getting state is equals which means it is not deleting anything,
Could you guys help me please?
  const deleteComment = (id : Number) => {
    axios.delete(`http://localhost:4000/deleteComment/${id}`,)
        .then((res) => {
            dispatch(actions.deleteComment(id))
        })
        .catch((err) => {
            console.log('--------err', err);
        })
}

Here is how i m passing id :
<ul>
                        {
                            comments.map((items: any) => {
                                return (
                                    <p
                                        key={uuidv4()}
                                    >Comment : {items.comment}
                                    <button onClick={() => {deleteComment(items.commentid)}}>Delete</button>
                                    </p>
                                );
                            })}
                    </ul>

And this part works id is passing correctly
I also checked and my store comments is not empty

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save data from actors on system shutdown For example I have following actors: Player and GameRoom.
GameRoom holds players with scores. When user left(terminates), we save player score in database:
  class Player extends Actor {
        ...
  }

  object GameRoom {
    case object Join
  }

  class GameRoom(database:ActorRef) extends Actor {

    type Score = Int

    var players: Map[ActorRef, Score] = Map.empty

    def receive: Receive = {
      case GameRoom.Join =>
        context.watch(sender())
        players = players + (sender() -> 100)
      case Terminated(player) =>
        players = players - player
        database ! SavePlayerScore(...)
    }

  }

But what if I want to kill jvm process (SIGTERM)? In that case i have no way to save all users score to database on shutdown.
Any hints how to implement needed behaviour?

A: You can install a shutdown hook that will terminate your ActorSystem (using ActorSystem#terminate()) on application shutdown.
That will trigger an ordered termination of the Actors hierarchy, and in turn result in your GameRoom to receive the Terminated for the players.
Here is a small code snippet to install that shutdown hook:
   Runtime.getRuntime.addShutdownHook(
     new Thread("shutdown-hook") {
       override def run() {
         // This obviously needs to
         try{
           Await.ready(actorSystem.terminate(), Duration(2, TimeUnit.MINUTES))
         }catch{
           case _ : InterruptedException => // Termination was interrupted
           case _ : Throwable => // Exception thrown by actor system termination
         }}
     })}

One important thing to notice here is: once the code in the Shutdown Hook is completed, the JVM will shutdown (killing all threads even if they are not done), so if you have any other cleanup to do, add it to the shutdown hook.
EDIT 1: The JVM will terminate even if the Await.ready threw an Exception. This means that, some of your state might have not been saved or something. You might want to handle those exception then and there because, again, once the run() method is complete, the JVM will die.


text:
Q: How do I get hidden HTML to appear only in my popover on click, not elsewhere on the page? I know this may be a weird request, but I am using a popover and I have some HTML in that popover.
However, when my link is clicked it shows both the HTML at the bottom of the page and the HTML in the popover. I just want it to show the HTML in the popover only.
This is my HTML:
Note: This is not a Physical DVD. Downloading & Streaming Only.

    Click here for Details about The Masterclass.

Masterclass Contents

    Test Content!

Test

iTem 1

iTem 2

This is my JS:
   $(document).ready(function(){
    $("#masterclass-popover").popover({
    html : true,
        placement: 'bottom',
    title: function() {
      return $("#masterclass-popover-head").clone();
    },
    content: function() {
      return $("#masterclass-popover-content").clone();
    }
    });

    $("small.download-notice a").click(function(e) {
    e.preventDefault();
    });

  $("#masterclass-popover").click(function() {
    $("div#masterclass-popover-head").toggleClass("hidden");
    $("div#masterclass-popover-content").toggleClass("hidden");
  });
});

Edit 1
If you wanted to refactor my JS, you would get an extra +1 for that - because I know it is likely quite inefficiently written.
Edit 2
I had included the wrong link to a live version. Here is the updated one: http://jsfiddle.net/VB32W/1/

A: $(document).ready(function(){
    $("#masterclass-popover").popover({
        html : true,
        placement: 'bottom',
        title: $("#masterclass-popover-head").text(),
        content: $("#masterclass-popover-content").html(),
    });
});

jsfiddle

A: $(document).ready(function(){
$("#masterclass-popover").popover({

html : true,

placement: 'bottom',

title: $("#masterclass-popover-head").html(),

content: $("#masterclass-popover-content").html()

    });

$("small.download-notice a").click(function(e) {
e.preventDefault();
});

});
Just change your javascript code. the popover function accepts html as its title and content if you set html:true
JS fiddle edited


text:
Q: Multiple day wise plots in timeseries dataframe pandas My data frame look like this -
In [1]: df.head()
Out[1]:
Datetime                     Value
2018-04-21 14:08:30.761     offline
2018-04-21 14:08:40.761     offline
2018-04-21 14:08:50.761     offline
2018-04-21 14:09:00.761     offline
2018-04-21 14:09:10.761     offline

I have data for 2 weeks. I want to plot Value against time (hours:minutes) for each day in week. If I am to see data one week at a time that also works.
I took a slice for a single day created a plot using plotly.
 In[9]: df['numval'] = df.Value.apply(lambda x: 1 if x == 'online' else -1)
 In[10]: df.iplot()

If can have mutiple plots similar to this for sunday to saturday using few lines it would speed up my work

Suggestions -
Something like I can put in arguments as weekday (0-6), time (x axis) and Value (y axis) and it would create 7 plots.
In[11]: df['weekday'] = df.index.weekday
In[12]: df['weekdayname'] = df.index.weekday_name
In[13]: df['time'] = df.index.time

Any library would work as I just want to see the data and will need to test out modifications to data.
Optional - Distribution curve, similar to KDE, over data would be nice

A: This may not be the exact answer you are looking for. Just giving an approach which could be helpful.
The approach here is to group the data based on date and then generate a plot for each group. For this you need to split the DateTime column into two columns - date and time. Code below will do that:
datetime_series = df['Datetime']
date_series = pd.Series()
time_series = pd.Series()

for datetime_string in datetime_series:
    date,time = datetime_string.split(" ")
    date_s = pd.Series(date,dtype=str)
    time_s = pd.Series(time, dtype=str)
    date_series=date_series.append(date_s, ignore_index=True)
    time_series = time_series.append(time_s, ignore_index=True)

Code above will give you two separate pandas series. One for date and the other one for time. Now you can add the two columns to your dataframe
df['date'] = date_series
df['time'] = time_series

Now you can use groupby functionality to group the data based on date and plot data for each group. Something like this:
First replace 'offline' with value 0:
df1 = df.replace(to_replace='offline',value=0)

Now group the data based on date and plot:
for title, group in df1.groupby('date'):
    group.plot(x='time', y='Value', title=title)


text:
Q: Add a border to subtotals with excel vba I have created a macro that applies subtotals to a worksheet. This is all fine, but I haven't been able to add a border to go right across the subtotal row. Using conditional formatting I have been able to highlight the cell row contains the subtotal function.
Is it possible to add a border and colour the background row for each subtotal row in VBA?

A: Use the .Find method to look for whatever function you subtotaled.  For example, if you used COUNT, then look for the word "count".  If you used SUM, then look for the word "total".  Then using the .offset method for the number of cells to the actual total, and use the borders property to add the border.  Example,
With Worksheet.Range(c.address).Offset(0,2).Borders(xlEdgeTop)
.Weight=xlMedium
.Color=RGB(255,0,0)

A: Sure. For borders use the Border properties.
Example:
With Rows(1).Borders(xlEdgeTop) 'Applies border settings to first row
     .LineStyle = xlContinuous
     .Weight = xlThin
     .ColorIndex = xlAutomatic
End With

For background color, easiest I think is to use the ColorIndex property like this:
 Rows(1).Interior.ColorIndex = 3 'Red background on first row


text:
Q: Custom chessboard axis labels I would like to use the chessboard package to create a chess board, but with customized axis labels. The Latex below creates a board where the files are labelled with numbers instead of letters. I would like to label the files and ranks in non-sequential orders, for example "a, b, c, d, d, c, b, a", or "5, 4, 3, 2, 1, 1, 2, 3, 4, 5" on a 10x10 board.
\documentclass{article}
\usepackage{chessboard}

\begin{document}

\begin{frame}
\newgame
\chessboard[
    setfen=rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2,
    labelbottomformat=\arabic{filelabel}
]
\end{frame}

\end{document}

Some past questions have other labels, or sequences starting with 0, but all make use of sequential numbering. Page 37 of the chessboard documentation is promising but I haven't been able to get further.

A: \documentclass{article}
\usepackage{xskak,chessboard}

\newcommand\myfancynumbering[1]{%
 \ifcase#1 \or blub\or xxx\or a\or b\or 123\or c\or abc\or Bär\fi}
\begin{document}

\begin{frame}
\newchessgame
\chessboard[
    setfen=rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2,
    labelbottomformat=\myfancynumbering{\value{filelabel}}
]
\end{frame}

\end{document}


text:
Q: How to change character encoding on XMLHttpRequest upon sending FormData Object I need to change my character encoding to EUC-JP

Here is my code:

formData.append("send", "送信");
var xhr = new XMLHttpRequest();
xhr.open("POST", "foo.php", false);
xhr.setRequestHeader("Content-type", "text/html; charset=euc-jp");
xhr.send(formData);

I've just learned that:

Content-Type cannot be set upon sending FormData() object.

and

the default encoding is UTF-8

Because of UTF-8 encoding, I cannot receive the correct japanese characters on foo.php.


text:
Q: Need to have HashMap add(sum) multiple values within a key I am attempting to have a single button process multiple inputs in the same input boxes. I have 16 input boxes, each with its own id# (YfProduct) which I am using as the key for my hashmap. For the input value, I have Weight. A user will enter in whatever double weight they want, in however many input boxes they wish, and click a button (an a4j:commandButton) which activates the method below.
private HashMap<Integer, Double> storeWeight = new HashMap<Integer, Double>();

public void storeWeight(Yieldfl yieldfl){
    for (YieldItem row : yielditem) {
    storeWeight.put(row.getYfProduct(), row.getWeight());
    System.out.print(storeWeigt)}
}

Right now this code will set the appropriate values with the right key, and replace those values with new input entered and another button click. However what I am trying to do is have the bean save the previous values, and sum up the next values entered with the previous entry(s) that have the same key. So at the end of the user's input, the HashMap will contain 16 keys with the sum of the individual values added up for each key.  I havn't been able to come up with a way to do this without some serious hardcoding. Help much appreciated.

A: So this actually turned out to be a simple fix, I'll put the solution on here just incase somebody runs into a similar problem. It's my first time working with a HashMap so I had a colleague help me out. I needed the value to call the key.
storeWeight.put(row.getYfProduct(), storeWeight.get(row.getYfProduct() + (row.getWeight()));

and to avoid null-pointers:
public void storeWeight(Yieldfl yieldfl){
    for (YieldItem row : yielditem) {
        Double oldValue = storeWeight.get(row.getYfProduct());
        if (oldValue == null)
            oldValue = 0.0;
    storeWeight.put(row.getYfProduct(), oldValue + (row.getWeight()));
    row.setWeight(0.0);
    System.out.print(storeWeight);}
}


text:
Q: Get all items for a given set of hashkeys What is the efficient way of getting all items for a given set of hashkeys from a single table? Table has both hashkey and rangekey.
To retrieve a single item I am using
items = tbl.items.query(
                    :hash_value => "HashKey1",
                    :select => :all).select.map {|i| i.attributes}

One way to retrieve all item is to loop through keys which is a terrible solution
hashkeys = %w(abcd efgh xyz)
hashkeys.each do |key|
     items[dn] = tbl.items.query(
                    :hash_value => key,
                    :select => :all).select.map {|i| i.attributes}
end

I am using ruby client for Amazon DynamoDB.

A: I did not use ruby client but in comparison with php client you could use an array as hashkey value like:
hashkeys = %w(abcd efgh xyz)
items = tbl.items.query(
    :hash_value => hashkeys,
    :select => :all).select.map {|i| i.attributes}


text:
Q: Add User to default User Group I want to create a user and add it to the standard user group.
How can I do this?
Code:
$button_BenutzerErstellen_OnClick = {
    $textBox6.Text
    # Define password variable as SecureString
    $password = ConvertTo-SecureString $textBox7.Text -AsPlainText -Force

    # Check for empty Textboxes
    if (($handler_textBox6.Text -eq 0) -or ($handler_textBox7.TextLength -eq 0)) {
        [System.Windows.Forms.MessageBox]::Show("Bitte füllen Sie alle Kriterien aus.", "Combat 19")
    } else {
        # create user
        New-LocalUser $textBox6.Text -Password $password -Description $textBox1
        [System.Windows.Forms.MessageBox]::Show("Benutzer wurde erstellt!", "Combat 19")
    }
}

A: I am not sure how creation of user is linked with the script you have highlighted.
I believe you are talking about local users and groups.
Then you can use:
For USers
NET USER username "password" /ADD

For Adding it to Group
NET LOCALGROUP "group" "user" /add


text:
Q: Is there a specific name for arithmetic and operations on Probability Density Functions It is possible to add (independent) Probability Density Functions (resulting in convolution if I'm not mistaken), or to multiply, divide these… i.e. to perform arithmetic on pdf…
But has this specific type of calculation (this "category" ?) a specific name ? Is it just "arithmetic on Probability Density Functions" ?

A: The pdf's correspond to random variables; the usual terminology is that you're doing arithmetic on those random variables. In the example you mention, if you have rv's $X$ and $Y$, the convolution of their pdf's is the pdf of $X+Y$, so $X$ and $Y$ are what you're really adding.

A: It is called Stochastic Optimization
So long after having asked that question!


text:
Q: Bit twiddling to get sign bit of 32 bit int I would like to convert
(n < 0 ? 1 : 0)

into bit twiddling (assuming 2s complement arch).
for performance reasons.

A: With an unsigned shift,
x = n >>> 31; // Java's unsigned shift

x = (int)((uint)n >> 31); // C#'s unsigned shift, the casts are effectively nop

GCC does this automatically, other compilers may also. Or not. Your mileage may vary.


text:
Q: LINQ (Unable to cast object of type 'System.Double' to type 'System.String'.) I am facing a problem while using LINQ concept.
below i am comparing two datatables one is filled by database another is by excel file.
Problem is when I am apply join between two "tempdt" contains double value which promoting an error of casting object.
I can't change return type from string to double cause it could be any data type in future as currently it is double it might be alpha numeric in future.
    var commonRows = from r1 in dt.AsEnumerable()
                             join r2 in tempdt.AsEnumerable()
                             on r1.Field<string>(0) equals r2.Field<string>(4)
                             select r2;
            if (commonRows.Any())
            {
                abcdefgh = commonRows.Count();
                dt123 = commonRows.CopyToDataTable();
                // ring the ghanta of gutlu
            }

Exception: Unable to cast object of type 'System.Double' to type
  'System.String'.

A: Here is where I think your problem is:
from r1 in dt.AsEnumerable()
join r2 in tempdt.AsEnumerable() on
r1.Field<string>(0)  //<-- this may not be string
equals
r2.Field<string>(4) //<-- this may not be string
select r2;

What you could  do is to treat it as object:
from r1 in dt.AsEnumerable()
join r2 in tempdt.AsEnumerable() on
(string.Empty + r1.Field<object>(0)) <-- Edited by Andreas X
equals
(string.Empty + r2.Field<object>(4)) <-- Edited by Andreas X
select r2;

What you should do, is to make sure your index numbers (0 and 4) points to the same type.
Edit: I usually use the old ASP-trick to aboid null pointers when asking to the tostring value.

A: Casting to string isn't really possible, since double and string are 2 completely unrelated classes. perhaps try comparing their .ToString() values. Or if you want to be completely safe, compare their string formats, so you don't get any NullReferenceExceptions: string.Format("{0}", fieldvalue)

A: below code is working for me.
thanks every one
    var commonRows = from r1 in dt.AsEnumerable()
                             join r2 in tempdt.AsEnumerable()
                             //on r1.Field<object>(0).ToString() equals r2.Field<object>(4).ToString()
                             on r1[0].ToString() equals r2[4].ToString()
                             select r2;
            if (commonRows.Any())
            {
                abcdefgh = commonRows.Count();
                dt123 = commonRows.CopyToDataTable();
                // ring the ghanta of gutlu
            }

A: Field expects the underlying datatype to be a string.
see: http://msdn.microsoft.com/en-us/library/bb301394.aspx
InvalidCastException
The value type of the underlying column could not be cast to the type specified by the generic parameter, T.
You could use object to ignore the type as Jens Kloster purposed.
However, there is something wrong with your design if you don't know the datagtype of your columns.

A: This error is caused by a mismatch datatypes between properties' entity and underlying table columns.


text:
Q: An MST-like problem with vertex selection Consider a planar pointset in a rectangle, where every point has a color (an integer label).
We need to select one point of every color, so as to minimize the cost of a planar MST of selected points (in my application, the distances are Manhattan/$L_1$).
For example, given the locations of US cities, we would find an MST that connects to one city from every state.
If helpful, we could additionally assume that the local density of the pointset is upper-bounded (the points can't be clustered too closely). Points of the same color will generally come in groups (can even assume that each color corresponds to a connected region).
A straightforward heuristic would average locations of points of each color, build an MST for those "centers", and then look for shortcuts. Is there something better ?
Points of interest: a proof of NP-hardness, an approximation algorithm, an effective heuristic


text:
Q: cross-thread calls? This is mt first time trying to write a not web based program, and my first time writing anything in C#.
I need a program that monitors folders, but I can't get it to work.
I have used the example from this post Using FileSystemWatcher with multiple files but is trying to make it a form.
My current problem comes in the ProcessQueue function where fileList apparently is defined in another thread.
Whenever a file is actually submitted to the watched folder I get an error that using fileList is a cross thread call
Can anyone explain this error to me, and how to fix it?
namespace matasWatch
{
    public partial class Form1 : Form
    {
        private int n = 1;
        private bool isWatching = false;
        private List<string> filePaths;
        private System.Timers.Timer processTimer;
        private string watchedPath;
        private FileSystemWatcher watcher;

        public Form1()
        {
            filePaths = new List<string>();
            watchedPath = "C:\\Users\\username\\Desktop\\test";
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!isWatching)
            {
                button1.Text = "Stop";
                isWatching = true;
                watcher = new FileSystemWatcher();
                watcher.Filter = "*.*";
                watcher.Created += Watcher_FileCreated;
                watcher.Error += Watcher_Error;
                watcher.Path = watchedPath;
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents = true;
            }
            else {
                button1.Text = "Watch";
                isWatching = false;

                watcher.EnableRaisingEvents = false;
                watcher.Dispose();
                watcher = null;
            }
        }

        private void Watcher_Error(object sender, ErrorEventArgs e)
        {
            // Watcher crashed. Re-init.
            isWatching = false;
            button1_Click(sender, e);
        }

        private void Watcher_FileCreated(object sender, FileSystemEventArgs e)
        {
            filePaths.Add(e.FullPath);

            if (processTimer == null)
            {
                // First file, start timer.
                processTimer = new System.Timers.Timer(2000);
                processTimer.Elapsed += ProcessQueue;
                processTimer.Start();
            }
            else{
                // Subsequent file, reset timer.
                processTimer.Stop();
                processTimer.Start();
            }
        }

        private void ProcessQueue(object sender, ElapsedEventArgs args)
        {
            try
            {
                fileList.BeginUpdate();
                foreach (string filePath in filePaths)
                {
                    fileList.Items.Add("Blaa");
                }
                fileList.EndUpdate();
                filePaths.Clear();
            }
            finally
            {
                if (processTimer != null)
                {
                    processTimer.Stop();
                    processTimer.Dispose();
                    processTimer = null;
                }
            }
        }
    }
}

A: I assume that fileList is a windows forms control. The ProcessQueue method is called from a timer thread which is by default a background thread. The fileList control resides in the UI thread. You need to use the Invoke() method of the form passing it in a delegate the updates the fileList control.
    Invoke(new Action(() =>
    {
        fileList.BeginUpdate();
        foreach (string filePath in filePaths)
        {
            fileList.Items.Add("Blaa");
        }
        fileList.EndUpdate();
        filePaths.Clear();
    }));

A: Try using System.Windows.Forms.Timer instead of System.Timers.Timer so the timer tick event is executed on the UI thread.
See here for more details.


text:
Q: sbt plugin dependency not resolved from nexus - Server access Error: Connection timed out I have a Play Framework project (v2.5.3) using sbt v0.13.11. I have installed the latest version of sbt 1.1.0 (do I need to install an older version?). I have also installed the latest version of Intellij 2017.3. We are using a corporate nexus server to resolve sbt dependencies.
My repositories file is set up like so:
[repositories]
local
my-ivy-proxy-releases:http://nexus.xxx.com:8081/nexus/repository/ivy-releases/[organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]
my-maven-proxy-releases:http://nexus.xxx.com:8081/nexus/repository/mvn-repositories/

I have set an environment variable:
SBT_OPTS = -Dsbt.override.build.repos = true

When I load the project in Intellij the sbt refresh gets stuck resolving dependencies from the sbt-uglify plugin. I know it is sbt-uglify because I commented out all the plugins to figure out which one is the issue.
plugins.sbt:
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.9")
addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-gzip" % "1.0.2")
addSbtPlugin("com.typesafe.sbt" % "sbt-uglify" % "2.0.0")

Here are the errors/warnings I get in Intellij:
[info] Resolving org.webjars.npm#right-align;[0.1.1,0.2) ...
[error] Server access Error: Connection timed out: connect
url=https://repo.typesafe.com/typesafe/ivy-releases/org.webjars.npm/right-align/
[error] Server access Error: Connection timed out: connect
url=https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/org.webjars.npm/right-align/
[error] Server access Error: Connection timed out: connect
url=https://repo1.maven.org/maven2/org/webjars/npm/right-align/maven-metadata.xml
[error] Server access Error: Connection timed out: connect
url=https://repo1.maven.org/maven2/org/webjars/npm/right-align/
[warn] problem while listing resources in http://nexus.xxx.com:8081/nexus/repository/ivy-releases/org.webjars.npm/right-align/ with my-ivy-proxy-releases:
[warn]   java.lang.NullPointerException charsetName

It takes about an hour to fully resolve everything because it will try to resolve dependencies for about 10 different org.webjars.npm libraries and try 4 different urls timing out each time. Note that the project does not fail to compile. It eventually pulls the libraries from our nexus but only after timing out the other urls. If I sbt clean compile on the command prompt I still get the warnings but it takes less time to resolve (maybe a few minutes).
Installing node.js (the compiler was complaining it couldn't find a js engine) temporarily resolved the issue until there is a change in build.sbt and it has to refresh the project.
Questions are as follows:
1. Why does it take much longer to resolve in Intellij vs command prompt?
2. Why is sbt not hitting the nexus repository first?
3. Is it possible to get rid of the errors/warnings or at least reduce the timeout?


text:
Q: Creating a favourites page I currently have a 3 tables setup in PHPMYADMIN
Customer(CUSTOMER_ID,........)
Product(PRODUCTID, ProductName..............)
Favourite(PRODUCTID, CUSTOMER_ID)
The Products page currently displays all items stored in the database like:
echo '
';
        echo '
Name	Category	Description	Price	Image	Favourite	';
        while($row=mysqli_fetch_assoc($result)){
            echo '
'.$row['ProductName'].'	'.$row['Category'].'	'.$row['ProductDescription'].'	'.$row['ProductPrice'].'		FAVOURITE	';
        }
        echo '
';

This all displays correctly. What I need is when the user clicks the favourite button it adds their ID and the ProductID to the database so that when they go to the favourite.php page it displays all their favourited items which an option to remove the favourited item.
The problem I am having is getting the query to run. Here is what  I currently have.
<?php

include 'connection.php';
session_start();

$customerID = $_SESSION['cust'];
$product = $row['ProductName'];

//echo $customerID;
//echo $product;

$query="SELECT ProductID FROM Products WHERE ProductName = '$product'";

$result=mysqli_query($connection, $query);

echo $row['ProductID'];

//echo $_SESSION['cust'];

//$query="INSERT INTO favourites (CUSTOMER_ID, ProductID) VALUES ('$_SESSION['cust']', '$_SESSION['cust']' )";

$result=mysqli_query($connection, $query);

Any help is highly appreciated. Thanks.


text:
Q: Why can't current flow in a conductor with a potential/emf on one end and earth on the other? Is there a mathematical expression? Let's say I have a wire with one end connected to earth and the other end floating. Now let's induce a voltage/EMF of X volts into the wire. Considering the ground to be zero potential, why doesn't any current flow from wire to ground?
I have heard the answer "current flows in a closed loop and the airgap makes the resistance infinite in this specific scenario", and then my question would be: why does current only flow in a closed loop? Is there a mathematical representation/symbolic equation that shows this electrical property?
This question arose from this problem (to provide more context) "There is a pole/fence parallel to a 3 phase power line with some impedance and one of its side connected to ground. We were asked to find out the voltage in the pole." To find the above we had to consider the current flowing through the pole as zero and calculate the voltage effect from the mutual impedance. This is confusing to me because there is an emf due to the power line in this case which is what is being calculated and clearly there is a path to ground and why isn't there a current flow there.

A:
Let's say I have a wire with one end connected to earth and the other end floating.

If one end is earthed, then the other end is not 'floating', but also connected to earth by the wire. Perhaps instead of floating, you meant 'available to make a connection to'. That would be called a terminal.

Now let's induce a voltage/emf of X volts into the wire.

You can't, the wire is connected to earth. But if the wire has a finite resistance, then the terminal is earthed through a resistance, which means you can put a voltage onto it.
In order to put a voltage onto the terminal, you would have to connect it two a source of voltage. Voltage is always measured between two points. As you have specified a single voltage, that voltage is by definition with respect to ground. You therefore need to connect a voltage source, like a battery or power supply, between ground and the terminal.

Considering the ground to be zero potential

That's what we mean by ground

why doesn't any current flow from wire to ground?

Current flows along the wire, from the terminal, to ground. It continues to flow through the power supply back up to the terminal in a loop.

A:
why does current only flow in a closed loop? Is there a mathematical representation/symbolic equation that shows this electrical property?

The full answer is "Maxwell's equations", but that isn't particularly intuitive or easy to understand. The simpler answer for most circuit analysis is "Kirchoff's Current Law".
However, it's also important to recognize that "can only flow in a closed loop" is only always true for DC analysis. Let's have a look at a simple AM radio receiver:

Image source: circuitdiagram.org - Simple AM Receiver
What's that on the left? That looks like a wire open at one end and connected to ground at the other. And from a DC point of view it is: if you try to apply a DC current to the free end of the antenna, it will remain near 0V.
However, radio waves will induce an AC current in the antenna, which drives the resonant LC (coil and capacitor) circuit on the left, which is tuned to receive the desired radio signal.

A: Current flows from Voltage source to Ground as there is some resistance in the wire which is connected to Ground. Kirchhoff's laws explain how the current flows. Kirchhoff's laws are based on law of conversation of charge and law of conservation of energy. You can perhaps verify it mathematically.

A: Current doesn't only flow in a closed loop.  "Current" is the motion of charged particles.  The force that moves the charge comes from an electric field.  In electric circuits, we can say current flows in a loop because we provide a conductive path for the electric field to follow.
Your specific example of a power line next to a fence cannot possibly be answered without a vast amount of information - both geometric and parametric info about the fence, power lines, and surrounding soil - and a lot of processing power to simulate the transient electromagnetic effects.
We have formulaic estimations (more like guess-amations) that can give us ball park figures in every day practice.
To answer your first question, "inducing an emf" doesn't mean much when your question is this particular.  What kind of emf?  An emf from a battery?  Attached to what part of the wire?  Is it an emf from a neighboring alternating current?  What direction is the e-field that has been induced?  ... the point that I'm making is that your question straddles the fence between electrical engineering and electrodynamics.  Electrical engineers typically don't have a low-level understanding of the physics and resort to a high-level understanding of circuitry which often leads to incorrect conclusions.
There's too much to discuss and explain.  The answer is with maxwell's equations, which are the low-level building blocks of electrical engineering.


text:
Q: Recreating Arraylist class I'm working on recreating the ArrayList class. I have a problem with the add method. I want my add method to return the new table and to affect it to my element. But when I want to get into the element of my table element it's always null.
And another question..I wanna Create the constructor that takes objects as the elements of the Arraylist like ArrayListBis(1,2,3)..what's gonna be the parameter of the contractor is it ArrayListBis(Object... args) ?
public class ArrayListBis  {

final static int DEFAULTSIZE=50;
private int indexCourant,dernierElement,size;
private Object [] elements;

public ArrayListBis(int size){
    elements=creatList(size);
    indexCourant=0;
    dernierElement=size-1;
    this.size=size;
}

public void add(Object o){
    add(o,size());
}

public void add(Object o, int index){
    Object[] temp;
    if(index <0 || index > size())
        throw new IndexOutOfBoundsException();
    else{
            temp=creatList(size()+1);
            for(int i=0;i!=size()+1;i++){
                if(i<index)
                    temp[i]=elements[i];
                else if(i==index)
                    temp[i]=elements[index];
                else
                    temp[i]=elements[i+1];
            }
        this.size++;
            elements=temp;
    }
}

A: There a couple issues with your add method. First, you do not need to recreate your list every time a new element is added. The reason is that your list will not start out full, hence this line
add(o,size());

should only be done on the condition that this.size == elements.length. However, I believe you should use size or some variable to reflect the actual count of how many elements were inserted so far into your arraylist. So in your constructor, I would set this.size = 0 instead since it starts out with zero elements. Now in your original add method, only create a new array if you're adding to an array that's full. And like others have said, you weren't adding the new element to begin with. So with those changes it should now look like this,
public void add(Object o, int index){
    Object[] temp;
    if(index >= 0 && index < elements.length)
        temp[index] = o;
        size++;
    else{
        temp=creatList(elements.length * 2);
        for(int i=0;i < elements.length;i++){
            if(i<index)
                temp[i]=elements[i];
            else if(i==index)
                temp[i]=o;
            else
                temp[i]=elements[i+1];
        }
        temp[index] = 0;
        size++;
        this.elements = temp;
    }
}

Only other thing I changed was how much the new list's size should be. I changed it to be double the original array's size because you don't want to make a new array of a size that's only one more bigger than the original because making new arrays and copying all the elements from the old one to the new one is a costly operation that shouldn't be done too often.


text:
Q: Only allow numbers 0-168 including decimals up to two places This is what I have so far:
/^(1[0-6][0-8]|1[0-5][0-9]|1[01][0-9]|[1-9]?[0-9])$/

This regex only allows the numbers 0-168 but does not allow any decimal places i.e. 1.5 or 12.56 or 167.99.

A: ^(?:\d\d?|1[0-5]\d|16[0-7])(?:\.\d\d?)?$

This matches numbers from 0 to 168, excluding 168 itself.
If you want to add it, just
|^168(?:\.00?)?$


text:
Q: Javascript onClick() doesn't work for my button to calculate form inputs? I want to take input values from HTML input and then I want to show the value by clicking result button.
Here is my code:
HTML:
<form class="form-inline">

                Purchase Price

                    <input type="text" id="purchase-price">

            <button class="mortgage-button" id="mortgage-calculate" onClick="result()">CALCULATE</button>

</form>

JavaScript:
    var paid_in_percent;
function setValue(){
    paid_in_percent = document.getElementById("#purchase-price").value;

}
function result(){
    setValue();
    alert(paid_in_percent);
}

Actually what I want:
I want to take inputs from HTML input, then I want to calculate those results and finally clicking the result/calculate button I want to reveal the calculation.
Here is the jsfiddle

A: Corrected your code
HTML
<form class="form-inline">

                    Purchase Price

                        <input type="text" id="purchase-price">

                    Down Payment

                    <input type="text" id="down-payment">

                    Mortgage Term

                    <input type="text" id="mortgage-term">

                    Interest Rate

                    <input type="text" id="interest-rate">

                    Property Tax

                    <input type="text" id="property-tax">

                    P.Insurance

                    <input type="text" id="p-insurance">

                <input class="mortgage-button" type="button" value="CALCULATE" id="mortgage-calculate" onClick="result()"/>

</form>

JavaScript
var paid_in_percent;
function setValue(){
    paid_in_percent = document.getElementById("purchase-price").value;

}
function result(){
    setValue();
    alert(paid_in_percent);
}

JSFIDDLE Here

Changes :  1] Removed # from getElementById function. 2] Changed
  button element to input tag with type button. This prevents form
  submission when clicked on it.


text:
Q: How can I synchronize my all accounts? For example, I updated my Stack Overflow profile, and I want to apply that profile to all my network profiles. How can I do that?

A: If you look at the bottom of the page at, for example, https://meta.stackoverflow.com/users/164923/monstermmorpg?tab=accounts, you will notice the following three buttons:

The first one is the one you are looking for. All of those buttons are listed in your user account, in all the SE sites where you have an account. Just go to the SE with the account containing the data you want copied in the other accounts, and you will be all set up.

A: This will probably be covered somewhere already, but...

*

*go to your profile view and select  the 'accounts' tab,

*scroll to the very bottom of the page,

*select the first option 'Copy Stack Overflow profile to all Stack Exchange accounts'.


text:
Q: Test written for mouse events failing code coverage I am writing a jasmine test in angular for code coverage. The test is to cover the click events of component. The test individually pass but the code coverage complains that the function is not covered.Could somebody tell me what am i missing.The tests that i an referring to here are onOverlayClicked and onDialogClicked
Component
export class DialogComponent implements AfterViewInit, OnDestroy {
  private readonly _onClose = new Subject<any>();

  public componentRef: ComponentRef<any>;
  public childComponentType: Type<any>;
  public onClose = this._onClose.asObservable();

  // add this:
  @ViewChild(InsertionDirective, { static: false })
  insertionPoint: InsertionDirective;

  constructor(public componentFactoryResolver: ComponentFactoryResolver,
              public cd: ChangeDetectorRef,
              public dialog: DialogRef) {
  }

  ngAfterViewInit() {
    this.loadChildComponent(this.childComponentType);
    this.cd.detectChanges();
  }

  ngOnDestroy() {
    if (this.componentRef) {
      this.componentRef.destroy();
    }
  }

  onOverlayClicked(evt: MouseEvent) {
    // close the dialog
  }

  onDialogClicked(evt: MouseEvent) {
    evt.stopPropagation();
  }

  loadChildComponent(componentType: Type<any>) {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.viewContainerRef;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
  }

  closeModal() {
    this.dialog.close();
  }
}

Test component
describe('DialogComponent', () => {
  let component: DialogComponent;
  let fixture: ComponentFixture<DialogComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [SharedModule, DialogModule], // DialogModule
      providers: [DialogConfig, DialogRef ]
    })
    .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [DialogComponent, ExampleComponent] } })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DialogComponent);
    component = fixture.componentInstance;
    component.childComponentType = ExampleComponent;

    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should set call onOverlayClicked click', () => {
    fixture.detectChanges();

    spyOn(component, 'onOverlayClicked');
    const overlay = fixture.debugElement.query(By.css('.overlay'));
    overlay.triggerEventHandler('click', {});
    fixture.detectChanges();

    expect(component.onOverlayClicked).toHaveBeenCalled();

  });

  it('should set call onDialogClicked click', () => {
    fixture.detectChanges();

     spyOn(component, 'onDialogClicked');
     const overlay = fixture.debugElement.query(By.css('.dialog'));
     overlay.triggerEventHandler('click', {});
     fixture.detectChanges();

     expect(component.onDialogClicked).toHaveBeenCalled();

   });

});

A: I have now fixed it
spyOn(component, 'onOverlayClicked').and.callThrough();


text:
Q: Ways to call a native iPhone application from another native iPhone application What are the various ways to call a native iPhone application from another native iPhone application?

A: You can use the url scheme built into iOS. For example, you could call Safari with a url because it is registered as the application which handles the http URL scheme
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com/"]]

The openURL: method is an instance method of the singleton UIApplication instance, on which you can call any application installed which registers in its plist an ability to handle some sort of input data.
Here's a list of common url schemes in iOS.
A little known way to detect the existence of another application on a device is to use canOpenURL: on the same singleton instance:
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]])
{
    NSLog(@"cydia installed");
}
else
{
    NSLog(@"cydia not installed");
}


text:
Q: FluentValidation: How to inject all registered validators? I'm using FluentValidation.AspNetCore library (Version="10.3.3") for a .Net Core project.
To register validators i use this:
services.AddValidatorsFromAssemblyContaining<TestValidator>();
For example i have class called Test and i can inject validator for this class like this:
    public class Service : IService
    {
        private readonly IValidator<Test> _testValidator;

        public Service(IValidator<Test> testValidator)
        {
            _testValidator = testValidator;
        }
   }

But i dont know how to inject all registered validators into my Service constructor as IEnumerable instance. So what is the correct way to do it?

A: FluentValidation's AddValidatorsFromAssemblyContaining registers all validators implementing IValidator<T> from assembly as generic interface and self so you can resolve them only by concrete type or constructed generic (i.e. IValidator<Test>) i.e. it is not possible to resolve all of them as a single collection.
If you really want you can try leveraging that IValidator<T> inherits IValidator and use the following (a bit hacky) solution:
services.AddValidatorsFromAssemblyContaining(typeof(Val1));

// Only after all validators registrations
var serviceDescriptors = services
    .Where(descriptor => typeof(IValidator) != descriptor.ServiceType
           && typeof(IValidator).IsAssignableFrom(descriptor.ServiceType)
           && descriptor.ServiceType.IsInterface)
    .ToList();

foreach (var descriptor in serviceDescriptors)
{
    services.Add(new ServiceDescriptor(
        typeof(IValidator),
        p => p.GetRequiredService(descriptor.ServiceType),
        descriptor.Lifetime));
}

After that you will be able to resolve IEnumerable<IValidator>. Though not sure that this will be much help for you.


text:
Q: Passing list to WHERE IN clause with JPQL causes IllegalArgumentException I found today a (strange) issue while I was attempting to fetch objects from database by their ids using Hibernate and JPQL.
The method I call is:
List<User> userList = userDao.findUsersByIds(ids);

In details:
@Repository
public interface UserDao extends JpaRepository<User, Long> {
(...)
       @Query("SELECT u FROM User u " +
                "WHERE u.id IN :ids")
        List<User> findUsersByIds(@Param("ids") List<Long> ids);
}

I'm running out of ideas what the root cause ot this problem might be, since the list that's being passed is of type List<Long>.
It causes following stacktrace, though:
Caused by: java.lang.IllegalArgumentException: Parameter value element [37] did not match expected type [java.lang.Long (n/a)]
at org.hibernate.query.spi.QueryParameterBindingValidator.validateCollectionValuedParameterBinding(QueryParameterBindingValidator.java:77) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:46) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.internal.QueryParameterListBindingImpl.validate(QueryParameterListBindingImpl.java:75) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.internal.QueryParameterListBindingImpl.setBindValues(QueryParameterListBindingImpl.java:33) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.internal.AbstractProducedQuery.setParameterList(AbstractProducedQuery.java:568) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:490) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:106) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_144]

A: Try this (Query Method if you are using spring):
List<User> findAllByIdIn(List<Long> id);

Or JPQL:
@Query("SELECT u FROM User u WHERE u.id IN ?1")
List<User> findUsersByIds(List<Long> id);


text:
Q: Storing CheckBox state in a ListView I'm trying to implement a piece of code I found to store the state of a CheckBox that is in a ListView but it didn't worked. Does anyone have any idea why my code from my adapter isn't working?
package kevin.erica.box;

import java.util.ArrayList;

import kevin.erica.box.R;

import android.R.color;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class MobileArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;
    private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

    public MobileArrayAdapter(Context context, String[] values) {
        super(context, R.layout.list_adapter, values);
        this.context = context;
        this.values = values;

        for (int i = 0; i < this.getCount(); i++) {
            itemChecked.add(i, false); // initializes all items value with false
        }
    }

    @Override
    public View getView(final int position, View covertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.list_adapter, parent, false);
            CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
            textView.setTextColor(0xFFFFFFFF);
            textView.setText(values[position]);
            //Store state attempt
            final CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1); // your
            // CheckBox
            cBox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {

                CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);

                if (cb.isChecked()) {
                    itemChecked.set(position, true);
                    // do some operations here
                } else if (!cb.isChecked()) {
                    itemChecked.set(position, false);
                    // do some operations here
                }
            }
        });
        cBox.setChecked(itemChecked.get(position)); // this will Check or Uncheck the
        // CheckBox in ListView
        // according to their original
        // position and CheckBox never
        // loss his State when you
        // Scroll the List Items.
        return rowView;
    }
}

A: You question didn't say anything about storing the data after the application has closed. To store the checked CheckBoxes you could use a database or a simple file. Bellow is an example of storing the CheckBox state in a database:
public class SimplePlay extends ListActivity {

    private String[] soundnames;
    private Helper mHelper = new Helper(this, "position_status.db", null, 1);
    private SQLiteDatabase statusDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // this is to simulate data
        soundnames = new String[40];
        for (int i = 0; i < 40; i++) {
            soundnames[i] = "Sound " + i;
        }
        // Retrieve the list of position that are checked(if any) from the
        // database
        statusDb = mHelper.getWritableDatabase();
        Cursor statusCursor = statusDb.rawQuery("SELECT * FROM status", null);
        int[] savedStatus = null;
        if ((statusCursor != null) & (statusCursor.moveToFirst())) {
            savedStatus = new int[statusCursor.getCount()];
            int i = 0;
            do {
                savedStatus[i] = statusCursor.getInt(0);
                i++;
            } while (statusCursor.moveToNext());
        }
        // if the cursor is null or empty we just pass the null savedStatus to
        // the adapter constructor and let it handle(setting all the CheckBoxes
        // to unchecked)
        setListAdapter(new MobileArrayAdapter(this, soundnames, savedStatus));
    }

    public class MobileArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;
        private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

        public MobileArrayAdapter(Context context, String[] values,
                int[] oldStatus) {
            super(context, R.layout.adapters_simpleplay_row, values);
            this.context = context;
            this.values = values;

            // make every CheckBox unchecked and then loop through oldStatus(if
            // not null)
            for (int i = 0; i < this.getCount(); i++) {
                itemChecked.add(i, false);
            }
            if (oldStatus != null) {
                for (int j = 0; j < oldStatus.length; j++) {
                    itemChecked.set(oldStatus[j], true);
                }
            }
        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            View rowView = convertView;
            if (rowView == null) {
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(R.layout.adapters_simpleplay_row,
                        parent, false);
            }
            CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
            cBox.setTextColor(0xFFFFFFFF);
            cBox.setText(values[position]);
            cBox.setTag(new Integer(position));
            cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    int realPosition = (Integer) buttonView.getTag();
                    if (isChecked) {
                        itemChecked.set(realPosition, true);
                        // update the database to store the new checked item:
                        ContentValues cv = new ContentValues();
                        cv.put("list_position", realPosition);
                        statusDb.insert("status", null, cv);
                    } else {
                        itemChecked.set(realPosition, false);
                        // delete this position from the database because it was
                        // unchecked
                        statusDb.delete("status", "list_position = "
                                + realPosition, null);
                    }
                }
            });
            cBox.setChecked(itemChecked.get(position));
            return rowView;
        }
    }

    //for working with the database
    private class Helper extends SQLiteOpenHelper {

        public Helper(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // the list_position will hold the position from the list that are
            // currently checked
            String sql = "CREATE TABLE status (list_position INTEGER);";
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Just for interface
        }

    }

}

After a quick test, the code works. It is just an example.

A: you can do one thing take an boolean array of same size & store whether it is clicked or not
you can also use another class to store the checked state...
this is the example of multiple selection of contacts this surely helps u.....
Multiple selection of Contacts
EDIT:
Example
public class simple List extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, GENRES));

    final ListView listView = getListView();

    listView.setItemsCanFocus(false);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

private static final String[] GENRES = new String[] { "india", "england", "London", "New york", "New jercy", "LA", "Pakistan", "srilanka", "bangladesh", "chin", "Australia", "Japan" };}


text:
Q: Python: My function returns "None" after it does what I want it to Here is my program
def reverse(letters):
    backwards = ""
    i = len(letters) - 1
    while i >= 0:
        backwards = backwards + letters[i]
        i = i - 1
    print (backwards)

print (reverse("hello"))

It works, it prints out "olleh" but after, it prints "None" on a new line. And I'm asking why this is.
Obviously the program is to reverse a word, the code works, and without a function it doesn't print none, so I don't know why it does in the function. This is being used in another larger program, so I need it as a function, and because it's for school, I'm not allowed to simply use the .reverse() function. So I really need this code fixed rather than large changes, if possible.

A: function return None by default, so you should  return backwards explicitly
also, you can use a pythonic way to solve the problem:
letters[::-1]

A: You can use a return statement to exit the function returning a value. If the function gets to the end without reaching a return statement, it will return None by default
def add1(x):
   return x+1

def returnsNone():
   pass

print(add1(2))
print(returnsNone())

A: Every function returns something in Python. If you don't explicitly return a value, Python has your function return None.
Your function doesn't actually return anything because print prints to stdout, while return actually returns a value. They may look the same in the REPL, but they're completely different.
So to fix your problem, return a value:
return backwards

A: Try just:
 reverse(hello)

In fact with
print reverse(hello)

you are printing the return value of reverse. And that return value is None.
Let me give you few general advises:
reverse() in your code is a function with side effects (printing). You should avoid
functions with side effects when you don't need, consider having reverse() returning the word instead of printing it:
def reverse(letters):
    backwards = ""
    i = len(letters) - 1
    while i >= 0:
        backwards = backwards + letters[i]
        i = i - 1
    return backwards
print (reverse("hello"))

Moreover
i = len(letters) - 1
    while i >= 0:
        backwards = backwards + letters[i]
        i = i - 1

is not easy to mantain and if you add functionality to the loop the decrement i=i-1 will be far from the place where it should 'conceptually' be. You should prefer having decrement together with the check:
for i in xrange(len(letters)-1,-1,-1):
    backwards = backwards + letters[i]

When I'm lazy I write
myString = myString + fewChars

so I can understand you being lazy. But adding fewChars does not modify myString but creates a new one. If you are iteratively adding many chars, rarely the most efficient way is to add one by one. Consider using join().
For instance
letters = 'word'
lettersList = [letters[i] for i in xrange(len(letters)-1,-1,-1)]
myReversed ''.join(lettersList)

ok I agree is not readable and probably not even faster, but for larger strings it scales better than a newString = oldString + oneChar approach.
That said, more pythonic approaches
letters[::-1]

already suggested by someone faster than me typically works much better and are easy to be read by python programmers.

A: It makes sense if you think about it. Your reverse does not return anything - it just prints it's result. But when you write print (reverse("hello")), you are actually printing what reverse returns. Since it doesn't return anything, None is printed.

A: As mentioned earlier. If the python function does not come across a return statement it prints None by default. Making a small change as shown below fixes this:
def reverse(letters):
    backwards = ""
    i = len(letters) - 1
    while i >= 0:
        backwards = backwards + letters[i]
    i = i - 1
    return(backwards)  # instead of print(backwards)

print(reverse("hello"))


text:
Q: Thread scheduling issue with MFC and AfxBeginThread I'm creating a worker thread in MFC with AfxBeginThread, but the thread is not getting scheduled. Here's the code:
CWinThread* worker = AfxBeginThread(initialUpdateWorkerThread, this);
DWORD dwExitCode = 0;
while(GetExitCodeThread(worker->m_hThread, &dwExitCode))
{
    if(dwExitCode != STILL_ACTIVE)
        break;
    ::Sleep(100);
}

When I run this, this loop just livelocks because initialUpdateWorkerThread is never called (I've put break points and message boxes at the top of it) so dwExitCode is always STILL_ACITVE. But if I put in a call to AfxMessageBox before the loop but after AfxBeginThread then the function is called. This makes me think that somehow I'm not calling the right function to get the thread scheduled, but a call to AfxMessageBox causes it to get scheduled.
How can I force the thread to be scheduled? I would think sleep would do that, but in this case it doesn't seem to.

A: Your worker thread is probably trying to send your main thread a message, but since you aren't processing messages on on the main thread, the worker thread simply waits. You can confirm this by simply breaking into the debugger to see what the worker thread is doing.


text:
Q: getting dimension of multidimensional array in ruby I just started learning ruby.
Now I need to figure out the dimension of a multidimensional array. I had a look at ruby-docs for the all the array methods, but I could not find a method that returns the dimension.
Here is an example:
For [[1, 2],[3,4],[5,6]] the dimension should be 2.
For [[[1,2],[2,3]],[[3,4],[5]]], the dimension should be 3.

A: Simple, object-oriented solution.
class Array
  def depth
    map {|element| element.depth + 1 }.max
  end
end

class Object
  def depth
    0
  end
end

A: There is not a built-in function for that as there may be multiple definition as to what you mean by "dimension" for an array. Ruby's arrays may contain anything including hashes or other arrays. That's why I believe you need to implement your own function for that.
Asuming that by dimension you mean "the deepest nested level of arrays" this should do the trick:
def get_dimension a
  return 0 if a.class != Array
  result = 1
  a.each do |sub_a|
    if sub_a.class == Array
      dim = get_dimension(sub_a)
      result = dim + 1 if dim + 1 > result
    end
  end
  return result
end

EDIT: and as ruby is a great language and allows you to do some fancy stuff you can also make get_dimension a method of Array:
 class Array
   def get_dimension
   ... # code from above slightly modified
   end
 end

A: in the simplest case
depth = Proc.new do |array|
  depth = 1
  while Array === array.first do
    array = array.first
    depth += 1
  end
  depth
end

array =  [[[1,2],[2,3]],[[3,4],[5]]]
depth.call(array)
#=> 3

Or this tiny recursive method
def depth(array, depth=1)
  array = array.send(:first)
  Array === array ? depth(array, depth+1) : depth
end

array =  [[[1,2],[2,3]],[[3,4],[5]]]
depth(array)
#=> 3

A: How about:
class Object
    def dimension
        self.class == Array ? 1 + self[0].dimension : 0
    end
end
[[[1,2],[2,3]],[[3,4],[5]]].dimension
#=> 3

A: As a modification of Tass's approach:
class Array
    def depth
        map{ |element| element.is_a?( Vector ) ? element.depth + 1 : 1 }.max
    end
end

Keeps depth as a method of Array, and doesn't require adding a method to Object.
Of course, that might be what you want if you are going to call my_object.depth, where you don't know in advance that my_object.class == Array

A: I was not satisfied with the other solutions so I wrote a one-liner I'd actually use:
def depth(array)
  array.to_a == array.flatten(1) ? 1 : depth(array.flatten(1)) + 1
end

It will flatten the array 1 dimension at the time until it can't flatten anymore, while counting the dimensions.
Why is this better?

*

*doesn't require modification to native classes (avoid that if possible)

*doesn't use metaprogramming (is_a?, send, respond_to?, etc.)

*fairly easy to read

*works with hashes as well (notice array.to_a)

*actually works (unlike only checking the first branch, and other silly stuff)


text:
Q: How to have header in some particular pages? In document class "report", in some particular pages, I  would like to have two kinds of headers. I want that the header for the odd pages is as follows:
Title1 ................................................. Page number

and accordingly, the header for the even pages as follows:
Page number ............................................ Title2

I should to explain that title 1 is related to the "name of my report" and title 2 is fixed and is independent of the chapter name. In the following, I have mentioned my work:
\documentclass[11pt,a5paper,twoside]{report}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage[top=25mm, bottom=25mm, left=20mm, right=20mm]{geometry}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage{framed}
%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{indentfirst}
\usepackage{emptypage}
\usepackage{titlesec}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[colorlinks=true,linkcolor=Blue,urlcolor=Blue,citecolor=Blue]{hyperref}
\usepackage{algorithm,algcompatible}
\usepackage[textfont={small},labelfont={rm,small},format=hang,labelsep=quad,justification={centering},aboveskip=1pt,belowskip=1pt]{caption}
\usepackage{subcaption}
\usepackage[nottoc]{tocbibind}
\usepackage{tocloft}
\usepackage{times}
\usepackage{cite}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\titleformat{\chapter}[display]
{}{}{1ex}{\bfseries\fontsize{15}{16}\selectfont}[]
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}} % for chapters
\begin{document}
\pagenumbering{alph}
\tableofcontents
\cleardoublepage
\pagestyle{plain}
\pagenumbering{arabic}
This is my work.
\end{document}

How can I do it?
Thank you

A: Here is a simple solution with titleps, which is loaded  with the pagestyles option of titlesec. Likewise, the   clearempty option replaces loading the emptypage package.
Note the first page of chapters (if any) still have the plain page style (page number centred in the footer).  This can  be modified, either adding a command in \titleformat{\chapter} or re-defining the plain page style with \renewpagestyle{plain}.
I took the opportunity to simplify the options for geometry. Some other remarks: hyperref should be loaded as the last package, with very few exceptions (most notably cleveref should be loaded afterwards). Also, if you have maths in your document (I suppose so, since you load mathtools), you should use a maths font which fits times – I loaded newtxmath for that, which is based on the Times-clone TeX Gyre Termes, ad I'd recommend, if you're allowed to replace times, to load also newtxtext, to have true small caps and some other delicacies.
\documentclass[11pt,a5paper,twoside, dvipsnames]{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage[vmargin=25mm, hmargin=20mm]{geometry}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage{framed}
%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{indentfirst}
\usepackage{emptypage}
\usepackage[pagestyles, clearempty]{titlesec}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{algorithm,algcompatible}
\usepackage[textfont={small},labelfont={rm,small},format=hang,labelsep=quad,justification={centering},aboveskip=1pt,belowskip=1pt]{caption}
\usepackage{subcaption}
\usepackage[nottoc]{tocbibind}
\usepackage{tocloft}
\usepackage{times, newtxmath}
\usepackage{cite}
\usepackage[colorlinks=true,linkcolor=Blue,urlcolor=Blue,citecolor=Blue]{hyperref}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[toc]{blindtext} %for demonstrating purposes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\titleformat{\chapter}[display]
{}{}{1ex}{\bfseries\fontsize{15}{16}\selectfont}[]
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}} % for chapters

\newpagestyle{myps}{%
\sethead[][\thepage\enspace\dotfill\enspace Title 2][]{}{Title 1\enspace\dotfill\enspace\thepage}{}
\setfoot{}{}{}
}%

\begin{document}

\pagenumbering{alph}
\tableofcontents
\cleardoublepage
\pagestyle{myps}
\pagenumbering{arabic}

\chapter{A First Chapter}
\Blindtext[5][2]
\chapter{A Second Chapter}
\Blindtext[2][5]

\end{document}

A: If I understand your question, The following is an elementary answer:
\documentclass[11pt,a5paper,twoside]{report}
\usepackage{lipsum}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage[top=25mm, bottom=25mm, left=20mm, right=20mm]{geometry}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage{framed}
%%%%%%%%%%%%%%%%%%%%%%%%%%
    \usepackage{indentfirst}
\usepackage{emptypage}
\usepackage{titlesec}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[colorlinks=true,linkcolor=Blue,urlcolor=Blue,citecolor=Blue]        {hyperref}
\usepackage{algorithm,algcompatible}
\usepackage[textfont={small},labelfont=        {rm,small},format=hang,labelsep=quad,justification=    {centering},aboveskip=1pt,belowskip=1pt]{caption}
\usepackage{subcaption}
\usepackage[nottoc]{tocbibind}
\usepackage{tocloft}
\usepackage{times}
\usepackage{cite}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\fancyhf{}
\fancyhead[LO]{\small  \leftmark \ \hrulefill\ \thepage}
\fancyhead[RE]{\small  \thepage \ \hrulefill\ \rightmark}
\fancypagestyle{plain}{%
\fancyhead{}
}
\renewcommand{\headrulewidth}{0pt}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\titleformat{\chapter}[display]
{}{}{1ex}{\bfseries\fontsize{15}{16}\selectfont}[]
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}} % for chapters
\begin{document}
\pagenumbering{alph}
\tableofcontents
\cleardoublepage
%\pagestyle{plain}
\pagenumbering{arabic}
\lipsum[3-56]
\end{document}

You can use \dotfill command instead of \hrulefill for dotted header.


text:
Q: Determining (de)selected checkbox in a checkedListBox as they are selected I'm looking to setup a checkedListBox in C#. There will be roughly 50 names displayed in this checkedListBox. I'd like it so that when a name is either selected or deselected, then the program will be able to store it in a variable.
I already have the code so that when a button is pressed, it searches through all off the names in the checkedListBox and returns all those with the selected state:
for (int i = 0; i < nameBox.CheckedItems.Count; i++)
{
          ArrayList.Add(nameBox.CheckedItems[i]);
}

I know that in Java I can use the e.getStateChange() to determine which item has either been selected or deselected:
public void itemStateChanged(ItemEvent e)
{
        if(e.getStateChange() == ItemEvent.SELECTED)
    {
              ArrayList = checkbox.getText();
        }
}

Is there anything similar to this Java code that I can use in C# for the checkedListBox?
Any help/advice will be greatly appreciated!

A: Building on the comment and the link, which has all you need in the example:
In your form add the private variable, such as a List:
 public class Form1 : System.Windows.Forms.Form
   {
      private System.Windows.Forms.CheckedListBox checkedListBox1;
      private List<string> extraVariable;

then in your constructor or wherever you initialize the checkList, also initialize your extra variable:
      public Form1()
      {
         InitializeComponent();

         extraVariable = new List<string>();

Then add your ItemChecked event, where you Add or Remove from your extra variable:
      private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
      {
         if(e.NewValue==CheckState.Unchecked)
         {
            extraVariable.Remove(e.NewValue);
         }
         else
         {
            extraVariable.Add(e.NewValue);
         }
      }


text:
Q: Why does WSO2 API Manager tryit feature fail? I have a configuration as follows:
1 server with seperate Publisher (9446) and Store (port 9447).  Both are configured with shared gov/config registry (note that the publisher is the same except localhost:9446/registry for the remote instance url:
<dbConfig name="govregistry">
    <dataSource>jdbc/WSO2SHAREDCONREG_DB</dataSource>
</dbConfig>
<remoteInstance url="https://localhost:9447/registry">
    <id>gov</id>
    <dbConfig>govregistry</dbConfig>
    <readOnly>false</readOnly>
    <enableCache>true</enableCache>
    <registryRoot>/</registryRoot>
</remoteInstance>
<mount path="/_system/governance" overwrite="true">
    <instanceId>gov</instanceId>
    <targetPath>/_system/governance</targetPath>
</mount>
<mount path="/_system/config" overwrite="true">
    <instanceId>gov</instanceId>
    <targetPath>/_system/nodes</targetPath>
</mount>

I have a Gateway and Key Manager on a different server.  These are both deployed to different directories and the WSO2 documentation did not say to do anything additional for the registry.xml file so they look like:
<currentDBConfig>wso2registry</currentDBConfig>
<dbConfig name="wso2registry">
    <dataSource>jdbc/WSO2CarbonDB</dataSource>
</dbConfig>

When the API is published and then I attempt to use the 'try it' functionality I get the following error (regardless of if the API is set to require a token or not)...
This error is on the gateway server:
[2014-01-23 21:54:31,111] ERROR - APIAuthenticationHandler API authentication failure
org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException: Access failure for API: /newphoneverify, version: 1.0.0 with key: null

Do I need to do something additional like setting up governance and config registry sharing on the keymanager and gateway as well?

A: This happens if the OPTIONS verb of the API is not enabled with 'None' auth type. Check [1].
[1]https://wso2.org/jira/browse/APIMANAGER-1819

A: I have the same problem:
Swagger UI does not works and return the same screenshots above, but if I use chrome/postman the API return the correct value so is just the swagger UI that has problems, I have an Apache in front of the API manager and the external name of the store is different from the internal name and apache proxypass the request.
I have configured the api-manager.xml and the API does not have authorization (all set to none) have really no idea on how to fix it.


text:
Q: Openssl Sha1 compile issue #include <algorithm>
#include <stdio.h>
#include <openssl/sha.h>

using namespace std;

int main()
{
    unsigned char ibuf[] = "compute sha1";
    unsigned char obuf[20];

    SHA1(ibuf, strlen(ibuf), obuf);

    int i;
    for (i = 0; i < 20; i++) {
        printf("%02x ", obuf[i]);
    }
    printf("\n");
}

g++ file.cpp -o file -l libssl

file.cpp: In function 'int main()':
file.cpp:29:27: error: invalid conversion from 'unsigned char*' to 'const char*' [-fpermissive]
/usr/include/string.h:399:15: error:   initializing argument 1 of 'size_t strlen(const char*)' [-fpermissive]

Wonder whats wrong.. I am trying to compute a sha1

A: First, I wonder if it got lost in anonymization, but it seems to me there's missing
include <string.h>

and the commandline should really look more like:
g++ file.cpp -o file -lssl

You're using C++ compiler. C++ compilers are usually very strict about types. You've defined ibuf to be unsigned char (and used in strlen it is treated as unsigned char *)  and strlen expects const char*, so it produces an error.
You have following options:

*

*you can just cast ibuf in strlen:
SHA1(ibuf, strlen((const char *)ibuf), obuf);

*you can use suggested -fpermissive flag to make g++ more forgiving and transform errors to mere warnings, although I wouldn't recommend it:
g++ -fpermissive file.cpp -o file -lssl

*As the code looks just like a plain C, maybe you don't need C++ compiler. If that's the case, just use C-compiler instead of C++:
gcc file.cpp -o file -lssl

You would then need to remove include <algorithm> and namespace...


text:
Q: ENOENT: no such file or directory: even if the folder exists I tried to submit a form through postman, but I keep getting the no such file error, The pdf is not getting saved to the path mentioned in local pc, even though the file exists. Node keeps throwing the error :

[Error: ENOENT: no such file or directory
Error: ENOENT: no such file or directory, open
  'D:\lims\Generate_PDF_for_Forms\ViralFlexSeqSubmissionForm_Dash_7-2-2019_13:37:42.pdf']
        errno: -4058,
        code: 'ENOENT',
        syscall: 'open',
        path:
         'D:\lims-customer\Generate_PDF_for_Forms\ViralFlexSeqSubmissionForm_Dash_7-2-2019_13:37:42.pdf' .

Brief Code :
    const printer = new pdfMakePrinter(fontDescriptor);
    const doc = printer.createPdfKitDocument(docDefinition);
    // functions getDateAndTime returns date in mm/dd/yyyy format followed by time in HH:MM:SS:Milliseconds
    const dateAndTime = getDateAndTime();
    const pdfName = 'ViralFlexSeqSubmissionForm' + '_' + user.lastName + '_' + dateAndTime + '.pdf';
    console.log("HereYouGo::"+pdfName);
    doc.pipe(fs.createWriteStream('Generate_PDF_for_Forms/' + pdfName).on('error', (err) => {
            console.log(err);
        })
    );


text:
Q: Labels when using gaps between line and point in pgfplots this is a follow up question to: Gap between line and point in pgfplots, like pointintervalbox in gnuplot.
I would like to add a legend in the plot and maybe even on the y-axis. Unfortunatelly this does not work with the "discontinuous line" code:
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\makeatletter
\pgfplotsset{
discontinuous line/.code={
    \pgfkeysalso{mesh, shorten <=#1, shorten >=#1}
    \def\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke{%
        \pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
        \pgfplotsplothandlermesh@definecolor
        \pgfusepath{stroke}
        \pgfplotsplothandlermesh@show@normals@if@configured
    }%
},
discontinuous line/.default=1.5mm
}
\makeatother
\begin{document}
\begin{tikzpicture}

\begin{axis}[
axis background/.style={
    shade,bottom color=gray!50,top color=white
},
legend pos=north west,
xlabel=$x$,
ylabel=\ref{dataone}\ one  \ref{datatwo}\ two
]
\addplot [discontinuous line, black, mark=*] table {
0 5
1 3
2 4
3 8
4 0
};
\label{dataone}
\addlegendentry{one}
\addplot [discontinuous line=3mm, red, mark=square] table {
0 1
2 5.5
3 7.25
4 8
};
\label{datatwo}
 \addlegendentry{two}
\end{axis}
\end{tikzpicture}
\end{document}

Which gives this result:

Does anyone have an idea how to get the correct legend?
Thanks and greetings!

A: To fix the legend, you'll need to redefine the legend image code/.code:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\makeatletter
\pgfplotsset{
    discontinuous line/.code={
        \pgfkeysalso{mesh, shorten <=#1, shorten >=#1,
        legend image code/.code={
        \draw [##1, shorten <=0cm] (-#1,0cm) -- (0.3cm,0cm);
        \draw [only marks] plot coordinates {(0.3cm,0cm)};
        \draw [##1, shorten >=0cm] (0.3cm,0cm) -- (0.6cm+#1,0cm);
        }}
        \def\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke{%
            \pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
            \pgfplotsplothandlermesh@definecolor
            \pgfusepath{stroke}
            \pgfplotsplothandlermesh@show@normals@if@configured
        }%
    },
    discontinuous line/.default=1.5mm
}
\makeatother
\begin{document}
\begin{tikzpicture}

\begin{axis}[
axis background/.style={
    shade,bottom color=gray!50,top color=white
},
legend pos=north west,
xlabel=$x$,
ylabel=\ref{dataone}\ one  \ref{datatwo}\ two
]
\addplot [discontinuous line, black, mark=*] table {
0 5
1 3
2 4
3 8
4 0
};
\label{dataone}
\addlegendentry{one}
\addplot [discontinuous line=3mm, red, mark=square] table {
0 1
2 5.5
3 7.25
4 8
};
\label{datatwo}
 \addlegendentry{two}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Autodesk Forge Design Automation Freeze We are running an application using Forge Design Automation for Revit and have an issue I can't fully explain.  Our tests have been working just fine but we got a couple lately that seem to freeze inside Revit as far as I can tell.  Here is the OnStartup method of my external application:
    public ExternalDBApplicationResult OnStartup(ControlledApplication application)
    {
        SharedData.Initialize(new LoggerConsole());
        // Startup is only for registering the DA ready event
        SharedData.Log.AddLine("Design automation startup in App");
        DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationBridge_DesignAutomationReadyEvent;
        SharedData.Log.AddLine("Design automation event registered");
        return ExternalDBApplicationResult.Succeeded;
    }

Here is the outline of the event handler referenced:
    void DesignAutomationBridge_DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e)
    {
        // Start the actual processing here
        SharedData.Log.AddLine($"Into automation ready event, working directory is: {Environment.CurrentDirectory}");

       ...Other Code...
    }

The log for one of the jobs I'm talking about (clipped to relevant portion) looks as follows:
[12/10/2020 01:34:42] Design automation startup in App
[12/10/2020 01:34:42] Design automation event registered
[12/10/2020 01:34:42] Initialize and  get RCE: (VersionBuild) 21.1.10.26 (VersionNumber) 2021 (SubVersionNumber) 2021.2
[12/10/2020 04:34:33] Error: Revit Core Engine Core Console is shut down due to process time limit.
[12/10/2020 04:34:33] End script phase.

As you can see, it makes it to the log line about event registered so the only thing left to do after that is return success.  It does seem to get that success because the next log line is from inside Revit (the one that starts with 'Initialize and get').  Then after that it seems to wait 3 hours and then error because of time out.  It never logs the very first line of the event handler so as far as I can tell that's not getting called.
Anyone else experienced this?  How would you even go about debugging it?


text:
Q: T-SQL query must include and exclude child rows I have simple parent -> child (one to many) relationship. Need to return children that have all given attributes, in this case red hair and brown eyes.
Table:
CREATE TABLE [dbo].[children](
    [child_id] [int] IDENTITY(1,1) NOT NULL,
    [parent_id] [int] NOT NULL,
    [attribute] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK_children] PRIMARY KEY CLUSTERED
(
    [child_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Data:
insert into children (parent_id, attribute) values (1, 'red hair');
insert into children (parent_id, attribute) values (1, 'blue eyes');
insert into children (parent_id, attribute) values (2, 'red hair');
insert into children (parent_id, attribute) values (2, 'brown eyes');
insert into children (parent_id, attribute) values (3, 'purple hair');
insert into children (parent_id, attribute) values (3, 'brown eyes');

Desired Result:
parent_id
2

Semi Working Query:
select parent_id

from children

where attribute in ('red hair','brown eyes')

group by parent_id

having count(child_id) = 2;

That query works, however I would think there is a better way, (maybe not?) where I don't have to provide a count of the given arguments.
Update: Previous question and example were overly complicated and not communicated well. Hopefully this simplifies the issue.

A: Alright, round three!
So, it looks like you're trying to find any parents that match all given criteria, correct? I'm assuming you're looking to use this in some real world scenario (a report or application). If that's the case, you'll need to pass in the criteria using a parameter.
The code here is going on that assumption.For this to work correctly, you'll need a function to split the parameter string. STRING_SPLIT function is not supported until SQL 2012, so if you're working in 2008, you'll need this function.
SET QUOTED_IDENTIFIER ON;

SET ANSI_NULLS ON;
GO

CREATE FUNCTION dbo.SplitString
(
    -- Add the parameters for the function here
    @myString     VARCHAR(500)
    ,@deliminator VARCHAR(10)
)
RETURNS @ReturnTable TABLE
(
    -- Add the column definitions for the TABLE variable here
    id     INT         IDENTITY(1, 1) NOT NULL
    ,value VARCHAR(50) NULL
)
AS
BEGIN
    DECLARE @iSpaces INT;
    DECLARE @part VARCHAR(50);

    --initialize spaces
    SELECT  @iSpaces = CHARINDEX(@deliminator, @myString, 0);

    WHILE @iSpaces > 0
    BEGIN
        SELECT  @part = SUBSTRING(@myString, 0, CHARINDEX(@deliminator, @myString, 0));

        INSERT INTO @ReturnTable
        (
            value
        )
        SELECT @part ;

        SELECT  @myString = SUBSTRING(
                                         @myString, CHARINDEX(@deliminator, @myString, 0) + LEN(@deliminator)
                                         ,LEN(@myString) - CHARINDEX(' ', @myString, 0)
                                     );

        SELECT  @iSpaces = CHARINDEX(@deliminator, @myString, 0);
    END;

    IF LEN(@myString) > 0 INSERT INTO @ReturnTable   SELECT @myString;

    RETURN;
END;
GO

Then, this query should give you the results you're looking for.
If you're using SQL 2012 or higher, you can replace the function (dbo.SplitString) with the built in windowed function STRING_SPLIT and achieve the same results.
DECLARE @ParmList VARCHAR(MAX) = 'red hair,blue eyes';

SELECT  c.parent_id
FROM    dbo.children AS c
WHERE   EXISTS (
                   SELECT   1
                   FROM     dbo.SplitString(@ParmList, ',') AS at
                   WHERE    at.value = c.attribute
               )
GROUP BY
        c.parent_id;

A: Sorry I have found I mistyped "intersect" as "union", all are corrected now
Previous problem
(select photo_id from tags where text = 'include-1'
intersect
select photo_id from tags where text = '2-some-tag'
intersect
select photo_id from tags where text = 'anothertag'
)
except
select photo_id from tags where text in ('exclude-x', 'dont-include')

New problem
select parent_id from @children where attribute = 'red hair'
intersect
select parent_id from @children where attribute = 'brown eyes'


text:
Q: how to throw customize fault message from jax-rs webservice Can any one help me out how i can throw a customize server exception from jax-rs webservice which will be send response to client in the  xml tag. as  I am not be able to find the wsdl file for that webservice so can any one help me out by providing complete tutorial or  complete example
Thanks In Advance.


text:
Q: Linux assembly and printf i try write simple assemble program with printf function. I compile it nasm -f elf 64 and link using gcc. After run i see segmentation fault. What is wrong?
[Bits 32]

extern printf
global main

section .data

hello:
db "Hello", 0xa, 0

section .text

main:

push hello
call [printf]

add esp, 4

mov eax, 1
mov ebx, 0
int 80h

A: Linux on ia32 doesn't use the same calling convention as on amd64. As your code uses the former you must assemble it as 32 bits and link with a 32 bits libc. On debian you'll need the libc6-dev-i386 package.
You must also replace 'call [printf]' with 'call printf', that's a mistake.
Note also that as you are using the main interface you should return from main instead of performing an exit system call to allow the C runtime shutdown code to run.
Hello World example for x86-32 with build instructions.
If you are working on amd64, you might want to learn how to write 64 bits assembly instead.
Hello World example for x86-64 with build instructions.

A: If you really want to get a 32 bit binary as your code header shows then you just need to fix the line:
call [printf]

changing it to:
call printf

When you do call [printf] you are not calling printf but the address pointed by first printf  code bytes, that construction ([address]) is called an effective address.


text:
Q: C# WinForms: How to restrict MDI child windows to always be within the bounds of the MDIParent? I have a C# WinForms MDI application that has a few MDI child windows. Users are able to move or resize the individual windows. The issue is that when they move the windows to the bounds of the MDI parent, scrollbars appear on the MDIParent window and the user can drag the child windows outside the bounds of the MDI parent. Is there any way to change this behavior so that the child windows are always inside the parent window and no scrollbars are ever created? I know there are ways to "pop" the child windows back inside the parent window by overriding the OnMove event. I want the windows to stay inside even when the user is moving the window. Is there any way to do this?

A: On your child forms, handle the FormResize event, with something like this:
private void Form1_Resize(object sender, EventArgs e)
{
    Size pSize = this.ParentForm.ClientSize;

    Size maxAllowed = new Size(pSize.Width - this.Left, pSize.Height - this.Top);

    // Resize the child if it goes out of bounds
    if (this.Height > maxAllowed.Height)
        this.Height = maxAllowed.Height;

    if (this.Width > maxAllowed.Width)
        this.Width = maxAllowed.Width;
}

probably not great results depending on wht you want.
I would probably redo it so that it moves te form back in bounds instead of resizing it.


text:
Q: Apache24, PHP 8.2.1, Twig 3 Templates, Callable functions I'm working on a PHP website using Twig templating, on the following system specs:

*

*Window 10 x64 Pro (up to date)

*Apache 2.4.5 x64 for Windows

*PHP 8.2.1 x64 Thread Safe

*Twig 3

I have made a class for routing, referenced in an index.php file at the site root. I also render templates within this index.php file. All is working well, but it would look better and be more manageable, if I could put the Twig rendering into a separate file, namespace and class. This is where things stop working.
The code is as follows:
.htaccess file
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

A summarised route class
/src/router.php
<?php declare(strict_types=1);
namespace App {

    class Router {
        private array $handlers;

        public function get(string $path, callable $callback): void {
            $this->addHandler("GET", $path, $callback);
        }

        private function addHandler(string $method, string $path, callable $callback): void {
            $this->handlers[$method . $path] = [
                'path' => $path,
                'method' => $method,
                'handler' => $callback];
        }

        public function run() {
            $request_uri = parse_url($_SERVER['REQUEST_URI']);
            $request_path = $request_uri['path'];
            $request_method =  $_SERVER['REQUEST_METHOD'];
            $callback = null;

            foreach($this->handlers as $hnd) {

                if (($hnd['path'] === $request_path) && ($hnd['method'] === $request_method)) {
                    $callback = $hnd['handler'];
                    break;
                }
            }

            call_user_func_array($callback, [array_merge($_GET, $_POST)]);
        }
    }
} ?>

In my summerised index.php file.
index.php
<?php declare(strict_types=1);
    require_once "./src/router.php";
    use App\Router;
    $router = new Router();

    require_once __DIR__ . "/vendor/autoload.php";
    use \Twig\Loader\FilesystemLoader;
    use \Twig\Environment;

    $loader = new FilesystemLoader([__DIR__ . "/tpl"]);
    $twig_env = new Environment($loader, ['autoescape'=>false]);

    /* common website paramaters for the twig template */
    $base_data = ['site_title'=>"my-website",
          'site_author'=>"Me Myself & I", 'copy_right'=>"©2023",
          'css_sitewide'=>"http://my-website:8080/static/css/site-wide.css"];

    $home_page = function() use ($twig_env, $base_data) {
        $hp = ['page_title'=>"Home", 'page_desc'=>"Welcome to the my website", 'format_phone'=>"no", 'tell_me'=>"CRIKEY! IT WORKS'"];
        echo $twig_env->render("/index.html", $base_data + $hp);
    };
    $router->get("/", $home_page);

    $contact_page = function() use ($twig_env, $base_data) {
        $cp = ['page_title'=>"Contact", 'page_desc'=>"Get in touch, we'll join ya' in the chat.", 'format_phone'=>"yes", 'tell_me'=>"HELLO! ARE YOU THERE?"];
        echo $twig_env->render("/contact.html", $base_data + $cp);
    };
    $router->get("/contact", $contact_page);

    $router->run();
?>

All works quite well. But as the number of routes increase, the page looks more unmanageable. I want to place the rendering in another file and class, while leaving the router get calls on this index.php.
I've made another file and class summerised as such.
/src/render.php
<?php declare(strict_types=1);
namespace App {
    require_once "/apache24/my-website/vendor/autoload.php";
    use \Twig\Loader\FilesystemLoader;
    use \Twig\Environment;

    class Render {
        private static $loader;
        private static $twig_env;
        private static $base_data;

        public static function init(string $tpl) {
            Render::$loader = new FilesystemLoader($tpl);
            Render::$twig_env = new Environment(Render::$loader, ['autoescape'=>false]);
            Render::$base_data = ['site_title'=>"my-website",
                'site_author'=>"Me Myself & I", 'copy_right'=>"©2023",
                'css_sitewide'=>"http://my-website:8080/static/css/site-wide.css"];
        }

        public static function homePage() {
            $hp = ['page_title'=>"Home", 'page_desc'=>"Welcome to the my website", 'format_phone'=>"no", 'tell_me'=>"CRIKEY! IT WORKS'"];
            echo Render::$twig_env->render("/", Render::$base_data + $hp);
        }

    }
} ?>

This is where it stops working. The index.php file for this.
index.php
<?php declare(strict_types=1);
    require_once "./src/router.php";
    use App\Router;
    $router = new Router();

    require_once "./src/render.php";
    use App\Render;
    Render::init(__DIR__ . "/tpl");

    $router->get('/', Render::homePage());

    $router->run();
?>

The page indeed renders but I receive the following error in my php_error.log file,
[22-Jan-2023 18:38:16 Australia/Sydney] PHP Fatal error:

Uncaught TypeError: App\Router::get(): Argument #2 ($callback) must be of type callable, null given,
called in D:\apache24\my-website\index.php on line 11 and defined in D:\apache24\my-website\src\router.php:10

Stack trace:
#0 D:\apache24\my-website\index.php(11): App\Router->get()
#1 {main}
  thrown in D:\apache24\my-website\src\router.php on line 10

In the Firefox web developer console I get,
GET http://my-website:8080/ [HTTP/1.0 500 Internal Server Error 19ms]
Status             500 Internal Server Error
Version            HTTP/1.0
Transferred        1.14 kB (908 B size)
Referrer Policy    strict-origin-when-cross-origin
Request Priority   Highest

I'm having a guess here from the log file, but I think it's with the render function (public static function homePage()) return type. I can't make this callable.
Any suggestions, or pointers is deeply appreciated.
Thanks and regards,
njc