text:
Q: Multiple issues with Robolectric and ActionBarActivity test I'll just start with the project setup (as far as I see it relevant for the current problem):
Android studio 0.8.6
Gradle 1.12
robolectric-gradle-plugin 0.11.0
robolectric 2.3(tested with 2.4-SNAPSHOT also)
com.android.support:support-v4 20.0.0
com.android.support:appcompat-v7 20.0.0
com.google.android.gms:play-services 5.2.08
I have an activity that extends ActionBarActivity which I want to test.
First issue:
If I use the following setup I will get a NullPointerException from Robolectric when trying to read the AndroidManifest:
@Config(emulateSdk = 18, manifest = "src/main/AndroidManifest.xml")
@RunWith(RobolectricTestRunner.class)
public class FilterActivityTest {}

This error comes when trying to read the value for:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

This first error seems related to others posted here like https://github.com/robolectric/robolectric/issues/1025 and https://github.com/robolectric/robolectric-gradle-plugin/issues/56. By using the suggestions there I managed to get past this error. My @Config would look like this:
@Config(manifest = "build/intermediates/manifests/debug/AndroidManifest.xml", resourceDir = "../../../../build/intermediates/res/debug", emulateSdk = 18)

The next error was:
android.content.res.Resources$NotFoundException: Resource ID #0x7f0c0000
    at android.content.res.Resources.getValue(Resources.java:1118)
    at android.content.res.Resources.loadXmlResourceParser(Resources.java:2304)
    at android.content.res.Resources.getLayout(Resources.java:934)
    at android.support.v7.internal.view.SupportMenuInflater.inflate(SupportMenuInflater.java:115)
    at ro.cursurideschimb.user.FilterActivity.onCreateOptionsMenu(FilterActivity.java:56)
    at android.app.Activity.onCreatePanelMenu(Activity.java:2504)
    at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
    at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:233)
    at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:146)
    at android.support.v7.app.ActionBarActivity.onCreatePanelMenu(ActionBarActivity.java:200)
    at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onCreatePanelMenu(ActionBarActivityDelegateICS.java:293)
    at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:413)
    at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:775)
    at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:198)
    at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:37)
    at org.robolectric.shadows.ShadowLooper.post(ShadowLooper.java:207)
    at org.robolectric.shadows.ShadowHandler.postDelayed(ShadowHandler.java:56)
    at android.os.Handler.postDelayed(Handler.java)
    at android.view.ViewRootImpl$RunQueue.executeActions(ViewRootImpl.java:6230)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1239)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
    at android.view.Choreographer.doFrame(Choreographer.java:532)
    at android.view.Choreographer$FrameHandler.handleMessage(Choreographer.java:664)
    at org.robolectric.shadows.ShadowHandler.routeMessage(ShadowHandler.java:125)
    at org.robolectric.shadows.ShadowHandler.access$100(ShadowHandler.java:25)
    at org.robolectric.shadows.ShadowHandler$1.run(ShadowHandler.java:110)
    at org.robolectric.util.Scheduler$PostedRunnable.run(Scheduler.java:162)
    at org.robolectric.util.Scheduler.runOneTask(Scheduler.java:107)
    at org.robolectric.util.Scheduler.advanceTo(Scheduler.java:92)
    at org.robolectric.util.Scheduler.advanceToLastPostedRunnable(Scheduler.java:68)
    at org.robolectric.util.Scheduler.unPause(Scheduler.java:25)
    at org.robolectric.shadows.ShadowLooper.unPause(ShadowLooper.java:228)
    at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:267)
    at org.robolectric.util.ActivityController.create(ActivityController.java:110)
    at org.robolectric.util.ActivityController.create(ActivityController.java:120)
    at ro.cursurideschimb.user.FilterActivityTest.setUp(FilterActivityTest.java:30)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:267)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:194)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Which got solved by adding qualifiers = "v10" to the @Config annotation.
Now the error is:
java.lang.NullPointerException
at android.support.v7.app.ActionBarImplICS.setDisplayHomeAsUpEnabled(ActionBarImplICS.java:179)
at android.support.v7.app.ActionBarImplJB.setDisplayHomeAsUpEnabled(ActionBarImplJB.java:20)
at ro.cursurideschimb.user.FilterActivity.initialize(FilterActivity.java:72)
at ro.cursurideschimb.user.FilterActivity.onCreate(FilterActivity.java:105)
at android.app.Activity.performCreate(Activity.java:5133)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:113)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:265)
at org.robolectric.util.ActivityController.create(ActivityController.java:110)
at org.robolectric.util.ActivityController.create(ActivityController.java:120)
at ro.cursurideschimb.user.FilterActivityTest.setUp(FilterActivityTest.java:30)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:267)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:194)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

(Line 72 in FilterActivity reads like this:  actionBar.setDisplayHomeAsUpEnabled(true);)

Now, if I add reportSdk = 10 to the @Config annotation I get back to the missing resource ID error.
Any pointers here would be appreciated. Thank you for your time.


text:
Q: How to use onclick event after an image generated by php code? I am creating an image which is a graph, plotting days and no of documents created on each day.
I am using php to create image.
Now, to get more details about the query, I want to enable the user to click on the image created and redirect him to more details, which is a table.
Could anyone suggest me how to use onclick event...?

<form name="imageform" id="imageform" method="get" action="resultdocument.php" >
<img border="0" src="<?php graphytry.php/img.png ?>" width="304" height="228" onclick="details()"></form>

P.S:- Image is created in the same script, just above this HTML code.
The PHP code :-
    <?php
# ------- The graph values in the form of associative array
$xaxis="Jan";
$yaxis=110;
$values=array(
    $xaxis => $yaxis,
    );
$img_width=450;
$img_height=300;
$margins=20;

# ---- Find the size of graph by substracting the size of borders
$graph_width=$img_width - $margins * 2;
$graph_height=$img_height - $margins * 2;
$img=imagecreate($img_width,$img_height);

$bar_width=20;
$total_bars=count($values);
$gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);

# -------  Define Colors ----------------
$bar_color=imagecolorallocate($img,0,64,128);
$background_color=imagecolorallocate($img,240,240,255);
$border_color=imagecolorallocate($img,200,200,200);
$line_color=imagecolorallocate($img,220,220,220);

# ------ Create the border around the graph ------

imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);

# ------- Max value is required to adjust the scale -------
$max_value=max($values);
$ratio= $graph_height/$max_value;

# -------- Create scale and draw horizontal lines  --------
$horizontal_lines=20;
$horizontal_gap=$graph_height/$horizontal_lines;

for($i=1;$i<=$horizontal_lines;$i++){
    $y=$img_height - $margins - $horizontal_gap * $i ;
    imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
    //$v=intval($horizontal_gap * $i /$ratio);
    //imagestring($img,0,5,$y-5,$v,$bar_color);

}

# ----------- Draw the bars here ------
for($i=0;$i<$total_bars; $i++){
    # ------ Extract key and value pair from the current pointer position
    list($key,$value)=each($values);
    $x1= $margins + $gap + $i * ($gap+$bar_width) ;
    $x2= $x1 + $bar_width;
    $y1=$margins +$graph_height- intval($value * $ratio) ;
    $y2=$img_height-$margins;
    imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);
    imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);
    imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($img);?>

A: You can look at the option of creating image map and generate x1,y1, x2,y2 co-ordinates for click event with separate AJAX request, if you need to have multiple clicks on image instead of single click.
More about image map : click here
If you are just looking for single click, then as @Andreas suggested, use below

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to determine cumulative probability, i.e. the probability of the variable X being less than µ + σ when we do not know X, µ or σ Let's say that you need to find the cumulative probability for a random variable X which is normally distributed.
You do not know what the value of X is or, for that matter, what the value of µ and σ is.
You only know that X = µ + σ.
Can you find the cumulative probability, i.e. the probability of the variable being less than µ + σ?

A: I assume you mean what is ${\Bbb P}(X \le \mu+\sigma)$ for $X$ a $N(\mu,\sigma)$-distributed random variable. The answer is the same as ${\Bbb P}(Y \le 1)$ for $Y$ a $N(0,1)$-distributed random variable, which is $\Phi(1)$ where $\Phi$ is the cumulative distribution function of a standard normal, and the answer is approximately $0.841345$.


text:
Q: How to validate XML when schema is referenced in the XML document? The XML contains a link to the schema. How can I get C# to validate the XML against the schema?
<Specification xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schemas.company.com/Specification.xsd">
    <FirstElement>...</FirstElement>
</Specification>

I've changed the schema location URL for this post, so this example won't actually work. I've tried the following:
var schemaErrors = new List<string>();
var settings = new XmlReaderSettings
{
    DtdProcessing = DtdProcessing.Ignore,
    ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings,
    ValidationType = ValidationType.Schema
};
settings.ValidationEventHandler += (o, e) => { schemaErrors.Add(e.Message); };

using (var xmlReader = XmlReader.Create(xmlText, settings))
{
    XDocument.Load(xmlReader);
    var actual = schemaErrors;

    Assert.That(actual, Is.Empty);
}

where xmlText is the XML from above.
I get the following errors:
"Cannot load the schema for the namespace '' - The underlying connection was closed: An unexpected error occurred on a send."
"Could not find schema information for the element 'Specification'."
I've searched the internet for answers but it seems everyone uses a local schema.

A: It would appear there's nothing wrong with the code. Despite the schema validating correctly in XmlSpy, the unit test was failing.
The hint was in the error message "The underlying connection was closed: An unexpected error occurred on a send.". Once I asked the host to enable logging the problem went away. Most odd.


text:
Q: How can I get the connection string to a database hosted Azure in the appsettings.json file? I have created a database and hosted it in Microsoft Azure. I am struggle to connect to the database because I do not have the connection. Where can I get the connection string?
I have tired to find the connection on the Azure platform under the Azure databases that I have created and I was expecting to be able to access the data stored in the database.

A: Connect to Azure and create an SQL Server and database.

*

**Select the connection string of that particular database in the left pane as shown below and choose connection strings as highlighted .

*The below highlighted string need to be used in the appsettings.json to communicate with database of the azure.

**Use the connection string in the appsettings.jsonfile as shown below.


text:
Q: Become friendly after being discovered as a werewolf Recently, I was playing The Elder Scrolls V: Skyrim vanilla on xbox 360, and while I was playing, I turned into a werewolf in front of people in Riverwood and it caused them to become hostile.
I don't want to kill them. How can I make them friendly again without loading the last save? A lot of my precious items would disappear if I load the last save game.

A: Transforming into a werewolf is a crime like any other; it has no lasting consequences and can be paid off in the same way: either by paying your bounty, or by serving jail time.


text:
Q: Linux dynamic and static linking I have an executable that linked with shared library 'A' , which in turn uses shared library 'B' (GUI written in Qt).
When i compile the executable, the linker looks for all the libraries, including 'B', and all libraries it needs inside (Qt libraries).
How can i disconnect the 'B' library from the executable in such way that it will not need the 'B' in the link time.
I'd like that the executable will not know about the 'B' library.

A: Assuming you can build dependency 'B' from source, you can hide it from your executable by linking 'A' statically to 'B'.
In the case of not being able to compile 'B' from source, it's possible to limit visibility of symbols in 'B' that are not explicitly used. You can accomplish this via the 'ld' command on Unix systems. I know very little about this. This post may offer some suggestions. However, they strike me as very explicit and manual, so probably less applicable if 'B' is a large library with many symbols. I suspect that's not really what you were going for.
You want 'B' to not show up when calling the 'ldd' command on your executable. Is that right?
Or are you only trying to make the installation of your executable easier on users? If yes, you can still automate the installation to some extent.


text:
Q: I want to add a relation in my charm for MySQL db and create some tables using my charm I have a charm XYZ. I want to add a relation between my charm & MySQL service and Create some tables in database, For doing that I am adding a hook for relation-join in my charm. I am not sure how to access mysql form my charm and create tables in MySQL database using my relation-join hook charm.
My charm code is in Python.

A: Your relation-join hook can get some useful information from the Mysql service - a username and password. You also have the server address, so your XYZ charm can use this info to make SQL calls to the database. You may want to check out a pyhton library for mysql.
http://zetcode.com/db/mysqlpython/


text:
Q: How to add icons to drawer items using react-navigation? None of the other questions/answers related to adding icons to drawer items have worked.
Goal: use an image component as the drawer item's icon
Problem: using answers supplied to other questions doesn't work. I get Reference Error: React is not Defined. The error is located at DrawerNavigatorItems at line {drawerIcon}
DrawerNavigator route config code:
const drawerRouteConfig = {
    Inbox: {
        screen: InboxStack,
        navigationOptions: {
            drawerIcon: () => (
                <Image
                    source={require('../assets/img/white-inbox.png')}
                    style={{ height: width * 0.05, width: width * 0.05 }}
                    resizeMode={'contain'}
                />
            )
        }
    },
    Discover: DiscoverStack,
    Account: AccountStack,

};

How do I properly implement drawerItem icons?

A: My problem was that I hadn't imported React.
fix: import React from 'react'


text:
Q: How to create DataFrame from fixed-length text file given field lengths? I am reading fixed positional file. Final result of file is stored in string. I would like to convert string into a DataFrame to process further. Kindly help me on this. Below is my code:
Input data:
+---------+----------------------+
|PRGREFNBR|value                 |
+---------+----------------------+
|01       |11 apple     TRUE 0.56|
|02       |12 pear      FALSE1.34|
|03       |13 raspberry TRUE 2.43|
|04       |14 plum      TRUE  .31|
|05       |15 cherry    TRUE 1.4 |
+---------+----------------------+
data position: "3,10,5,4"
expected result with default header in data frame:
+-----+-----+----------+-----+-----+
|SeqNo|col_0|     col_1|col_2|col_3|
+-----+-----+----------+-----+-----+
| 01  |  11 |apple     |TRUE | 0.56|
| 02  |  12 |pear      |FALSE| 1.34|
| 03  |  13 |raspberry |TRUE | 2.43|
| 04  |  14 |plum      |TRUE | 1.31|
| 05  |  15 |cherry    |TRUE | 1.4 |
+-----+-----+----------+-----+-----+

A: Given the fixed-position file (say input.txt):
11 apple     TRUE 0.56

12 pear      FALSE1.34

13 raspberry TRUE 2.43

14 plum      TRUE 1.31

15 cherry    TRUE 1.4

and the length of every field in the input file as (say lengths):
3,10,5,4

you could create a DataFrame as follows:
// Read the text file as is
// and filter out empty lines
val lines = spark.read.textFile("input.txt").filter(!_.isEmpty)

// define a helper function to do the split per fixed lengths
// Home exercise: should be part of a case class that describes the schema
def parseLinePerFixedLengths(line: String, lengths: Seq[Int]): Seq[String] = {
  lengths.indices.foldLeft((line, Array.empty[String])) { case ((rem, fields), idx) =>
    val len = lengths(idx)
    val fld = rem.take(len)
    (rem.drop(len), fields :+ fld)
  }._2
}

// Split the lines using parseLinePerFixedLengths method
val lengths = Seq(3,10,5,4)
val fields = lines.
  map(parseLinePerFixedLengths(_, lengths)).
  withColumnRenamed("value", "fields") // <-- it'd be unnecessary if a case class were used
scala> fields.show(truncate = false)
+------------------------------+
|fields                        |
+------------------------------+
|[11 , apple     , TRUE , 0.56]|
|[12 , pear      , FALSE, 1.34]|
|[13 , raspberry , TRUE , 2.43]|
|[14 , plum      , TRUE , 1.31]|
|[15 , cherry    , TRUE , 1.4 ]|
+------------------------------+

That's what you may have had already so let's unroll/destructure the nested sequence of fields into columns
val answer = lengths.indices.foldLeft(fields) { case (result, idx) =>
  result.withColumn(s"col_$idx", $"fields".getItem(idx))
}
// drop the unnecessary/interim column
scala> answer.drop("fields").show
+-----+----------+-----+-----+
|col_0|     col_1|col_2|col_3|
+-----+----------+-----+-----+
|  11 |apple     |TRUE | 0.56|
|  12 |pear      |FALSE| 1.34|
|  13 |raspberry |TRUE | 2.43|
|  14 |plum      |TRUE | 1.31|
|  15 |cherry    |TRUE | 1.4 |
+-----+----------+-----+-----+

Done!


text:
Q: One more releasing and acquiring locks make performance worse unexpectedly My program has 8 writing threads and one persistence thread. The following code is the core of the persistence thread
    std::string longLine;
    myMutex.lock();
    while (!myQueue.empty()) {
        std::string& head = myQueue.front();
        const int hSize = head.size();
        if(hSize < blockMaxSize)
            break;
        longLine += head;
        myQueue.pop_front();
    }
    myMutex.unlock();
    flushToFile(longLine);

The performance is acceptable (millions of writings finished in hundreds of milliseconds). I still hope to improve the code by avoiding string copying so that I change the code as followed:
    myMutex.lock();
    while (!myQueue.empty()) {
        const int hsize = myQueu.front().size();
        if(hsize < blockMaxSize)
            break;

        std::string head{std::move(myQueue.front())};
        myQueue.pop_front();
        myMutex.unlock();

        flushToFile(head);
        myMutex.lock();
    }
    myMutex.unlock();

It is surprising that the performance drops sharply to millions of writings finished in quite a few seconds. Debugging shows most of time was spent on waiting for the lock after flushing the file.
But I don't understand why. Any one could help?
Not understand more time spent on wait for the lock

A: Possibly faster. Do all your string concatenations inside the flush function. That way your string concatenation won't block the writer threads trying to append to the queue. This is possibly a micro-optimization.
While we're at it. Let's establish that myQueue is a vector and not a queue or list class. This will be faster since the only operations on the collection are an append or total erase.
std::string longLine;
std::vector<std::string> tempQueue;
myMutex.lock();
if (myQueue.size() >= blockMaxSize) {
    tempQueue = std::move(myQueue);
    myQueue = {};  // not sure if this is needed
}
myMutex.unlock();
flushToFileWithQueue(tempQueue);

Where flushToFileWithQueue is this:
void flushToFileWithQueue(std::vector<std::string>& queue) {
    string longLine;
    for (size_t i = 0; i < queue.size(); i++) {
        longline += queue[i];
    }
    queue.resize(0);  // faster than calling .pop() N times
    flushToFile(longLine);
}

You didn't show what wakes up the persistence thread.  If it's polling instead of using a proper condition variable, let me know and I'll show you how to use that.
Also make use of the .reserve() method on these instances of the vector collection such that all the queue has all the memory it needs to grow. Again, possibly a micro-optimization.


text:
Q: CSS3 animation, stay put I'm using the following animation:
.wheel1anim {
    -webkit-animation-name: wheel1go;
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-direction: normal;
    -webkit-animation-delay: 0;
    -webkit-animation-play-state: running;
    -webkit-animation-duration: 1s;
}

@-webkit-keyframes wheel1go {
    0% {
    }
    100% {
        -webkit-transform: translate(200px, 150px);
    }
}

The animation works fine, but once the animation is finished, the element moves from the place it was animated to, to its default position
Is there a way to make it stay in place?

A: You can add one line in .wheel1anim:
-webkit-animation-fill-mode:both;


text:
Q: listing the data from two table I have two tables staffdetails and worklog with staff's start time and finish time. I am looking for a result that lists some staff they are not started work when executing this SQL please refer below example:
staffdetails table
stafid  staffname
100200  John
100201  Jenny
100203  Camas

Worklog table
stfid   startime   finishtime
100200  11.30 p.m  12.30 p.m
100201  10.00 a.m  10.30 a.m
100200  12.35 p.m  12.40. p.m
100200  12.45 p.m
100203  1.30 p.m   2.30 p.m
300200  10.0 p.m   6.00 p.m

The output
staffid   stafname
100203    Camas
100201    Jenny

A: select  *
from    staffdetails sd
where   not exists
        (
        select  *
        from    worklog w
        where   sd.stafid = w.stfid
                and starttime is not null
                and finishtime is null
        )


text:
Q: Connecting to Oracle User Schema Geodatabase using ArcObjects? I've set up an Oracle user Schema geodatabase and loaded some data into it. I now want to connect to it programmatically using ArcObjects, the problem is I don't see how. Where can I set the newly created schema name in my connection property set, or how do I change the schema value after I have connected? In ArcCatalog it is done in the Geodatabase connection properties window :

The code below works fine connecting to the default SDE schema. What do I have to change to connect to a user geodatabase? I have tried examining IDatabaseConnectionInfo2 and IWorkspaceProperties but I don't see where I can set or change the schema that is connected to.
 public static IWorkspace ConnectToTransactionalVersion(String dbclient, String dbConnProp, String user, String password, String database, String version, String authentication)
    {
        IPropertySet propertySet = new PropertySet();
        propertySet.SetProperty("DBCLIENT", dbclient);
        propertySet.SetProperty("DB_CONNECTION_PROPERTIES", dbConnProp);
        propertySet.SetProperty("DATABASE", database);
        propertySet.SetProperty("USER", user);
        propertySet.SetProperty("PASSWORD", password);
        propertySet.SetProperty("VERSION", version);
        propertySet.SetProperty("AUTHENTICATION_MODE", authentication);
        Type factoryType = Type.GetTypeFromProgID(
            "esriDataSourcesGDB.SdeWorkspaceFactory");
        IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance
            (factoryType);
        return workspaceFactory.Open(propertySet, 0);
    }

I tried adding "SCHEMA" as a property in propertySet and it gets ignored, I also tried setting the version property to the new user schema default version but it errors with "version not found"

A: Hy,
this code is working for me under Java:
 IPropertySet propertySet = new PropertySet();
 propertySet.setProperty("SERVER", "myserver");
 propertySet.setProperty("INSTANCE", "5151:ASSESSOR");
 propertySet.setProperty("DATABASE", "");
 propertySet.setProperty("USER", "myusername");
 propertySet.setProperty("PASSWORD", "mypassword");
 propertySet.setProperty("VERSION", "ASSESSOR.DEFAULT");
 IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactory();
 return (Workspace) workspaceFactory.open(propertySet, 0);

The only special is the INSTANCE and the VERSION which are containing user-schema related informations, in your case assessor.
new UPDATE:
Please find here the code for a user-schema geodatabase direct-connection:
  PropertySet propertySet = new PropertySet();
  propertySet.setProperty("INSTANCE", "sde:oracle:XE:DGP_OWNER");
  propertySet.setProperty("USER", "dgp_owner");
  propertySet.setProperty("PASSWORD", "xxxxxxx");
  propertySet.setProperty("VERSION", "DGP_OWNER.DEFAULT");
  workspace = workspaceFactory.open(propertySet, 0);

This code will connect to the user-schema DGP_OWNER geodatabase in the XE-named Oracle database.

A: Create a connection file (sde file) with ArcCatalog.
Solution 1: Use this connection file like in my example (first 7 lines). I think this is not that good, because you have to distribute the sde file, too.
Solution 2: Maybe you can make some kind of 'reverse engeneering'. In the example below (all lines) you could establish the connection to your workspace by the sde file and read the properties of this file. I hope you will find the missing parameter.
IWorkspaceFactory wsFactory = null;
IFeatureWorkspace featWs = null;
object names = null;
object values = null;
try
{
    wsFactory = new SdeWorkspaceFactoryClass();
    featWs = (IFeatureWorkspace)wsFactory.OpenFromFile(@"D:\Test.sde", 0);

    IWorkspace ws = featWs as IWorkspace;
    if (ws != null)
    {
        IPropertySet props = ws.ConnectionProperties;
        props.GetAllProperties(out names, out values);
    }
}
catch (Exception ex)
{
}


text:
Q: C++ socket programming: packing data from an array of different types I'm new to socket programming in C++, and while I do have the basics down, I'm having trouble tackling the following situation:
I have a function which consumes an array of void pointers (i.e. void **). Each pointer will be pointing to a different standard C data type (i.e. char, int, short, long, float, double). This array will be of variable length, but I will have access to its length and the type of data each pointer is pointing to.
The goal of this function is to send all the data pointed to by the pointers. My question is: is there a way to send this all in one go?
By the way, I do know that send() doesn't guarantee the delivery of every byte. I do have a helper function which loops and invokes send() as many times as needed. My question has to do with packing and serializing the data.
If I want to send an integer, I simply invoke htons() or htonl() in order to convert the data to network byte order.
If I want to send a variable length string, I simply send the length of the string first followed by the actual string. Easy enough.
But what if I want to send a variable amount of data, all in one go (assuming I have my helper to guarantee the delivery of every byte), where the data comes from an array of pointers to different C standard data types? Again, I know I'll want to send the length of the data first, which is no problem because I do know the length and the type of each pointer in the array. I just don't know how to pack it to ensure that it'll be in network byte order.


text:
Q: Filtering mysql results via select dropdown I'm a new member of StackOverflow, and although I've been using the website for a long time, it's my first time posting a question, in a hope that someone will be able to help me. I'll start by saying that my knowledge of PHP and MySQL is basic, but what I'm trying to do isn't too complex in my opinion, so hopefully I won't be asking for much. I've done a lot of prior research, but I just couldn't find the right answer.
In short, this is what I'm trying to do:
I've got an html form, which upon submission writes data to a database, and then publishes a table on a separate html page. With each successful submission a new table gets generated and published, while the old one gets pushed underneath. This all works fine, and I've also implemented pagination so that only 5 tables are visible per page.
What I'd like to be able to do is allow people to ONLY view/display results (tables) based on a specific criteria, in this case "rating", by selecting a rating from a drop-down on the page where tables are published. Rating is one of the fields in my form which gets submitted to a database and then published in one of the rows in a table.
Below is the code which publishes tables. Thanks in advance for your help!
<?php
include('dbconnect.php');

mysql_select_db("vtracker", $con);
$result  = mysql_query("SELECT * FROM userdata");
$age = "Age:";
$rating = "Rating:";
$country = "From:";
$name = "Name:";

        while($row = mysql_fetch_array($result))
        {

                        echo "
";
                        echo "
";
                        echo "
";
                        echo "" .$name . " " . $row['personsname'] . "	";
                        echo "";
                        echo "
" . $row['mft'] . "
";
                        echo "	";
                        echo "
";
                        echo "
";
                        echo "" . $country . " " . $row['nationality'] . "	";
                        echo "
";
                        echo "
";
                        echo "" . $age . " " . $row['personsage'] . "	";
                        echo "
";
                        echo "
";
                        echo "" . $rating . " " . $row['rating'] . "	";
                        echo "
";
                        echo "
";
                        echo "
";
                        echo "
";

        }
    ?>

A: for both true and false use can add thid in your code:
if($_POST['rating_dropdown']!='')
{
    $temp_rating = $_POST['rating_dropdown'];
    $query=mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
}
else
{
    $query=mysql_query("SELECT * FROM userdata");
}

A: Dunno if this works, it's just a hinch. haha.
It will see if the rating is true(not null), if it's true it will echo the results.
while($row = mysql_fetch_array($result))
{
if ($rating)
                echo "
";
                echo "
";
                echo "
";
                echo "" .$name . " " . $row['personsname'] . "	";
                echo "";
                echo "
" . $row['mft'] . "
";
                echo "	";
                echo "
";
                echo "
";
                echo "" . $country . " " . $row['nationality'] . "	";
                echo "
";
                echo "
";
                echo "" . $age . " " . $row['personsage'] . "	";
                echo "
";
                echo "
";
                echo "" . $rating . " " . $row['rating'] . "	";
                echo "
";
                echo "
";
                echo "
";
                echo "
";
}

}

A: Once the dropdown gets selected and posted to your display page, use this code:
$temp_rating = $_POST['rating_dropdown'];
mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");

Keep in mind, however, that you should be using PDO or mysqli extension, not the mysql extension. According to PHP's website:

This extension is deprecated as of PHP 5.5.0, and will be removed in
  the future. Instead, the MySQLi or PDO_MySQL extension should be used.
  See also MySQL: choosing an API guide and related FAQ for more
  information.


text:
Q: Passing string to input stream Someone wrote a class that I wish to test. It looks something like:
public class foo <E>{
     public static void main(String[] args){
         Scanner scan = new Scanner(System.in);
         do_stuff(scan.nextInt());
     }
}

I have another class which tries to test the above function's main method as follows:
public class Test{
   public static void main(String[] args){
        System.in.read("5".getBytes());
        foo.<Integer>main(new String[]{});
   }
}

Basically, I'm trying to use the Test class to feed input into the stream that will soon be read by the Scanner in foo. I cannot change foo at all, as it is someone else's code.
Why doesn't this work? What is the correct way to do this?

A: What your System.in.read("5".getBytes()) does is pass a byte array to the read method, which attempts to fill it with user input. It completely ignores the data you put in that byte array.
You have to call System.setIn() to change the stream connected to System.in:
System.setIn(new ByteArrayInputStream("5".getBytes()));
foo.<Integer>main(new String[]{});


text:
Q: How to play in any browser any video format for which codecs are installed in the system? I am developing a system, among the functions of which may be playing local video files of the user. User video files can be in any format.
There is an idea to use browser as a GUI for this system (In this case, the core of the system will work as a web server). The system itself is very similar to a social network, so the idea with a browser is very logical.
Unfortunately, the standard VIDEO tag does not support any formats, even if the corresponding video codecs are installed on the user's computer.
I need to understand: is there a way to get any browser to play any video? Since in any case there will be a client application, it is possible to install additional extensions for browsers, additional software etc. The main thing that it was a stable and working solution.

A: "is there a way to get any browser to play any video?"
Yes and no. No, you can not install new codecs and have the browser use it. The browser will only ever use codecs it comes with.
You could compile a tool like ffmpeg to wasm, and do software decoding, then render to a canvas. However this is a big legal problem and you would need to obtain licenses for dozens of codecs. Or risk lawsuits


text:
Q: PHP Loop through JSON to create a new array I am not sure why I am having such a hard time with this but I have some Decoded JSON and I want to loop through it to build a smaller array using some of the data.
Below is my JSON $jsonData:
{
  "resultsPage": {
    "results": {
      "event": [
        {
          "id":11129128,
          "type":"Concert",
          "uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
          "displayName":"Wild Flag at The Fillmore (April 18, 2012)",
          "start": {
            "time":"20:00:00",
            "date":"2012-04-18",
            "datetime":"2012-04-18T20:00:00-0800"
          },
       location": {
            "city":"Chicago, IL, US",
            "lng":-134.903409,
            "lat":37.7842398
          },
          "venue": {
            "id":6239,
            "displayName":"The Fillmore",
            "uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
            "lng":-122.4332937,
            "lat":37.7842398,
            "metroArea": {
              "id":26330,
              "uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
              "displayName":"SF Bay Area",
              "country": { "displayName":"US" },
              "state": { "displayName":"CA" }
            }
          },
          "status":"ok",
          "popularity":0.012763
        },
        {
          "id":7923094,
          "type":"Concert",
          "uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
          "displayName":"Wild Flag at The Fillmore (April 18, 2012)",
          "start": {
            "time":"20:00:00",
            "date":"2012-04-18",
            "datetime":"2012-04-18T20:00:00-0800"
          },
       location": {
            "city":"New York, NY, US",
            "lng":63.902374,
            "lat":49.7842328
          },
          "venue": {
            "id":6239,
            "displayName":"The Fillmore",
            "uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
            "lng":-122.4332937,
            "lat":37.7842398,
            "metroArea": {
              "id":26330,
              "uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
              "displayName":"SF Bay Area",
              "country": { "displayName":"US" },
              "state": { "displayName":"CA" }
            }
          },
          "status":"ok",
          "popularity":0.012763
        },

        {
          "id":89763146,
          "type":"Concert",
          "uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
          "displayName":"Wild Flag at The Fillmore (April 18, 2012)",
          "start": {
            "time":"20:00:00",
            "date":"2012-04-18",
            "datetime":"2012-04-18T20:00:00-0800"
          },
       location": {
            "city":"Miami, FL, US",
            "lng":42.1238243,
            "lat":50.7289731
          },
          "venue": {
            "id":6239,
            "displayName":"The Fillmore",
            "uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
            "lng":-122.4332937,
            "lat":37.7842398,
            "metroArea": {
              "id":26330,
              "uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
              "displayName":"SF Bay Area",
              "country": { "displayName":"US" },
              "state": { "displayName":"CA" }
            }
          },
          "status":"ok",
          "popularity":0.012763
        }
      ]
    },
    "totalEntries":24,
    "perPage":50,
    "page":1,
    "status":"ok"
  }
}

Below is my first try at looping through the JSON variable and parsing out the data I want into a new array. I am not sure if I should use push or if there is a more effiecent way to parse the data I want into a new array:
$newArray = array();

foreach($jsonData['resultsPage']['results']['event'] as $val){

$newArray .= "{'id' => $val['id'], 'long' => $val['location']['lng'], 'lat' => $val['location']['lat']}"

}

A: Try this:
$jsondata_array = json_decode($jsonData, true);

$new_required_arr = $jsondata_array['resultsPage']['results']['event'];

foreach($new_required_arr as $key => $val)
{
  //Your logic to create new array with required key value pair.
}

A: The provided JSON format is wrong, the index location missing the double quote at the beginning.
To parse the JSON , you can convert JSON to array and loop through the array to apply your logic OR build new array, you can use json_decode with true parameter.
$arr = json_decode($json, true);
foreach($arr as $k => $v){
  //Your logic
}

A: The problem with you loop is when the element don't exist you get an error because you try to access an element in your array which doesn't exist.
foreach($jsonData as $val) {
}

Then you can work insight with your values and you should check them with isset. Or you make an if statement around your loop to prevent it that problem.
The next problem is that you define $newArray as an array. But the . is to concat a string. So you should define your initial variable like this:
$newArray = '';

The last thing is i can't see it in your code but to parse a json string you have to use json_decode first. To get an object. If you want an array you have to set the second parameter to true.
$arr = json_decode($myjson, true);


text:
Q: Is this a glitch or a problem with my computer? I installed XCom a while ago and something horrible happened. When I changed my point of view by pressing the Q button, and then I move one of my soldiers, my screen froze and I had to force-shut-it-down in order to allow it to recover. I have been using this same computer for the past year and this never happened before.

A: Sounds like a problem with your graphics card. What graphic card does your computer have?
Try to install the most up to date graphic driver, that may solve the problem


text:
Q: Spring Boot - Rest templates seems to ignore accept header set through the HttpEntity I am making a call to one of the Jasper server API endpoints and I have to set the header "Accept" to "application/json" for the service to return a JSON response. I have validated the API from Postman -

When I try to simulate the same behavior from my Spring Boot rest client, I try to set the accept header to 'application/json' but Spring seems to ignore the same and adds the accept header as shown below -

I have validated the same by enabling DEBUG for rest template using the following parameter -
logging.level.org.springframework.web.client.RestTemplate=DEBUG
Below is the code snippet for my rest client -
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBasicAuth(serviceUsername, servicePassword, StandardCharsets.UTF_8);

ResponseEntity<String> response = null;

String url = serviceEndpoint + "?reportUnitURI="
                    + URLEncoder.encode(reportPath, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20")
                    + "&label=" + URLEncoder.encode(label, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
            LOGGER.info("URL : " + url);

HttpEntity<String> requestEntity = new HttpEntity<String>("",
                    headers);

response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

*

*Can someone please help explain the behavior here?

*Why does my header values for 'accept' gets ignored?

*What could be done to pass the 'accept' header properly?

A: Even though the code sets the accept header, the HttpMessageConverter used my scenario (StringHttpMessageConverter) does not allow changes on the accept headers and maintains the default values.
To get past that I have modified the StringHttpMessageConverter behavior at runtime to allow setting the preferred accept header.
@Bean
public RestTemplate getRestTemplate() {
    final RestTemplate restTemplate = new RestTemplate();
    final List<HttpMessageConverter<?>> converters = new ArrayList<>();

    for (HttpMessageConverter converter : restTemplate.getMessageConverters()) {
         if (converter instanceof StringHttpMessageConverter) {
             ((StringHttpMessageConverter) converter).setWriteAcceptCharset(true);
             ((StringHttpMessageConverter) converter).setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
             converters.add(converter);
         }
     }

    restTemplate.setMessageConverters(converters);
    return restTemplate;
}

Now, the framework allows my REST client to modify the header, code snippet below -
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setBasicAuth(serviceUsername, new String(new DecryptionService().decrypt(servicePassword)), StandardCharsets.UTF_8);

ResponseEntity<String> response = null;

try {
    String url = serviceEndpoint + "?reportUnitURI=" + reportPath + "&label=" + processLabel(label, false);
    HttpEntity<String> requestEntity = new HttpEntity<String>("",
                    headers);

    response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
    //more stuff


text:
Q: Putting changelists on another perforce machine I did a migration of the perforce server. Because there are many depots and many data and because our department does not want that the server is down for a day, I did the following:
Step 2 : Stop the 'old' perforce server on machine A
Step 1 : Copy all data from machine A to machine B
Step 2 : Start again the 'old' server
Setp 3 : Do the complete migration and start the new server at machine B
Now the problem is that in the meanwile, there are several changelists submitted to machine A.
Is there an easy way to copy the changes to machine B ? Note that I have a checkpoint, so the metadata is not the problem.
I know that on version controls like git it is easy with patches. Is such a thing also possible in perforce in an easy way?

A: You may want to look at p4 pull and p4 replicate command given by perforce.
P4 Pull and P4 Replicate are the 2 commands given for purpose like these. I am assuming that your p4 server is p4d 2010.2 or above for these commands.
Also, I would recommend you reading Perforce's knowledge base for their article on Offline check pointing. This article is not a direct solution to your problem, but it gives you insight of how you may tackle your situation.
Hope this helps.

A: Did you truncate your journal when you did the first migration?  If so, you can probably replay the latest production journal and then rsync/robocopy the archive content (files in the depots).  That'll let you catch up.
I assume this is a one-off activity?
You should probably check in with Perforce tech support just to make sure you're not overlooking anything.


text:
Q: OpenGL on Mac operation This is really architecture question or 'how does it work' question than a problem to solve.
Apple documentation claims that CGL is lowest level api for managing OpenGL contexts, yet is lacks functionality that allows to connect a context to a window.
AGL and Cocoa can bind a context to a window without a problem though, so the question is - how do they do that if they are built upon CGL?
The obvious way appears to be that they use CGL to render to offscreen memory and are then capable of compositing this somehow. If this is so, how does that happen?

A: There is a private function CGLSetSurface that connects a surface that is part of a window to a GL context created with CGLCreateContext. Both AGL and Cocoa use this function internally.

A: Complete example:
/*
mkdir -p build/test.app/Contents/MacOS
clang++ --std=c++11
 -fno-exceptions
 -fno-rtti
 -mmacosx-version-min=10.9
 -Wno-writable-strings
 -Wno-deprecated-declarations
 -framework OpenGL
 -framework Carbon
 -g gui8.cpp
 -o build/test.app/Contents/MacOS/test

 */

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#include <OpenGL/CGLTypes.h>
#include <OpenGL/CGLCurrent.h>
#include <OpenGL/OpenGL.h>
#include <OpenGL/gl.h>

typedef int CGSConnectionID;
typedef int CGSWindowID;
typedef int CGSSurfaceID;

typedef uint32_t _CGWindowID;

extern "C" {

typedef int CGSConnection;
typedef int CGSWindow;
typedef int CGSValue;

typedef enum _CGSWindowOrderingMode {
   kCGSOrderAbove                =  1, // Window is ordered above target.
   kCGSOrderBelow                = -1, // Window is ordered below target.
   kCGSOrderOut                  =  0  // Window is removed from the on-screen window list.
} CGSWindowOrderingMode;

typedef void *CGSRegion;
typedef CGSRegion *CGSRegionRef;
typedef CGSWindow *CGSWindowRef;

extern CGError CGSNewWindow( CGSConnection cid, int, float, float, const CGSRegion, CGSWindowRef);
extern CGError CGSNewRegionWithRect( const CGRect * rect, CGSRegionRef newRegion );
extern OSStatus CGSOrderWindow(CGSConnection cid, CGSWindow win, CGSWindowOrderingMode place, CGSWindow relativeToWindow /* nullable */);
extern OSStatus CGSSetWindowProperty(const CGSConnection cid, CGSWindow wid, CGSValue key, CGSValue value);
extern CGSConnectionID CGSMainConnectionID(void);
extern CGError CGSAddSurface(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID *sid);
extern CGError CGSSetSurfaceBounds(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID sid, CGRect rect);
extern CGError CGSOrderSurface(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID sid, int a, int b);
extern OSStatus CGSMoveWindow(const CGSConnection cid, const CGSWindow wid, CGPoint *point);
extern CGLError CGLSetSurface(CGLContextObj gl, CGSConnectionID cid, CGSWindowID wid, CGSSurfaceID sid);

}
#define kCGSBufferedBackingType 2

int main () {

    CGLContextObj cgl_context = NULL;
    CGSWindow window = 0;

    int width = 500, height = 500;
    CGPoint window_pos = { .x = 200, .y = 200 };
    bool quit = false;

    CGSConnectionID connection_id = CGSMainConnectionID();
    assert(connection_id);

    {

        CGSRegion region = NULL;
        CGRect r = CGRectMake(0,0, width, height);
        auto err1 = CGSNewRegionWithRect(&r, &region);
        assert(region);
        auto err2 = CGSNewWindow(connection_id, kCGSBufferedBackingType, window_pos.x, window_pos.y, region, &window);
        assert(window);
        auto err3 = CGSOrderWindow(connection_id, window, kCGSOrderAbove, 0);
        assert (err3 == kCGErrorSuccess);

        CGLPixelFormatAttribute attributes[] = {
            kCGLPFADoubleBuffer,
            kCGLPFAAccelerated, // Hardware rendering
            // kCGLPFARendererID, (CGLPixelFormatAttribute) kCGLRendererGenericFloatID, // Software rendering
            (CGLPixelFormatAttribute)0
        };

        CGLPixelFormatObj pix;
        GLint num;
        auto err4 = CGLChoosePixelFormat(attributes, &pix, &num);
        assert(err4 == kCGLNoError); // CGLErrorString(err1)
        assert(pix);

        CGLCreateContext(pix, NULL, &cgl_context);
        assert(cgl_context);
        CGLDestroyPixelFormat(pix);
        CGLSetCurrentContext(cgl_context);

        GLint v_sync_enabled = 1;
        CGLSetParameter(cgl_context, kCGLCPSwapInterval, &v_sync_enabled);

        CGSSurfaceID surface_id = 0;
        auto err5 = CGSAddSurface(connection_id, window, &surface_id);
        assert(err5 == kCGErrorSuccess);
        auto err6 = CGSSetSurfaceBounds(connection_id, window, surface_id, CGRectMake(0, 0, width, height));
        assert(err6 == kCGErrorSuccess);
        auto err7 = CGSOrderSurface(connection_id, window, surface_id, 1, 0);
        assert(err7 == kCGErrorSuccess);

        auto err8 = CGLSetSurface(cgl_context, connection_id, window, surface_id);
        assert(err8 == kCGLNoError);

        GLint drawable = 0;
        CGLGetParameter(cgl_context, kCGLCPHasDrawable, &drawable);
        assert(drawable == 1);

    }

    assert(glGetError() == GL_NO_ERROR);

    CGPoint drag_starting_position;
    bool drag_started = false;
    while (!quit) {

        glClearColor(1,1,0,1);
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        static float a = 0;
        glRotatef(a * 1000, 0, 0, 1);
        // printf("a: %f\n", a);
        a= a + .001;
        glBegin(GL_QUADS);
        if (a>1.5) a=0;
        glColor4f(0,a,1,1);
        glVertex2f(0.25, 0.25);
        glVertex2f(0.75, 0.25);
        glVertex2f(0.75, 0.75);
        glVertex2f(0.25, 0.75);
        glEnd();

        auto err1 = CGLFlushDrawable(cgl_context);
        assert(err1 == kCGLNoError);

        assert(glGetError() == GL_NO_ERROR);

    }

    CGLSetCurrentContext(NULL);
    CGLDestroyContext(cgl_context);

}

A: I didn't revisit the question ever since, this is what I was able to make out of it:
The undocumented api's that float around the net appear to be a missing block from all that - I was able to CGLSetSurface without it returning an error, however it didn't do all that much in the end. Apparently there is some other stuff that needs to be done to make everything work on such a low level.
In all, there doesn't appear to be a sane way to control everything through CGL. The way to handle everything is like everyone else is doing apparently - through Cocoa classes (using CGL for all the stuff other then attaching to window is fine though after that point).


text:
Q: persistence issue with multiple @oneToMany associations in a single class with different classes I have two @OneToMany annotations in a single class. It works fine when i am persisting address but for the order i am getting an error with the sql.
I saw a solution where they said to use set and trying that also did not help.
@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer customerId;

    @OneToMany(fetch=FetchType.LAZY,  mappedBy="customer", cascade=CascadeType.ALL)
    private Set<Order> order;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade=CascadeType.ALL)
    private Set<Address> address;

    public Set<Order> getOrder() {
        return order;
    }

    public Set<Address> getAddress() {
        return address;
    }
public void addAddress(Address tempAddress) {
        if(address == null) {
            address = new HashSet<>();
        }
        address.add(tempAddress);
        tempAddress.setCustomer(this);
    }

    public void addOrder(Order theOrder) {
        if(order == null) {
            order = new HashSet<>();
        }
        order.add(theOrder);
        theOrder.setCustomer(this);
    }
}

here is@ManyToOne from other side of the relationship
@Entity
public class Address {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer addressId;

    private String state;
    @ManyToOne(fetch=FetchType.LAZY,cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH} )
    @JoinColumn(name="customer_id")
    private Customer customer;
}

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer orderI;

    @ManyToOne(fetch=FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="customer_id")
    private Customer customer;
}

When I am persisting address it works fine but when it comes to persisting order I am getting following error:
Hibernate: select customer0_.customer_id as customer1_1_0_, customer0_.contact_number as contact_2_1_0_, customer0_.email as email3_1_0_, customer0_.first_name as first_na4_1_0_, customer0_.last_name as last_nam5_1_0_, customer0_.password as password6_1_0_ from customer customer0_ where customer0_.customer_id=?
Hibernate: select order0_.customer_id as customer4_3_0_, order0_.order_id as order_id1_3_0_, order0_.order_id as order_id1_3_1_, order0_.customer_id as customer4_3_1_, order0_.order_description as order_de2_3_1_, order0_.order_total as order_to3_3_1_ from order order0_ where order0_.customer_id=?
2019-06-09 15:57:56.456  WARN 55268 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1064, SQLState: 42000
2019-06-09 15:57:56.457 ERROR 55268 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order order0_ where order0_.customer_id=1' at line 1
2019-06-09 15:57:56.479 ERROR 55268 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order order0_ where order0_.customer_id=1' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:970) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1020) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.2.0.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:419) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:191) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:121) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:691) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:75) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2245) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:585) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:263) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:581) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:148) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection$3.doWork(AbstractPersistentCollection.java:340) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection$3.doWork(AbstractPersistentCollection.java:328) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:263) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.readElementExistence(AbstractPersistentCollection.java:327) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.collection.internal.PersistentSet.add(PersistentSet.java:208) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at com.spring.ctech.shopease.entity.Customer.addOrder(Customer.java:117) ~[classes/:na]
    at com.spring.ctech.shopease.service.OrderService.createOrder(OrderService.java:22) ~[classes/:na]
    at com.spring.ctech.shopease.controller.OrderController.createOrder(OrderController.java:25) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]

A: Order is a reserved SQL keyword.
You shouldn't name entities with names that are used by SQL.
Simply rename the Order entity and table


text:
Q: accesing function of an object stored in vector If I would have an object that is basically a vector container looking like this:
std::vector<Base*> programs; //let's say in header file vector container would be defined like this

Box::box{
Base * a = new derived1(100);
Base * b = new derived2(100);
programs.push_back(a);
programs.push_back(b);
};//and it goes on, etc.

and when i create in main:
Box *ptr = new Box;

Then i wonder how can i access a public function that is a member of, let's say class derived1? Is it even possible?


text:
Q: How call process works with blue tooth devices? I tested few things on Android mobiles with bluetooth headset.I have few questions regarding the same.
Device Specifications :
Android 2.3 above
Headset Blue tooth profiles : HFP,A2DP
I accepted a call from accept button from the android mobile and I was able to hear the call from the bluetooth headset.After that I moved android device out of range and accepted the call from android and when the android mobile entered bluetooth range bluetooth headset connected automatically.Is it universal, I mean all the bluetooth headsets support the same or are there any deviations?
I would like to know what will happen when we accept the call from headset or Android mobile.Is it something like Android OS is going to create a call session/audio session and transfer this to headset when accept button is pressed from the headset.If a call is already received and when the headset is in bluetooth range,Android mobile is going to route the volume to headset. In both the cases the same thing happens(just routing the audio).I would like to know the call handling in detail both the cases.Could some one help me on this.
How the call process is different in iOS?
Edit
Is any call session like AVAudoioSession is getting created when we accept a call ?
@jjv360:
"An app can manually assign a route even though a bluetooth headset is connected, in which case it's up to the app to handle what happens when a new route is detected..."
Is it possible to route the call session to headset(from microphone to headset sco) in an iOS app?Could you please give some pointers on this.

A: On iOS if you connect a bluetooth headset while an audio session is active the current audio app(s) get notified and by default will transfer the session's route to the headset. An app can manually assign a route even though a bluetooth headset is connected, in which case it's up to the app to handle what happens when a new route is detected...
Also, AFAIK the reconnect is attempted by both the device (for a very short time) and the headsets, so it's mainly up to the headset to attempt reconnecting when it goes out of range. Almost all headsets should do this though.
It doesn't matter which button was used to accept the call (on device or on headset), if the bluetooth headset is connected it will be used, unless an app has specified that it doesn't want to use that route.
The call process AFAIK is the same for Android and iOS.
With the protocol used, A2DP is the high-quality protocol used when listening to music. It supports high-quality audio, but is one-way, so only works if the bluetooth headset is not recording from the mic. HFP is used when recording is also needed, but the quality is less. That is why you will notice on iOS if you're listening to music on bluetooth headset and then start a recording app, the sound quality will become worse until you stop the recording...


text:
Q: Bootstrap form inline make input full width

    1.

    <input type="text" className="form-control" />

Using bootstrap, why when I do input 100% the form will break?
https://jsfiddle.net/bdw9eyme/
How to make label and input to be at same line and input will fill the rest of the screen?

A: You shouldn't use a br to create a break here, you can use CSS for that. Also you should either nest your input in the label, or use the for attribute with the label to link to an id on the input.
Making the row flex with the input set to flex-grow: 1 will put the input by the label text, and make the input grow to take up the available space.

input {
  flex-grow: 1;
  margin-left: 1em;
}
.fw {
  display: flex;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.8.0/bootstrap-table.min.css" rel="stylesheet"/>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

  1. <input type="text" className="form-control">

A: i think this is what you're looking for

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  1.

  <input class="form-control" type="text"/>


text:
Q: HTTP Proxy Server keep-alive connection support I am currently working on a multi threaded proxy server that supports keep-alive connections. I see some weird issues while handling requests from firefox browser. I connect to my local proxy using localhost:10001/http://url, and I can access all the links on this host. The process is as below.
1. Create a socket bind it to port 10001
2. Accept connections and if a client is connected fork()
3. Keep on processing the client request as persistent connection.
Now the problem is that when I open a new tab in firefox to access a second url with different host with using localhost:10001/http://url2, the strange thing is that that request goes to my client socket connection created during first connection. I initially thought that it might be due to my code, but then i tried to do the same using telnet and all the new connections would create a separate process. Are there any specific settings that is making firefox browser do this??

A: HTTP keep-alive is a way to reuse an underlying TCP connection for multiple requests so that one can skip the overhead of creating a new TCP connection all the time. Since the target of the connection is the same all the time in your case it makes sense for the browser to reuse the same TCP connection. The comparison with telnet is flawed since with telnet you do a new TCP connection all the time.
If HTTP keep-alive gets used is specified by the HTTP version the Connection header and on the behavior of both server and client. Both server and client can decide to close the idle connection any time after a request was done, i.e. they are not required to keep it open after the request is done. Additionally they can signal that they like to have the connection open by using the Connection: keep-alive HTTP header or that they like to close after the request with Connection: close. These headers have default values depending on the HTTP version, i.e. keep-alive is on with HTTP/1.1 while off with HTTP/1.0 unless explicitly specified.
Apart from that the "proxy" you are implementing with the use of URL's like http://proxy/real-url is not a real HTTP proxy. A real HTTP proxy would be configured as a proxy inside the browser and the URL's you use would stay the same which also means that no URL rewriting would need to be done by the proxy. Worse is that your idea of a proxy effectively merges all hosts inside the same origin (i.e. origin is the proxy) and thus effectively disables a major security concept of the browser: the same-origin policy. This means for example that some rogue advertisement server would share with your implementation the origin with ebay and thus could get access to the ebay cookies and hijack the session and misuse it for identity theft

A: HTTP persistent connection is also used with the proxy, not only with the destination.
For firefox you could try to alter the behavior with the proxy by setting network.http.proxy.version to 1.0. But you'll have to enhance your proxy (and perhaps rethink completely its inner workings) to be able to deal with these reused connections. I'm sure it's not limited to Firefox.
Also make sure your proxy doesn't answer with HTTP/1.1 because it's not.


text:
Q: Improper formatting with fillRect I want to make a background for a game I have created.
I'm having some issues with fillRect.
Does getHeight and getWidth have to be in a certain order or should getX/Y/Height/Width be used at all?
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    //Graphical loop start
    Rectangle rect = new Rectangle(0,0,1440,900) ;
    g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
    //Graphical loop end
}

A: Firstly, you are using the Graphics object instead of Graphics2D. You need to set the paint colour first then use the fill method.
g2d.setPaint(Color.BLUE);
g2d.fill(new Rectangle2D.Double(0, 0, screenWidth, screenHeight));

Rectangle2D constructor arguments are: x-coordinate of top-left, y-coordinate of top-left, width, height
It is good practice to use the Graphics2D.fill() method which will accept any object that implements the Shape interface. This makes it easier to change a shape to a different one should you decide to do so.


text:
Q: Having Access Violation error in VS2012 using openGL below is my code
#include <iostream>
#include <glew.h>
#include <freeglut.h>

enum VAO_IDs{triangles, numVAOs};

const GLuint vPosition=0;

GLuint VAOs[numVAOs];

const GLuint window_width=700;
const GLuint window_height=300;

void init(){
    glClearColor(7,7,9,0);
    /*generate vertex array object*/
    glGenVertexArrays(numVAOs, VAOs); // <- breakpoint
    /*bind vertex array object*/
    glBindVertexArray(VAOs[triangles]);
        //rest of code removed
}

void display(){
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();  //or glutSwapBuffers();
}

int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA);
    glutInitContextVersion(2,8);
    glutInitContextProfile(GLUT_DEBUG);
    glutInitWindowSize(window_width, window_height);
    glutCreateWindow("Hello world to openGL");

    /*init the glew libarary*/
    glewExperimental = GL_TRUE;
    GLenum error=glewInit();
    if(GLEW_OK != error)
        std::cout<<"Glew libraray not initialized"  <<std::endl;

    std::cout<<glGetString(GL_VERSION)<<std::endl;

    init();
    glutDisplayFunc(display);
    glutMainLoop();
}

i am currently running on openGL 2.1 and the important thing is that the code is working fine on linux....
all the required libraries are included and mentioned in the dependency settings...
i even tried the same program in code::blocks but the same error at the same point. As this code is running in linux so that means it's not the hardware problem. The problem is in windows OS but don't know where. I am stuck.. help!!
on windows i tried this code in VS2013 and code::blocks (but fail) and is working on linux
using code::blocks.
following are the screenshots of errors First-Chance exception and Unhandled Exception:

i was somehow able to ignore First-Chance exception but don't know how to manage Unhandled exception.


text:
Q: lapply function with arguments for dataframe and variable I have a custom function which summarises a variable. I simplified the function to illustrate my problem, i.e. it is more complex than shown below. Note that the general structure of the function should remain the same: It takes an argument for specifying which dataframe to work on (df), and an argument which variable to summarise (variable_to_test).
my_fun <- function(df, variable_to_test) {

  variable_to_test <- enquo(variable_to_test)
  new_var_name <- paste0(quo_name(variable_to_test), "_new_name")

  df %>%
    summarise(
      !!new_var_name := sum(!!variable_to_test, na.rm = TRUE)
    )
}

Using an example, I can apply the function on each variable in my dataframe:
library(tidyverse)
dat <- tibble(
  variable_1 = c(1:5, NA, NA, NA, NA, NA),
  variable_2 = c(NA, NA, NA, NA, NA, 11:15)
)

> my_fun(dat, variable_1)
# A tibble: 1 x 1
   variable_1_new_name
                 <int>
1                  15

> my_fun(dat, variable_2)
# A tibble: 1 x 1
  variable_2_new_name
                <int>
1                  65

But: how can I list apply the function on all columns in the dataframe? I tried
> dat %>%
+ lapply(., my_fun)
Error in duplicate(quo) : argument "quo" is missing, with no default
Called from: duplicate(quo)

but this returns an error. I'm struggling with the fact that the function takes an argument for both the dataframe to work on, and the variable to summarise. Note that I'd like to keep this structure - I find it more elegant to pass the name of the dataframe into the function instead of just giving the function the variable name and "hard-code" the data frame into the function body. Does anybody have a good idea how to lapply() the function?

A: Oh, I think you're just mapping over the wrong thing. For the tidyverse solution I would try:
map(dat, ~my_fun(dat, .))

What this does is map over the column names and plug in the column to the ..

A: You're working at the wrong level. If you map a function over a data frame, then this function should take a column. The problem here is that the function my_fun() expects a data frame rather than a column.
You need to find some other way of solving the problem. One solution is to use the mappers provided by dplyr:
dat %>%
  summarise_all(sum, na.rm = TRUE) %>%
  rename_all(paste0, "_new_name")

You could equivalently use a combination of map() and set_names() from purrr.
dat %>%
  map_df(sum, na.rm = TRUE) %>%
  set_names(paste0, "_new_name")


text:
Q: "Trying to get property of non-object" - from a CURL response so i get the json api response from a remote resource via CURL like this:
$curly = json_decode($output, true);

and then i pass it to the view building function like this:
return View::make('assman.index', $curly);

and then when i try to access a $curly attribute in the blade view like this:
... {{ $asses[0]->url }} ...

my happy ending looks like:
Trying to get property of non-object

A: so um.. I just needed to typecast the curl response:
$curly = (array)json_decode($output);

dammit.


text:
Q: Yii2 kartik DatePicker how to selected full week on click date I tried to move this code from example answer on question DatePicker Week number column to be clickable on selecting week  on Yii2 with kartik datepicker
but after run and selected date the week does not selected by clicking
<?php
use kartik\date\DatePicker;
use yii\web\JsExpression;

$this->registerJs(
    <<<JS
$(function(){
   var startDate;
   var endDate;

   var selectCurrentWeek = function() {
        window.setTimeout(function () {
            $('.datepicker').find('.ui-datepicker-current-day a').addClass('ui-state-active')

        }, 1);
    }
});
JS
);

echo DatePicker::widget(
    [
        'model' => $searchModel,
        'attribute' => 'period_start',
        'language' => 'en',
        'class' => 'datepicker',
        'type' => DatePicker::TYPE_INPUT,
        'pluginOptions' => [
            'calendarWeeks' => true,
            'autoclose' => true,
            'format' => 'yyyy-mm-dd',
            'updateViewDate' => false,
            'onSelect' => new JsExpression(
                'function(dateText, inst) {
                        var date = $(this).datepicker(\'getDate\');
                        startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
                        endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
                        var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
                        $(\'#startDate\').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
                        $(\'#endDate\').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));

                        selectCurrentWeek();
                        }
                '
            ),
            'beforeShowDay' => new JsExpression(
                'function (date) {
                        startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
                        endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
                        var cssClass = \'\';
                        if(date >= startDate && date <= endDate)
                        cssClass = \'ui-datepicker-current-day\';
                        return [true, cssClass];
                    }
                '
            )

        ]
    ]
);

A: The post you are referring to is using jQueryUI and you are trying to use that solution with kartik\date\DatePicker which uses Bootstrap Datepicker. So you need to be careful when using any yii extension by looking into the docs or guide.
Now about getting it to work, you can use the yii\jui\DatePicker .The latest jui datepicker does not have the autoclose option anymore and  provides you with the inline option which displays the datepicker inline and hides the field.
I will replicate the same example you referred to and you can see the whole week selected
<?php
use yii\helpers\Html;
// use kartik\date\DatePicker;
use yii\jui\DatePicker;
use yii\web\JsExpression;

$this->registerJs(
    <<<JS

   var startDate;
   var endDate;

   var selectCurrentWeek = function() {
        window.setTimeout(function () {
            console.log('called');
            $('.hasDatepicker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
        }, 1);
    }

JS
);
echo DatePicker::widget([
    'model' => $searchModel,
    'attribute' => 'period_start',
    'inline' => true,
    'clientOptions' => [
        'selectOtherMonths' => true,
        'onSelect' => new JsExpression(
            "function(dateText, inst) {
                var date = $(this).datepicker('getDate');
                startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
                endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
                var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
                selectCurrentWeek();
            }"
        ),
        'beforeShowDay' => new JsExpression(
            "function(date) {
                    var cssClass = '';
                    if(date >= startDate && date <= endDate)
                        cssClass = 'ui-datepicker-current-day';
                    return [true, cssClass];
                }"
        ),
        'onChangeMonthYear' => new JsExpression(
            "function(year, month, inst) {
                selectCurrentWeek();
            }"
        )
    ]

]);


text:
Q: Angular router-outlet chilld doesn't take all width I have a router outlet in a component. The child component doesn't take the whole width. I tried to give to the child's div width:100%, min-width:100%, also with !important, but it's not working. How can I force the child's div to take the whole width available?
Parent HTML:

          ...

            <router-outlet></router-outlet>

Parent CSS:
.navbar {
    padding-top: 40px;
    padding-right: 80px;
    border-top: none;
}

.mainDiv {
    width: 100%;
    border-top: none;
}

Child CSS:

...

A: Try set the router-outlet inside a div without using flex:

<router-outlet ></router-outlet>


text:
Q: Join multiple values from one column, selected from another table Given these simplified multiple choice tables where sometimes more than one answer is correct:
STUDENT_ANSWERS
AnswerID | StudentID | QuestionID | Answers
-------------------------------------------
       1 |         1 |          1 | C,D

QUESTION_ANSWERS
QuestionID | Answer | Text
-------------------------------------------------
         1 |      A | This is answer A
         1 |      B | B could also be correct
         1 |      C | Maybe it's C?
         1 |      D | Definitely D!

How do I do a select which translates the answers to their descriptions?
My start:
SELECT *
FROM STUDENT_ANSWERS sa
LEFT OUTER JOIN QUESTION_ANSWERS qa ON qa.Answer IN sa.Answers???
 -- Doesn't seem to work as IN requires a format of ('C','D') while I have 'C,D'

Desired output:
AnswerID | StudentID | QuestionID | AnswerDescriptions
-------------------------------------------
       1 |         1 |          1 | Maybe it's C?,Definitely D!

So the descriptions simply have to replace the codes instead of getting a single line for each answer.

A: Your problem is the structure of table STUDENT_ANSWERS. It should have one row per answer:

AnswerID | StudentID | QuestionID | Answer
-------------------------------------------
       1 |         1 |          1 | C
       2 |         1 |          1 | D

Now, assuming you can't do anything to change (read: fix) this, you can fudge it with appending a comma and using LIKE:
select *
from STUDENT_ANSWERS a
join QUESTION_ANSWERS q on ',' + a.Answers + ',' like '%,' + q.Answer + ',%'
    and a.QuestionID = q.QuestionID

SQL Fiddle demo
Note this assumes you will never ever have the text , in QUESTION_ANSWERS.Answer. It will also never be able to use an index, so it's going to be slower than slow.
And if you absolutely must format this in the database to be one line, you can use STUFF and the FOR XML PATH('') trick to concatenate the resulting rows.

A: This is full working example using only T-SQL statements. I will recommend to you to create separate function for splitting CSV that returns row set. Also, if you are working with huge amount of data, you may want to create a CLR function for splitting the values. Take a look to this article (there is everything you need).
DECLARE @StudentAnswers TABLE
(
     [AnswerID] INT
    ,[StudentID] INT
    ,[QuestionID] INT
    ,[Answers] VARCHAR(256)
);

DECLARE @QuestionAnswers TABLE
(
     [QuestionID] INT
    ,[Answer] CHAR
    ,[Text] VARCHAR(256)
);

INSERT INTO @StudentAnswers ([AnswerID], [StudentID], [QuestionID], [Answers])
VALUES (1, 1, 1, 'C,D')
      ,(2, 2, 1, 'A');

 INSERT INTO @QuestionAnswers ([QuestionID], [Answer], [Text])
 VALUES  (1, 'A', 'This is answer A')
        ,(1, 'B', 'B could also be correct')
        ,(1, 'C', 'Maybe it''s C?')
        ,(1, 'D', 'Definitely D!');

SELECT SA.[AnswerID]
      ,SA.[StudentID]
      ,SA.[QuestionID]
      ,T.c.value('.', 'CHAR')
      ,QA.[Text]
FROM @StudentAnswers SA
CROSS APPLY
(
    SELECT CAST('' + REPLACE([Answers], ',', '') + '' AS XML) Answers
) DS
CROSS APPLY DS.Answers.nodes('i') T(c)
INNER JOIN @QuestionAnswers QA
    ON SA.[QuestionID] = QA.[QuestionID]
    AND T.c.value('.', 'CHAR') = QA.[Answer];

A: Try this
select answerid,studentid,a.QuestionID,group_concat(b.text) from student_answers a left join QUESTION_ANSWERS b on b.questionid= a.questionid and  FIND_IN_SET(b.Answer, a.Answers)
group by a.questionid

Definitely it works.


text:
Q: Call a page function from usercontrol code I'm developing a C# and WPF app.
I have a WPF Page 'HomeView' with a UserControl 'CreateItem'. After I click a Button (which related function is Close()) inside the UserControl, I have to make the UserControl visibility collapsed and call a function 'ReloadAnalytics' in the Page code.
namespace iMP
{
    public partial class CreateItem : UserControl
    {

    public CreateItem()
    {
        InitializeComponent();
    }

    private void Close(object sender, RoutedEventArgs e)
    {
        HomeView objHomeView= new HomeView();
        objHomeView.CreateNewItemDisplayGrid.Visibility = Visibility.Collapsed;
        objHomeView.InitializeAnalyticsOverview();
    }
}

When I call this function, pressing the Button, nothing happens. (CreateNewItemDisplayGrid is the name of the UserControl in HomeView)
(HomeView namespace is iMP.Views and the public partial class is HomeView : Page)

A: Follow the structure below. I defined an event in usercontrol and use that event in the main form.
Try to match the code with your code
In UserControl
public partial class CreateItem : UserControl
{
    public event ClickEventHandler CloseButtonClick;
    public delegate void ClickEventHandler(object Sender, RoutedEventArgs e);
    public CreateItem()
    {
       InitializeComponent();
    }

    private void Close(object sender, RoutedEventArgs e)
    {
       if (CloseButtonClick != null)
       {
           CloseButtonClick(this, e);
       }
    }
}

In HomeView
public partial class HomeView : Page
{
   public HomeView()
   {
      InitializeComponent();
      CreateItem userControl = new CreateItem();
      this.Content = userControl;
      userControl.CloseButtonClick += UserControl_CloseButtonClick;
   }

   private void UserControl_CloseButtonClick(object Sender, RoutedEventArgs e)
   {
       ///...................................
       this.CreateNewItemDisplayGrid.Visibility = Visibility.Collapsed;
       ///.......................
   }
}


text:
Q: How can aborted builds be ignored concerning the Jenkins job status preview? For internal reasons, one of my jobs is able to run concurrently, but new builds abort themselves if another build is already running (disabling concurrency doesn't help, since I don't want new jobs to be scheduled for execution once the current build is done).
However, this behaviour is detrimental to the job status preview (the colored ball next to the job name when inside the job's parent folder). It often shows the status as "aborted", which is undesirable - I want to view the latest running build as the source of the job status.
I tried deleting aborted builds from within their own execution, but that's unfortunately neither trivial nor stable, and thus not suitable for this situation. I could probably get a workaround running that deletes them from a separate job, but that's not ideal either.
Anyway, I'm now hoping that I can just tell Jenkins to ignore "aborted" builds in the calculation of the job preview. Unfortunately, I wasn't able to find a setting or plugin that allows me to do this.
Is this possible at all? Or do I need to find another way?

A: Would something like this help?
https://plugins.jenkins.io/build-blocker-plugin/
I haven't used it myself but it supports blocking builds completely if a build is already running.


text:
Q: MapReduce WordCount with prop nouns I'm trying to make a MapReduce WordCount that get a large article and counts proper nouns.
Here's requirements:

*

*Starts with a capital letter and has never been found in the text with a small letter

*Has length between 2 and 7 letters

*Sort in descending order

Looks like a typical WordCount mapreduce, but I couldn't do this. How to get rid of all the punctuation marks? What's the right way to construct mapper and reducer?
import sys
import re

for line in sys.stdin:
    article_id, text = line.strip().split('\t', 1)
    text = re.sub('\W', ' ', text).split(' ')
    for word in text:
        if len(word) >= 2 and len(word) < 7:
            key = "".join(sorted(word.lower()))
            print("{}\t{}\t{}".format(key, word.lower(), 1))

A: If you are only looking for words, since you already imported re, you can use re.compile (one solution) :
re.compile('\w+').findall(text)

This way you remove all the punctuation in the string, keeping only letters and numbers.
If you take the string below :
text = "Looks like a typical WordCount mapreduce, but I couldn't do this. How to get rid of all the punctuation marks"

you quickly obtain :
liste = ['Looks', 'like', 'a', 'typical', 'WordCount', 'mapreduce', 'but', 'I', 'couldn', 't', 'do', 'this', 'How', 'to', 'get', 'rid', 'of', 'all', 'the', 'punctuation', 'marks']

On which you can run your for loop in the same way.


text:
Q: oci_fetch_array returns false $sql = 'SELECT * FROM reunion';
$stmt = oci_parse($conn, $sql);

oci_execute($stmt);

echo '<pre>';

echo 'Reached'; // works

while (($row = oci_fetch_array($stmt, OCI_BOTH)) != false) {
   print_r($row);  // prints nothing
}

echo '</pre>';
oci_commit($conn);
oci_close($conn);

The above code prints nothing ! I have tested the connection and the table contains rows.

A: According to the official docs, oci_fetch_array returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.