text:
Q: Codeigniter Session is not storing values when i redirect from login page to dashboard page We have developed school admission system, in that we store user id when user logs in the system, and then we redirect the user to dashboard page and in dashboard page we fetch values from user id this system works perfectly fine under my localhost but problem is on when i host on live server,
on live server when user logs in the system then user id getting stored in the session on login page (when i print values of session it displays id of user) but when it redirects to dashboard that value gets deleted,
see my login page code
<?php
class Login extends CI_Controller
{
    public function index()
    {
        $this->load->view('Login_v');
    }
    public function Login_user()
    {
        $uname=$_POST['username'];
        $pwd=$_POST['password'];
        $this->load->model('Login_m');
        $data=$this->Login_m->get_user($uname,$pwd);
        $this->load->library('session');
        if($data!=NULL)
        {
           $id=$data[0]->sid;
           $sdata=array('sid' => $id);
           $this->session->set_userdata($sdata);
                /* echo '';*/
                echo '';
            exit();
        } else {
            $data="Invalid Login Details";
            $this->load->view('Login_v',['data'=>$data]);
        }
    }
}
?>

This is my session array on login page when i print it
Array ( [__ci_last_regenerate] => 1511755625 [sid] => 1 )

and on dashboard page when i print it
Array ( [__ci_last_regenerate] => 1511755625)

Session/Cookie $config - application/config.php
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

$config['cookie_prefix'] = '';
$config['cookie_domain'] = '.cmsgroupnigdi.com/admission/';;
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;

A: Try with a session variable. Here I am using admin as session variable
In your login Page
$this->session->set_userdata('admin', $data);

instead of window.location you can use redirect()
redirect('admission/dashboard');

In your dashboard page
$admindata   = $this->session->userdata('admin');
print_r($admindata);

A: You are loading the session library just for login function. Try loading the session in the autoload.php file under config folder to get access everywhere in the system. Maybe that is the reason why you are unable to access.
$autoload['libraries'] = array('database','session');

Hope this can help you.

A: Mysteriously your code works... with some changes.
You still need to add in validation and other things, but this is more an exercise in debugging.
I did alter some things - Read through the code - to prevent some of your possible "next questions."
What I did was create a mock up of your script with added debugging.
So your "login" controller - Login.php
class Login extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('url');

        $this->load->model('login_m');
    }

    public function index() {
        $this->load->view('login_v');
    }

    public function Login_user() {
        // Debug - View Posted Data
        var_dump($_POST);

        // @todo Requires Validation
        $uname = $_POST['username'];
        $pwd = $_POST['password'];
        $data = $this->login_m->get_user($uname, $pwd);

        // Debug - Data from Model
        var_dump($data);

        if ($data != NULL) {
            $id = $data[0]->sid;
            $sdata = array('sid' => $id);
            $this->session->set_userdata($sdata);

            // Debug - View The Session data
            var_dump($this->session->userdata);
            // exit required to view the var_dump outputs
            // in this method so prevent the redirect
            // Comment it out to allow the redirect
            //exit();

            redirect("admission/dashboard");
            exit();
        } else {
            // Debug - View The Session data
            var_dump($this->session->userdata);

            $error_message = "Invalid Login Details";
            $this->session->set_flashdata('error_message',$error_message);
            redirect('login',$data);
        }

    }
}

The dummy model - Login_m.php
class Login_m extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Simulate a good and bad login.
     */
    public function get_user($uname, $pwd) {

        // use for successful login testing
        $return_array[]= (object)array('sid'=>1);

        // use for failed login testing
        $return_array = NULL;

        return $return_array;
    }
}

And the View - login_v.php ( Note: I made it lowercase )

This is the Login View

<?php
// $error_message isn't always passed in so we need to cater for that
$error_message = $this->session->flashdata('error_message');

if ( ! empty($error_message)): ?>

 <?= $error_message; ?>

<?php endif; ?>

<form action="login/login_user" method="POST">
    username
    <input type="text" name="username" value="">

    password
    <input type="password" name="password" value="">

    <input type="submit" name="check_login" value="Login">
</form>

There are many ways to do this. As noted, you need to perform validation etc but this is something to start with.

A: I was facing the same issue, probably check with your PHP version . Intially was using PHP version 7.1 and session was not working, was facing the same issue. After that when i changed to PHP version 7.0 it worked well.
If you could mention the PHP version what you are using. It would be helpful to solve.
If not please try to change your code igniter SYSTEM  folder with recent version. Possibly it would solve your issue. They have fixed some bugs regarding session.

A: Thanks you, all of you for giving excellent suggestions i solved the problem i  use vanilla php session library. thanks a lot


text:
Q: Cognos Report with Multiple value prompts I currently have a report that have 9 value prompts items,so far I can only load the prompts with the values that the user can select from, however the desired results should be based on user selection for example if user selected from value prompt1 then only  values that are related to value prompt1 should be populated in other value prompts and so on. Your assistance in this regards will be highly appreciated, Thanks in advance.!!!

A: If I understand correctly, you want ValuePrompt2 to populate after a value is selected in ValuePrompt1 and be filtered by that selection.  You want ValuePrompt3 to populate after a value is selected in ValuePrompt2 and be filtered by that selection and the selection in ValuePrompt1.  Etc.
Given object relationships that follow this pattern:  QueryN : ValuePromptN : ParamN : QueryItemN
You need to set up Param1 as a Cascade Source for ValuePrompt2.  Cognos figures out the filtering for this.
You also need to set up Param2 as a Cascade Source for ValuePrompt3.  But that won't filter ValuePrompt3 by the selection(s) in ValuePrompt1.  To do that, you'll need to make Query3 more specific by adding filters that use Param1 and Param2.
QueryItem1 = ?Param1?
QueryItem2 = ?Param2?

(For clarity, you'll probably want to filter Query2 in a similar manner.)
So when you get to ValuePrompt9, it will be sourced from Query9 and have these filters...
QueryItem1 = ?Param1?
QueryItem2 = ?Param2?
QueryItem3 = ?Param3?
QueryItem4 = ?Param4?
QueryItem5 = ?Param5?
QueryItem6 = ?Param6?
QueryItem7 = ?Param7?
QueryItem8 = ?Param8?

...and its Cascade Source property will be set to Param8.
Consider the design of your queries.  A prompt page like you propose may be very slow.

Updated based on new requirement...
If you need to select the values in any order, all of the source queries should have filters to use all of the other parameters and none of the prompts should have the cascade source property set.  Then, create a new prompt (PromptNH) for each prompt (PromptN), set its Cascade source property to the related parameter (ParamN), set the Auto-submit property of the source prompt (PromptN) to Yes, and hide the prompt (PromptNH).  This forces a reprompt after each selection.  Keep in mind that in this scenario the prompt page will quickly filter itself into an unusable state.

A: Thanks for all the valuable inputs, I only needed to enter a measure in my query so that the filtering can only happen where the is volume in those filters

redpajama_set_name: RedPajamaStackExchange


text:
Q: For loop in shell script that iterates over two lists of files I want to write a for loop that uses a function that takes two variables, both of which are files. I have a set of FASTA files and a set of text files that correspond to each FASTA file, and I want the for loop to itereate over both lists in parallel. This is what the function would look like for one pair of files:
anvi-gen-contigs-database --contigs-fasta fastafile.fna --project-name ProjectName --output-db-path /path/to/file/fastafile.fna.db --external-gene-calls /path/to/file/textfile.txt --ignore-internal-stop-codons

I know how to set up a for loop that takes only one variable, and previously I have used a for loop that looks like this:
for f in *.fna; do
    anvi-gen-contigs-database --contigs-fasta $f --project-name ProjectName --output-db-path /path/to/file/${f}_out.db;
done

I've been looking around this and other sites for a way to modify the preceding for loop so that it will take two files as variables and iterate over them in pairs, and I've found two ways that might work, but none of the examples I have found involve using files as variables, so I wanted to check and make sure the for loop will do what I want it to do before I try running it. Here is the first way:
for f in *.fna and for e in *.txt; do
    anvi-gen-contigs-database --contigs-fasta $f --project-name ProjectName --output-db-path /path/to/file/${f}_out.db --external-gene-calls /path/to/file/$e --ignore-internal-stop-codons;
done

And here is the second way:
for f, e in zip(*.fna, *.txt); do
    anvi-gen-contigs-database --contigs-fasta $f --project-name ProjectName --output-db-path /path/to/file/${f}_out.db --external-gene-calls /path/to/file/$e --ignore-internal-stop-codons;
done

Can someone please confirm that at least one of those ways is syntactically correct and will iterate over the two lists of files in parallel as I want it to do, or else suggest a correct or better way? Thanks!

A: Put the two lists of filenames in arrays, then iterate over the array indexes.
fastas=(*.fna)
texts=(*.txt)

for i in ${#fastas[@]}; do
    f=${fastas[i]}
    e=${texts[i]}
    anvi-gen-contigs-database --contigs-fasta "$f" --project-name ProjectName --output-db-path "/path/to/file/${f}_out.db" --external-gene-calls "/path/to/file/$e" --ignore-internal-stop-codons
done


text:
Q: Using findViewById in Activity's onCreate not behaving as expected I'm attempting to use a 'RangeSeekBar' (https://code.google.com/p/range-seek-bar/). This has to be done in the code rather than the XML, so I've plugged the sample code into my activity's onCreate method as instructed.
My code falls apart at the findViewById method outlined below. Using the sample code, I get the following two outcomes:

*

*If I try to get the LinearLayout directly by referring to its ID, I get a null pointer exception. I expect this to provide the LinearLayout, I don't understand why this is null.

*If I refer to R.id.container, I can insert the RangeSeekBar but it overlaps the first field. Note that if I try to cast the container to a LinearLayout instead of ViewGroup, I get an error that indicates that the container is a FrameLayout, which tells me the container isn't the LinearLayout that I want it to be.
My question is this, How do I insert the RangeSeekBar into the fragment ViewGroup so that it adheres to the LinearLayout? Or, How do I retrieve my fragment LinearLayout from the activity onCreate and avoid a null pointer exception?
Update: I had previously listed the fragment xml rather than the activity xml. I've updated the question with both XML below.
Here's my onCreate method:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manage_seeds);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
    }

    // I replaced the sample code's "context" with getBaseContext() should this be something else??
    //RangeSeekBar<Integer> seekBar = new RangeSeekBar<Integer>(20, 75, context); //CODE SAMPLE
    RangeSeekBar<Integer> seekBar = new RangeSeekBar<Integer>(0, 40, getBaseContext()); //MY VERSION

    seekBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
        @Override
        public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
            // handle changed range values
            Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
        }
    });

    // add RangeSeekBar to pre-defined layout
    //ViewGroup layout = (ViewGroup) findViewById(<your-layout-id>); //SAMPLE CODE
    ViewGroup layout = (ViewGroup) findViewById(R.id.container); //MY CODE THAT SORT OF WORKS
    layout.addView(seekBar); // This inserts the RangeSeekBar overlapping the Name field

    //ViewGroup layout = (ViewGroup) findViewById(R.id.layout_manage); //MY CODE THAT RETURNS A NULL POINTER EXCEPTION AT RUNTIME
    //layout.addView(seekBar); // This causes the null pointer exception because the line above returns null.
}

Here's my fragment XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_manage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText android:id="@+id/test_edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/test_edit_name" />

    <EditText android:id="@+id/test_edit_type"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/test_edit_type" />

    <!-- I want the custom RangeSeekBar added here. Must be done via java code, not possible through XML -->

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test_button_save"
        android:layout_gravity="right" />
</LinearLayout>

Here's my activity_manage_seeds xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mypackage.myapp.ManageSeedsActivity"
    tools:ignore="MergeRootFrame" />

A: I think a tidier solution to this is to add a FrameLayout into your existing LinearLayout, and add the RangeSeekBar into the FrameLayout. See below:
<!-- Activity Layout -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/layout_manage"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical" >

<EditText android:id="@+id/test_edit_name"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />

<EditText android:id="@+id/test_edit_type"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />

<!-- This is the container for the RangeSeekBar -->
<FrameLayout
    android:id="@+id/range_seek_bar_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right" />
</LinearLayout>

Your onCreate() method may look as follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RangeSeekBar rangeSeekBar = new RangeSeekBar<Integer>(20, 75, context);

    ViewGroup rangeBarContainer = (ViewGroup) findViewById(R.id.range_seek_bar_container);
    rangeBarContainer.addView(rangeSeekBar);
}

This makes it much easier to edit the RangeSeekBar's layout attributes
Update
Upon reading your new code, I noticed you are attempting to edit the layout of one of your Fragments from your Activity code. You shouldn't do this. Work inside PlaceholderFragment.
Your onCreateView() method inside PlaceholderFragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.your_fragment_layout, container, false);

    RangeSeekBar rangeSeekBar = new RangeSeekBar<Integer>(20, 75, context);

    ViewGroup rangeBarContainer = (ViewGroup) rootView.findViewById(R.id.range_seek_bar_container);
    rangeBarContainer.addView(rangeSeekBar);

    return rootView;
}

A: 1) NullPointerExcption occus when you try to asscess a View which does not resides in your layout file (activity_manage_seeds).
Please make sure that your Viewgroup layout_manage is there in activity_manage_seeds.xml file.
2) Regarding your seekbar position you need to add layout parameters to set its proper location, provided you viewGroup R.id.container resides in activity_manage_seeds.xml which is not there in your xml file shown above.

A: You got the linear layout id wrong in the code try changing it to layout_manage instead of container.

A: You are trying to get a View that is not on your xml thats why it returns nullpointer..
change the layout of this :
setContentView(R.layout.activity_manage_seeds);

to the layout where the id R.id.container resides


text:
Q: Proving $a\sin\theta+b\cos\theta=R\sin(\theta+\alpha)$, where $R=\sqrt{a^2+b^2}$ and $\tan\alpha=\frac ba$ The R-method:
If $R = \sqrt{a^2 + b^2}$
$a \sinθ + b \cosθ$
$= R \sin(θ + α)$, where $\tan α = \frac ba$
$=R \cos(θ − α)$, where $\tan α = \frac ab$
Its proof provided here makes some assumptions that do not seem intuitive. Is there any alternative way to prove this?


text:
Q: Solving a specific equation in Mathematica & Finding the range of a value in an inequality Is there any way to solve (or even approximate the value of x) the following equation in Mathematica?
Solve[x - 11 - (1.0002)(0.0011/5.001)^(3x/(3x-5.0001)) == 0, x, Reals]

I have also another question which is in the following inequality how can I find the range of m that satisfies the inequality?
m - 2 - (0.02/5)^(m/(m-2)) > 0 && m > 0

A: The first one works the way you have written unless x has some definition that breaks it.
Try Remove[x] and then evaluate it again.
For the second one write:
Reduce[m - 2 - (2/100/5)^(m/(m - 2)) > 0 && m > 0, m, Reals]

m > 2


text:
Q: How do I use groovy to search+replace in XML? How do I use groovy to search+replace in XML?
I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting.
More specifically, how do I turn:
<root><data></data></root>

into:
<root><data>value</data></root>

A: Some of the stuff you can do with an XSLT you can also do with some form of 'search & replace'. It all depends on how complex your problem is and how 'generic' you want to implement the solution. To make your own example slightly more generic:
xml.replaceFirst("<Mobiltlf>[^<]*</Mobiltlf>", '<Mobiltlf>32165487</Mobiltlf>')

The solution you choose is up to you. In my own experience (for very simple problems) using simple string lookups is faster than using regular expressions which is again faster than using a fullblown XSLT transformation (makes sense actually).

A: After some frenzied coding i saw the light and did like this
import org.custommonkey.xmlunit.Diff
import org.custommonkey.xmlunit.XMLUnit

def input = '''<root><data></data></root>'''
def expectedResult = '''<root><data>value</data></root>'''

def xml = new XmlParser().parseText(input)

def p = xml.'**'.data
p.each{it.value="value"}

def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
def result = writer.toString()

XMLUnit.setIgnoreWhitespace(true)
def xmlDiff = new Diff(result, expectedResult)
assert xmlDiff.identical()

Unfortunately this will not preserve the comments and metadata etc, from the original xml document, so i'll have to find another way

A: I did some some testing with DOMCategory and it's almost working. I can make the replace happen, but some infopath related comments disappear. I'm using a method like this:
def rtv = { xml, tag, value ->
    def doc     = DOMBuilder.parse(new StringReader(xml))
    def root    = doc.documentElement
    use(DOMCategory) { root.'**'."$tag".each{it.value=value} }
    return DOMUtil.serialize(root)
}

on a source like this:
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://corp.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf></Mobiltlf>
  <E-mail-adresse></E-mail-adresse>
</application:FA_Ansoegning>

The only thing missing from the result are the <?mso- lines from the result. Anyone with an idea for that?

A: That's the best answer so far and it gives the right result, so I'm going to accept the answer :)
However, it's a little too large for me. I think i had better explain that the alternative is:
xml.replace("<Mobiltlf></Mobiltlf>", <Mobiltlf>32165487</Mobiltlf>")

But that's not very xml'y so I thought i'd look for an alternative. Also, I can't be sure that the first tag is empty all the time.

A: To retain the attributes just modify your little program like this (I've included a sample source to test it):
def input = """
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf  type="national" anotherattribute="value"></Mobiltlf>
  <E-mail-adresse attr="whatever"></E-mail-adresse>
</application:FA_Ansoegning>
""".trim()

def rtv = { xmlSource, tagName, newValue ->
    regex = "(<$tagName[^>]*>)([^<]*)(</$tagName>)"
    replacement = "\$1${newValue}\$3"
    xmlSource = xmlSource.replaceAll(regex, replacement)
    return xmlSource
}

input = rtv( input, "Mobiltlf", "32165487" )
input = rtv( input, "E-mail-adresse", "bob@email.com" )
println input

Running this script produces:
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf  type="national" anotherattribute="value">32165487</Mobiltlf>
  <E-mail-adresse attr="whatever">bob@email.com</E-mail-adresse>
</application:FA_Ansoegning>

Note that the matching regexp now contains 3 capturing groups: (1) the start tag (including attributes), (2) whatever is the 'old' content of your tag and (3) the end tag. The replacement string refers to these captured groups via the $i syntax (with backslashes to escape them in the GString). Just a tip: regular expressions are very powerful animals, it's really worthwile to become familiar with them ;-) .

A: Three "official" groovy ways of updating XML are described on page http://groovy.codehaus.org/Processing+XML, section "Updating XML".
Of that three it seems only DOMCategory way preserves XML comments etc.

A: To me the actual copy & search & replace seems like the perfect job for an XSLT stylesheet. In an XSLT you have no problem at all to just copy everything (including the items you're having problems with) and simply insert your data where it is required. You can pass the specific value of your data in via an XSL parameter or you can dynamically modify the stylesheet itself (if you include as a string in your Groovy program). Calling this XSLT to transform your document(s) from within Groovy is very simple.
I quickly cobbled the following Groovy script together (but I have no doubts it can be written even more simple/compact):
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

def xml = """
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf></Mobiltlf>
  <E-mail-adresse></E-mail-adresse>
</application:FA_Ansoegning>
""".trim()

def xslt = """
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:param name="mobil" select="'***dummy***'"/>
    <xsl:param name="email" select="'***dummy***'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Mobiltlf">
        <xsl:copy>
            <xsl:value-of select="\$mobil"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="E-mail-adresse">
        <xsl:copy>
            <xsl:value-of select="\$email"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
""".trim()

def factory = TransformerFactory.newInstance()
def transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))

transformer.setParameter('mobil', '1234567890')
transformer.setParameter('email', 'john.doe@foobar.com')

transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out))

Running this script produces:
<?xml version="1.0" encoding="UTF-8"?><?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:application="http://ementor.dk/application/2007/06/22/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf>1234567890</Mobiltlf>
  <E-mail-adresse>john.doe@foobar.com</E-mail-adresse>
</application:FA_Ansoegning>

A: Brilliant! Thank you very much for you assistance :)
That solves my problem in a much cleaner and easier way. It's ended up looking like this:
def rtv = { xmlSource, tagName, newValue ->
    regex = "<$tagName>[^<]*</$tagName>"
    replacement = "<$tagName>${newValue}</$tagName>"
    xmlSource = xmlSource.replaceAll(regex, replacement)
    return xmlSource
}

input = rtv( input, "Mobiltlf", "32165487" )
input = rtv( input, "E-mail-adresse", "bob@email.com" )
println input

Since I'm giving this to our testers for use in their testing tool SoapUI, I've tried to "wrap" it, to make it easier for them to copy and paste.
This is good enough for my purpose, but it would be perfect if we could add one more "twist"
Let's say the input had this in it...
<Mobiltlf type="national" anotherattribute="value"></Mobiltlf>

...and we wanted to retain thos two attributes even though we replaced the value. Is there a way to use regexp for that too?

A: check this:
http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page=2


text:
Q: Push down values without shifting the row So have this button on a form and I cant make the data on 3 cells (Ex:C1,D1,E1) go down 1 Row without shifting the whole sheet.

How do i make the values go down after being inserted so that i can leave Row1 allways open for new values?
This is the code on the command button, can i embed the solution on it or do I have to do it somewhere else?
 Private Sub CommandButtonAddDes_Click()

Dim emptyRow As Long

'Activate sheet
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("C:C")) + 1

'Transfer info
Cells(emptyRow, 3).Value = Des
Cells(emptyRow, 4).Value = ComboBox.Value
Cells(emptyRow, 5).Value = TextBox1.Value

End Sub

A: Looks like you want to make sure that the cells being updated are then moved down automatically. You can do that with a change event on the sheet code behind like this:
Sub Worksheet_Change(ByVal Target As Range)
    'Checks if the column being changed is C - E
    If Target.Column = 3 Or Target.Column = 4 Or Target.Column = 5 Then
        'Checks if the row being changed is row 2
        If Target.Row = 2 Then
            'Inserts a new row and pushes what is in C2:E2 down one row
            Range("C2:E2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        End If
    End If
End Sub

This code will go in the sheets code behind. So, you will have to right-click on the sheet that you have this data on and then click on view code (or just double-click the sheet)
Putting the code there will tell Excel to watch that sheet for changes and then the code checks if it is happening to one of those 3 cells (C2:E2)

A: With data in C1, D1 and E1 just:
Range("C1:E1").Insert Shift:=xlDown

This pushes down the three cells rather than the entire row.
EDIT#1:
Put this event macro in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Long
    c = Target.Column
    If c = 3 Or c = 4 Or c = 5 Then
        If Application.WorksheetFunction.CountA(Range("C1:E1")) = 3 Then
            Application.EnableEvents = False
                Range("C1:E1").Insert shift:=xlDown
            Application.EnableEvents = True
        End If
    End If
End Sub

Once you have entered all 3 values in C1 through E1, the values will get pushed down automatically.

A: Edited: changed lat column index from "D" to "E" and starting row index from "3" to "2"
Maybe you're after this
Private Sub CommandButtonAddDes_Click()
    With Sheet1
        With .Range("C2:E" & .Cells(.Rows.Count, "C").End(xlUp).Row)
            .Offset(1).Value = .Value
            .Resize(1) = Array(Des, ComboBox.Value, TextBox1.Value)
        End With
    End With
End Sub

Should different rows need to be "inserted" you just change the row index.

A: Replace you code on your userform. Ensure your input box names are correct, i.e. ComboBox1, TextBox1, etc. I don't understand what "Des" is. If you need it in row 2 then just change the 1s to 2s.
Private Sub CommandButton1_Click()
With Sheets("Sheet1")
    .Range("C1:E1").Insert Shift:=xlDown
    .Range("C1").Value = Des.Value
    .Range("D1").Value = ComboBox.Value
    .Range("E1").Value = TextBox1.Value
End With

End Sub


text:
Q: Firebase Crash Reporting - uploading custom files Is there a way to attach complete logcats to crashes using Firebase Crash Reporting?  I did notice that the Firebase SDK has some log functions, but those have to be specifically invoked.  My app already does a ton of logging to logcat using our own custom loggger (not Android logger) anyways, so I would hate to have to duplicate the log calls to Firebase.
For example, I would need to do:
MyLogger.d(TAG, "my log message");
Firebase.log("my log message");

A: Sending a complete logcat isn't really possible because modern Android permissions don't allow apps to access that any more (as logs could easily and accidentally contain sensitive information).  You will need to invoke the logging API to get logs attached.  It's advisable to hook your existing logging infrastructure to make this happen without duplication at every location.


text:
Q: Verilog GCD execution errors Re:Edit
I was able to solve that issue and move on to simulate the waveform using the testbench I had written, unfortunately there is no waveform from my main function getting generated.
My Testbench:
`timescale 1ns/1ps
module gcd_test();

reg [15:0] a,b;
reg clk, rst;

gcd uut(a,b,clk,rst);

initial begin

rst = 1;
a = 16'b0000000000001100;
b = 16'b0000000000000011;

end

initial begin
rst = 0;
end

always begin
#50
clk = 0;
#50
clk = 1;
end

endmodule

My output waveform is a couple of zzzz (as if my code was bored of execution). I check the output from the testbench, its good but the same isnt true for my main function. The output wave isnt as it should be. Again am I wrong with my testbench or parsing of the value from my testbench to the main?
TIA.
+++++++++++++++++++++++++++++++++++++++++++++
I am trying to execute a GCD function using Verilog HDL and I am utilizing a simple algorithm to execute this operation. However I keep stumbling across a number of errors during my execution.
My code:
module gcd(
input [15:0] a,
input [15:0] b,
input clk,
input rst);

reg [15:0] ra;
reg [15:0] rb;
reg [15:0] gcd;
reg done;
reg [2:0] state;
parameter start = 2'h1;
parameter check = 2'h2;
parameter comp = 2'h3;
parameter lastend = 2'h4;

always @ (posedge clk or posedge rst)
if (rst)
begin
    ra <= 16'h0;
    ra <= 16'h0;
    gcd <= 16'h0;
    state <= start;
end

else begin
    case(state)
        start: //status 0
                begin
                    ra <= a;
                    rb <= b;
                    state <= check;
                end
        check:  //Status 1
                begin
                    if ((ra == 16'h0) || (ra == 16'h0))
                    begin
                        state <= lastend;
                    end
                    else begin
                        state <= comp;
                    end
                end
        comp: //status 2
                begin
                    if(ra > rb) //Compare ra and rb
                    begin
                        ra = ra - rb;
                        if((ra < 16'h0) || (rb < 16'h0)) //Compare ra and rb and if either has become 0
                        begin
                            done = 1'h0;
                            state <= lastend;
                        end
                        else begin
                            state <= comp;
                            gcd <= ra;
                        end
                    end
                    else if (rb > ra) //Compare ra and rb
                    begin
                        rb = rb - ra;
                        if((ra < 16'h0) || (rb < 16'h0))//Compare ra and rb and if either has become 0
                        begin
                            done <= 1'h0;
                            state <= lastend;
                        end
                        else begin
                            state <= comp;
                            gcd <= ra;
                        end
                    end
                    else if(ra == rb) //Finally gcd found ra == rb
                        begin
                            gcd <= ra;
                            done <= 1'h0;
                            state <= start;
                        end
        lastend: //status 3
                        begin
                            gcd <= 16'h0;
                            done <= 1'h0;
                        end

    endcase
end
endmodule

Error (10170): Verilog HDL syntax error at gcd.v(85) near text
  "endcase";  expecting "end"

Or

Error (10163): Verilog HDL error at gcd.v(53): illegal name "lastend"
  used in expression
  Error (10163): Verilog HDL error at gcd.v(66):
  illegal name "lastend" used in expression

with an extra end appended to the code.
Also, I have backtracked the code and seemed to have found all begins with appropriate ends.
Any suggestion is very helpful.

A: This begin:
        comp: //status 2
                begin

does not appear to have a matching end.


text:
Q: Prove: (p ∧ q) ∨ (q ∧ r) ∨ (r ∧ p) ≡ (p ∨ q) ∧ (q ∨ r) ∧ (r ∨ p) I tried reversing absorption on the RHS to expand all terms then group the individual element but I end up getting the LHS  and the RHS.I was thinking maybe I can expand the LHS reversing using the same method and show that each sides can be expanded to the same form. However I feel there is a better way to prove this using only the laws where one side becomes the other.Thoughts?

A: You know FOIL from basic arithmetic, right?
$(a+b)(c+d)=ac+ad+bc+bd$
Well, it turns out you can generalize it in several ways. For example, you can have more than two terms in the sums:
$(a+b)(c+d+e)=ac+ad+ae+bc+bd+be$
The basic principle is the same though: you combine each element from the first sum with each element from the second sum.
You can also have more than two sums, e.g:
$(a+b)(c+d)(e+f)=ace+acf+ade+adf+bce+bcf+bde+bdf$
Again, it's the same general idea though: you produce all combinations of terms, where each terms picks exactly one element from each sum.
Now, it turns out that the same kind of distributive principles hold for logic. Indeed, the last one is very much like what you have, and so you get:
$(p \land q) \lor  (q \land r) \lor (r \land p) \equiv (p \lor q \lor r) \land (p \lor q \lor p) \land (p \lor r \lor r) \land (p \lor r \lor p) \land (q \lor q \lor r) \land (q \lor q \lor p) \land (q \lor r \lor r) \land (q \lor r \lor p)$
OK, but now we can simplify. First, by Idempotence, we can remove duplicates of the disjuncts:
$\equiv (p \lor q \lor r) \land (p \lor q) \land (p \lor r) \land (p \lor r) \land (q \lor r) \land (q \lor p) \land (q \lor r) \land (q \lor r \lor p)$
and also of the conjuncts:
$\equiv (p \lor q \lor r) \land (p \lor q) \land (p \lor r) \land (q \lor r) $
Finally, we can use Absorption, which states that $A \land (A \lor B) \equiv A$.  Wih that, we can get rid of the $(p \lor q \lor r)$ term, leaving us with:
$\equiv (p \lor q) \land (p \lor r) \land (q \lor r) $

A: Using the law of distribution the RHS can be simplified.
I am using a notation I learned in my computer engineering classes.
Unions can be substituted for ORs and Intersects can be substituted for ANDs
The RHS reads
$$(P + Q)(Q + R)(R + P)$$
Simplifies:
$$ PQR + PQ + QR + RP $$
Factor out an expression from PQR:
$$ PQ ( 1 + R ) + QR + RP $$
1 + R evaluates to 1:
$$ PQ (1) + QR + RP $$
Finally,
$$ PQ + QR + RP $$


text:
Q: How to define constants that multiplies with the trigonometric functions I have equation w, which contains some trig functions multiplied with come constants. how to express this function in python. I am getting an error that says a1...a4 and b are not defined. I know it is not defined, but I am interested in solving for these constants for a given value of b for a set of for conditions on w
import sympy as sy
import numpy as np
import math as ma
import matplotlib.pyplot as plt

w=a1*sin(b*x)+a2*cos(b*x)+a3*sinh(b*x)+a4*cosh(b*x)

A: To do this with sympy you need to import the sympy functions and define the symbols first:
In [2]: from sympy import sin, cos, sinh, cosh, symbols

In [3]: a1, a2, a3, a4, b = symbols('a1:5, b')

In [4]: w=a1*sin(b*x)+a2*cos(b*x)+a3*sinh(b*x)+a4*cosh(b*x)

In [5]: w
Out[5]: a₁⋅sin(b⋅x) + a₂⋅cos(b⋅x) + a₃⋅sinh(b⋅x) + a₄⋅cosh(b⋅x)

I recommend going through the sympy tutorial:
https://docs.sympy.org/latest/tutorial/index.html


text:
Q: Securing Google Cloud Functions run in background I am using Google Cloud Functions as a background functions to listen to an incoming CSV file on GS bucket and subsequently trigger a Cloud SQL Import (MySQL).
I am able to successfully test this flow and see the CSV file data loaded into Cloud SQL.
However, I would like to validate this approach from a security perspective and also explore if there are any other better options.
I understanding is that since there is no http endpoint exposed for the Cloud Functions (backgrounder function), there should not be a security loophole.
Wanted to validate this from others and flag if there is anything specific I need to take care.

A: Cloud Functions have several possible triggers: [Event triggers]

*

*HTTP—invoke functions directly via HTTP requests

*Cloud Storage

*Cloud Pub/Sub

*Firebase (DB, Storage, Analytics, Auth)
You can configure Cloud Functions access control depending on your needs. [Cloud Functions doc]
If you are using GCS (Google Cloud Storage) as trigger you need to configure GCS access control properly. [GCS doc]
If you control the entry-point (GCS in this case) everything should go well.


text:
Q: what is the header library for JSON in dart language what is the header library for JSON in dart language?
I need to parse from string and convert it into map.
 var jsonData = JSON.parse('{"x":1, "y":2}');

what is the header library?

A: To parse JSON, you import dart:convert and use json.decode (or jsonDecode, which is a just a shorthand for the former).


text:
Q: Horizontally centering elements inside a div To make this easy, say you had a div that was 100px wide, and 3 divs inside of it each 20px wide.  How can I align them to where they align to the center of the div leaving a 20px; gap on each side?

A: Center some HTML elements always depends of your project and integration dependencies...
You may be happy with these 2 solutions, display: inline-block; and float: left;
Both have pros & cons, hope that it can help you !
http://jsfiddle.net/HP2DS/1/

#container {
    width: 100px;
    height: 80px;
    text-align: center;
    background: cyan;
}

#container .centered {
    display: inline-block;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}

#container-2 {
    width: 60px; /* 60px + 2*20px of padding... */
    height: 80px;
    padding: 0 20px;
    text-align: center;
    background: cyan;
}

#container-2 .centered {
    float: left;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}

A: Good day! Here is how I implemented it:
HTML

CSS
#container {
  width: 100px;
  height: 100px;
  border: 1px solid red; /** for viewing purposes **/
  text-align: center; /** center the divs **/
  font-size: 0; /** remove the unwanted space caused by display: inline-block in .child **/
}

#container .child {
  display: inline-block; /** set the divs side-by-side **/
  vertical-align: top;
  width: 20px;
  height: 100px;
  font-size: 12px; /** override font-size: 0 of #container, so that text will be visible again **/
  text-align: left; /** set text in the .child divs back to normal alignment **/
  border: 1px solid blue; /** for viewing purposes **/
  box-sizing: border-box;
}

I hope this helps. Cheers! :)


text:
Q: Compatibility of Open GL 2.0 vs 1.1 on Android Hi we're developing a live wallpaper application for android handsets,  our coding team is saying that openGL 1.1 should be used instead of openGL 2.0.
http://developer.android.com/resources/dashboard/opengl.html
This shows that openGL 2.0 is supported on 90% of devices accessing the market,  our coding team says that the software supports it but hardware acceleration and support would be an issue on many devices running android 2.2 and above. Anyone have any issues with openGL 2.0 and Android?

A: I think most devices that support OpenGL ES 2 have appropriate hardware acceleration.
A lot of the newer devices actually emulate OpenGL ES 1.1 support using
OpenGL ES 2.0 and so would need an appropriate hardware accelerated 2.0 driver.

A: I've never heard of an Android device that emulates opengl es 2.0 in software, not even the emulator can do so.
"OpenGL ES 2.0 is supported by most Android devices and is recommended for new applications being developed with OpenGL"
From: http://developer.android.com/guide/topics/graphics/opengl.html
You should read the sections "OpenGL Versions and Device Compatibiity" and "Choosing an OpenGL API version", and you should trust Google and not your coding team.


text:
Q: Add-In Global Declarations I have a large EXCEL model that has to run routines via add-ins that have common variable. To speed up the process, I would like to create global variable FROM INSIDE the add-in modules. When I try that and then debug the add-in module, any module, excluding the main module, gives me an error the variables are not defined.
'Main module in add-in
'----------------------
Global i As Integer, j As Integer
'
Sub Macro1()
'
' Macro1 Macro
'
MsgBox "Macro 1: " & i
'
    i = 100
    Macro2
'
MsgBox "Macro 1: " & i
'
End Sub
'
'
'Separate module in add-in
'-------------------------
Sub Macro2()
'
' Macro2 Macro
'
    MsgBox "Macro 2: " & i
'
i = 200
'
'
    MsgBox "Macro 2: " & i

End Sub

error: i is an ambiguous name

A: Change Global to Public, it shoud work


text:
Q: Изменить формат даты в php У меня в БД два поля с датами date,date1 и в них дата  сейчас выводится так: 2016-09-25.Я хочу сделать вот так: 25-09-2016.
Пытался менять формат на : d-m-Y ,но выводит на месте даты 0000-00-00
Помогите пожалуйста.
В файле который выводит из бд данные запрос такой:
$rezult=mysql_query("SELECT * FROM klienti");

В файле который добавляет запрос код такой:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="calendar/tcal.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Добавление клиента</title>

<form>
клиент

<input type="text" name="klient" />

ОП_форма

<textarea name="op_forma" ></textarea>

Наимен

<input type="text" name="naimen"  />

отрасль

<input type="text" name="otrasl"  />

telefon

<input type="text" name="telefon"  />

email

<input type="text" name="email"  />

Контактное лицо

<input type="text" name="kont_lico"  />

Должность

<input type="text" name="dolznost"  />

<input type="hidden" name="date" value="<?php echo date ('d-m-Y');?>" />
<input type="hidden" name="time" value="<?php echo date ('H:i:s');?>" />

<input type="text" name="date1" class="tcal"  value="" />

<input type="submit"  id="send"  value="Добавить" />
<input type="button" name="reset_form" value="Очистить форму" onclick="this.form.reset();">
</form>

В файле отвечающем за вставку в БД
<?php
$connection=mysql_connect("localhost","reklama","reklama") ;
mysql_select_db('reklama');
mysql_set_charset("utf8");
$ret=true;

mysql_query(" INSERT INTO `klienti` (klient,op_forma,naimen,otrasl,telefon,email,kont_lico,dolznost,date,date1,time)
    VALUES ('". $_POST ['klient'] ."' , '" .  $_POST ['op_forma']  ."', '" .  $_POST ['naimen']  ."', '" .  $_POST ['otrasl']  ."', '" .  $_POST ['telefon']  ."', '" .  $_POST ['email']  ."', '" .  $_POST ['kont_lico']  ."', '" .  $_POST ['dolznost']  ."', '" .  $_POST ['date']  ."', '" .  $_POST ['date1']  ."', '" .  $_POST ['time']  ."')") or $ret=false;
echo $ret;
 ?>

A:
Тип данных DATE используется для величин, содержащих информацию о
  дате. MySQL извлекает и выводит величины DATE в формате 'YYYY-MM-DD'.

Вы не сможете изменить в базе данных формат хранения на другой никак - это стандарт MySQL.
Для форматирования вывода воспользуйтесь классом DateTime, который позволяет удобно работать с датами.
DateTime::createFromFormat('Y-m-d', '2015-05-24')->format('d-m-Y');

A: date_format(date_create($date), 'd-m-Y');

A: можно попробывать strtotime($date)
date(strtotime($date),'d-m-Y');

http://sandbox.onlinephpfunctions.com/code/ffb08eac54ea6208556727e9b4d27f54647bbc15

A: *

*mysql - устаревшее расширение. Используйте mysqli
https://habrahabr.ru/post/141127/
http://phpclub.ru/detail/article/mysqli

*Опасайтесь SQL инъекций, нельзя напрямую в базу отдавать, что пришло в массиве $_POST (VALUES ('". $_POST ['klient'] ."' , '" .  $_POST ['op_forma'])
https://habrahabr.ru/post/148151/
https://habrahabr.ru/post/148701/

*Попробуйте использовать нормальный IDE для написания кода, который научит хорошему форматированию кода, кроме остальных преимуществ (например PhpStorm, он умеет автоматически форматировать код по сочетанию клавиш ctrl+alt+L)

*Что касается ответа на вопрос, то как писали выше, класс DateTime в помощь.
http://ru2.php.net/manual/ru/book.datetime.php


text:
Q: JAXB HashMap unmappable I want to convert a HashMap in a POJO class to XML. I tried using the XmlAdapter but it results in only the key and value pairs of the HashMap being the attributes of the XML Elements. I need the Key to be the Element itself and the value of the HashMap to be the value of the element. For instance, I need the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cart>
<supervisor_id>555</supervisor_id>
<payments>
    <payment sequence="1">
        <amount>123.45</amount>
        <billing_method>12345</billing_method>
        <form>card</form>
        <delivery_mode>Q</delivery_mode>
    </payment>
<payment sequence="2">
        <amount>123.45</amount>
        <person_id>2333</person_id>
        <form>cash</form>
        <delivery_mode>Q</delivery_mode>
    </payment>
</payments>
</cart>

I created the following classes: MyMapType holds a list of MyMapEntryType class which has two fields namely Key and Value. How do I change the Key element to be @XmlElement and assign the value field to the Key field?

Here are my source files.
MyMapType.java
import java.util.ArrayList;
import java.util.List;

public class MyMapType {

    private List<MyMapEntryType> entry = new ArrayList<MyMapEntryType>();

    public List<MyMapEntryType> getEntry() {
        return entry;
    }

    public void setEntry(List<MyMapEntryType> entry) {
        this.entry = entry;
    }

}

MyMapEntryType.java
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;

@XmlAccessorType(XmlAccessType.FIELD)
public class MyMapEntryType {

@XmlAttribute
private String key;
@XmlValue
private String value;
public String getKey() {
    return key;
}
public void setKey(String key) {
    this.key = key;
}
public String getValue() {
    return value;
}
public void setValue(String value) {
    this.value = value;
}
}

Please also find the adapter class:
MyMapAdapter.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MyMapAdapter extends XmlAdapter<MyMapType, Map<String, String>> {

    @Override
   public MyMapType marshal(Map<String, String> map) throws Exception {

        MyMapType myMapType = new MyMapType();

      for(Entry<String, String> entry : map.entrySet()) {
         MyMapEntryType myMapEntryType = new MyMapEntryType();
         myMapEntryType.setKey(entry.getKey());
         myMapEntryType.setValue(entry.getValue());
         myMapType.getEntry().add(myMapEntryType);
      }
      return myMapType;
   }

   @Override
   public Map<String, String> unmarshal(MyMapType map) throws Exception {
      HashMap<String, String> hashMap = new HashMap<String, String>();
      for(MyMapEntryType myEntryType : map.getEntry()) {
         hashMap.put(myEntryType.getKey(), myEntryType.getValue());
      }
      return hashMap;
   }
 }

This is the class which has the HashMap field:
XmlElementMap.java
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlElementMap {

@XmlAttribute(name="sequence")
private int sequence;

@XmlJavaTypeAdapter(MyMapAdapter.class)
private Map<String, String> map = new HashMap<String, String>();

public int getSequence() {
    return sequence;
}

public void setSequence(int sequence) {
    this.sequence = sequence;
}

public Map<String, String> getMap() {
    return map;
}

public void setMap(Map<String, String> map) {
    this.map = map;
}

}

Please advise on how to achieve this.
Regards,
-Anand
Currently it produces the following output:

A: I have the same requirement "I need the Key to be the Element itself and the value of the HashMap to be the value of the element".
I didn't use customized adapter, but implemented it by converting the HashMap entries dynamically to a list of JAXBElement objects, and then annotated the list with @XmlAnyElement.
@XmlRootElement(name="root")
public class MyMapType {

    @XmlAnyElement
    public List<JAXBElement> entries = new ArrayList<JAXBElement>();

    public MyMapType() {    // JAXB required
    }

    public MyMapType(Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            entries.add(new JAXBElement(new QName(entry.getKey()),
                    String.class, entry.getValue()));
        }
    }

    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(MyMapType.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        MyMapType mt = new MyMapType(map);

        marshaller.marshal(mt, System.out);
    }
}

The output is,
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <key1>value1</key1>
    <key2>value2</key2>
</root>

A: Note: a marshal/unmarshal example for Map instance can be found here: Dynamic tag names with JAXB.


text:
Q: ¿Como buscar si un elemento existe dentro de un array de texto en C#? Buenas ando aprendiendo C# y me encuentro con un quebradero de cabeza del que no logro salir.
Estoy intentando crear una función la cual contiene un array de tipo string, la idea es que la funcion recibe un parametro y debe buscar si ese mismo parametro existe dentro del array, despues en funcion de si existe o no ejecutara una orden o otra.
El codigo por ahora es tal que asi:
public static void comprobador(string comando)
{
string[] ciudad = { "Madrid", "Barcelona" };
bool existe;

if (existe == true)
{
console.writeline("Existe");
}
else
{
console.writeline("no existe");
}

}

creo que mi problema radica en que no se exactamente como buscar dentro del array, ni como saber si existe algo en el array, he visto temas sobre listas, foreach, etc
Me estoy liando un poco porque toda la informacion que encuentro sobre el uso de arrays con texto me resulta un poco contradictoria o muy compleja para algo tan relativamente simple. Dado que vengo de otros lenguajes como python donde no habia una distincion tan clara entre tipos de variables me resulta todo muy confuso. ¿Alguien me pude ayudar?

A: Puedes usar el método Contains de Linq.
bool existe = ciudad.Contains(comando);

Donde comando es el objeto que quieres buscar.
Te dejo aquí la documentación del método.
Para poder usarlo, deberás poner el using System.Linq;.
Espero que sirva.

A: Podrías intentar hacerlo con un ciclo FOR:
Boolean existeEnArray = false;
for(int i = 0; i < tuArray.Length; i++){
   if(tuArray[i] == tuCadena){
       exiteEnArray = true;
   }
}


text:
Q: iOS5: Best method of forcing UI orientation programmatically [I know this has been done to death, and I'd ask follow up questions on an existing question were it not for not having enough stackoverflow points to make one:(]
I'm after an App Store valid way of forcing an existing UI to re-orientate without having to destroy the main ViewController or View. We work in fullscreen mode, so I'm assuming I can't use any of the toolbar approaches normally quoted. Finally I'm only interested in iOS5.
For iOS6 I have a solution based on the answers in How to change the device orientation programmatically in iOS 6. I used the solution which includes ForcePortrait, with the variation that I changed it so I can supply the required orientation as a parameter.
For iOS5 I have experimented with the suggestion of:
[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:") withObject:(id)UIInterfaceOrientationPortrait];

from How to set device (UI) orientation programmatically?. This works well but I'm worried that it would be rejected by App Store (complete no no for us).
Has anyone used this on something that has App Store approval and/or got a better suggestion?

A: Check this out: Force Rotate UIViewController.
Maybe it will work. This is however very hackish.

A: [Found a solution, at any rate. Not sure if it the best.]
Got the temporary UIViewController approach to work by adding shouldAutorotateToInterfaceOrientation. The meaning of this is overloaded by iOS5 to discover not only should it autoRotate but also should it start in a particular orientation to start with - I guess that is why it is replaced by several methods at iOS6.. Thus we return true in orientations that are OK.
Perhaps should have realised that before.
Not quite as neat as the setOrientation hack. Key glitch we've noticed is that when you then rotate the device around to the proper orientation you still get a rotation animation. This does not occur on iOS6. Oh well, you win some, you lose some.


text:
Q: Adding an enemy every 10 seconds which tracks your location Below I have part of the code for a simple game I am making. in the game, your finger around the screen a ball is underneath your finger. Then every 10 seconds a ball gets added in which follows your ball. I have an SKAaction which calls my add enemy function every 10 seconds which spawns the enemy. The issue is that I can't make the add enemy function update every frame because the SKAction won't let me call it if its updating every frame, so I'm not sure what to do in order for the the ball to be added in every 10 seconds and to have that ball track your location. Because currently it only tracks the initial location of the ball when it was added in. any help is appreciated, thank you.
import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var me = SKSpriteNode()

    override func didMove(to view: SKView) {

        me = self.childNode(withName: "me") as! SKSpriteNode

        let border = SKPhysicsBody (edgeLoopFrom: self.frame)
        border.friction = 0
        self.physicsBody = border

        run(SKAction.repeatForever(SKAction.sequence([SKAction.run(createEnemy), SKAction.wait(forDuration: 10.0)])))
    }

    func createEnemy () {

        let enemy = SKSpriteNode(imageNamed: "ball 1")
        enemy.name = "enemy"
        enemy.position = CGPoint(x:667, y: -200)

        enemy.run(SKAction.moveTo(x: me.position.x, duration: 2))
        enemy.run(SKAction.moveTo(y: me.position.y, duration: 2))

        enemy.zPosition = +1
        addChild(enemy)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches{

            let location = touch.location(in: self)
            me.run(SKAction.moveTo(x: location.x, duration: 0))
            me.run(SKAction.moveTo(y: location.y, duration: 0))
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches{

            let location = touch.location(in: self)
            me.run(SKAction.moveTo(x: location.x, duration: 0))
            me.run(SKAction.moveTo(y: location.y, duration: 0))
        }
    }

    override func update(_ currentTime: TimeInterval) {

    }
}

A: *

*Keep a list of all of your currently alive enemies in a dictionary via their .name property. The values in this dictionary are a tuple. This tuple keeps track of the enemy's instance, and its target's instance.

I do this in your createEnemy via makeEnemyName and addEnemyToDict

*during update give each enemy a new action to follow its target. This is done by iterating through the dictionary, then using each key's value to moveFollowerToTarget. This information is stored in the tuple type we created.

import SpriteKit

class GameScene22: SKScene {
  // MARK: - My code:

  // Tuple to keep track of enemy objects:
  typealias FollowerAndTarget = (follower: SKSpriteNode, target: SKSpriteNode)

  // [followerName: (followerSprite, targetSprite):
  var spriteDictionary: [String: FollowerAndTarget] = [:]

  // Give each enemy a unique name for the dictionary:
  var enemyCounter = 0

  // Assign to each enemy a unique name for the dictionary:
  private func makeEnemyName() -> String {
    enemyCounter += 1
    return "enemy\(enemyCounter)"
  }

  private func addEnemyToDict(enemy: SKSpriteNode, target: SKSpriteNode) {
    if let name = enemy.name { spriteDictionary[name] = (enemy, target) }
    else { print("enemy not found") } // error!
  }

  private func removeEnemyFromDict(enemy: SKSpriteNode) {
    if let name = enemy.name { spriteDictionary[name] = nil }
    else { print("enemy not removed from dictionary!") } // error!
  }

  // Note, you did not set the enemy to have a constant speed, so the enemy will move at random speeds
  // based on how far they are away from the target.
  private func moveFollowerToTarget(_ sprites: FollowerAndTarget) {
    let action = SKAction.move(to: sprites.target.position, duration: 2)
    sprites.follower.run(action)
  }

  private func allEnemiesMoveToTarget() {
    for sprites in spriteDictionary.values {
      moveFollowerToTarget(sprites)
    }
  }

  // Use this carefully if you are using phsyics later on:
  func killEnemy(_ enemy: SKSpriteNode) {

    // Remove this enemy from the update loop:
    removeEnemyFromDict(enemy: enemy)
    enemy.removeAllActions()
    enemy.removeFromParent()
    enemy.physicsBody = nil
  }

  // MARK: - Your code (mostly):

  var me = SKSpriteNode()

  override func didMove(to view: SKView) {
    me = SKSpriteNode(color: .blue, size: CGSize(width: 50, height: 50))
    me.name = "me"
    addChild(me)

    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    let border = SKPhysicsBody (edgeLoopFrom: self.frame)
    border.friction = 0
    self.physicsBody = border

    run(SKAction.repeatForever(SKAction.sequence([SKAction.run(createEnemy), SKAction.wait(forDuration: 10.0)])))
  }

  func createEnemy () {

    let enemy = SKSpriteNode(color: .purple, size: CGSize(width: 30, height: 30))
    enemy.name = makeEnemyName()
    addEnemyToDict(enemy: enemy, target: me)

    moveFollowerToTarget((follower: enemy, target: me))
    enemy.zPosition = +1
    addChild(enemy)
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches{

      let location = touch.location(in: self)
      me.run(SKAction.moveTo(x: location.x, duration: 0))
      me.run(SKAction.moveTo(y: location.y, duration: 0))
    }
  }

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches{

      let location = touch.location(in: self)
      me.run(SKAction.moveTo(x: location.x, duration: 0))
      me.run(SKAction.moveTo(y: location.y, duration: 0))
      allEnemiesMoveToTarget()
    }
  }

  override func update(_ currentTime: TimeInterval) {
    // Will iterate through dictonary and then call moveFollowerToTarget()
    // thus giving each enemy a new movement action to follow.
    allEnemiesMoveToTarget()
  }
}


text:
Q: Inter task communication, is Service Discovery the way to go? I am using ECS with 1 service that runs multiple tasks. The tasks should be able to communicate with each other. I made it work by reading out the eth1 network value, which corresponds to the private ipv4 address. With that value, tasks can talk to each other. I assume that this IP address never changes though, is this correct?
While googling other solutions, Service Discovery pops up. Now I am wondering, did I re-invented the wheel or is Service discovery used for communication among services and what I did was okay?

A:
did I re-invented the wheel or is Service discovery used for communication among services and what I did was okay?

You re-invented the wheel.

I assume that this IP address never changes though, is this correct?

That's incorrect. The IP can change, and probably will change, every time that task is replaced due to a deployment, due to auto-scaling, and due to any sort of task failure that causes ECS to automatically replace the task.


text:
Q: why Network programs store IP addresses in the IP address structure I'm a beginner in C, my textbooks cover some network programming in C, and states that Network programs store IP addresses in the IP address structure
/* Internet address structure */
struct in_addr {
unsigned int s_addr; /* Network byte order (big-endian) */
};

I'm confused, can't we just store a 32 bit integer?

A: in_addr represents an IPv4 address, which can indeed fit in a 32bit integer.
But, there are other types of socket addresses that cannot, such as IPv6 addresses.
Each type of socket address uses its own struct type:

*

*in_addr for IPv4

*in6_addr for IPv6

*char[] for UNIX paths

*etc

Usually wrapped inside a corresponding sockaddr struct:

*

*sockaddr_in for IPv4

*sockaddr_in6 for IPv6

*sockaddr_un for UNIX

*etc

Which is what you use with socket APIs like bind(), connect(), accept(), sendto(), recvfrom(), etc.
Very rarely would you ever need to use something like in_addr directly by itself.  Typically you would use it in conjunction with an API that requires an IPv4 address to be passed via the in_addr struct.


text:
Q: WPF ViewModel instantiation affecting child inheritance I have a child user control (Page1) which is failing to inherit the ViewModel (WizardPageViewModel) set on the DataContext of my WPF window when its declared inline in XAML:
<Window x:Class="WPFToolkitWizard.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:common="clr-namespace:WPFToolkitWizard"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <common:WizardPageViewModel/>
</Window.DataContext>
<Grid>
    <common:MyWizardControl>
        <common:MyWizardControl.Pages>
            <common:Page1 Title="Page 1" Description="First page" IsValid="true" />
        </common:MyWizardControl.Pages>
    </common:MyWizardControl>
</Grid>

However, if I change it as a static resource and reference it as follows:
<Window.Resources>
<common:WizardPageViewModel x:Key="vm" />
</Window.Resources>

<common:Page1 Title="Page 1" Description="First page" IsValid="true" DataContext="{StaticResource vm}" />

The bindings declared in Page1 which are dependant upon the injected VM work ok.  The problem is I want to reference the ViewModel from the DataContext property of the Window as this is how we declare our VMs across the team:
<Window.DataContext>
<common:WizardPageViewModel/>
</Window.DataContext>

I have tried setting the bindings as follows, but no such luck:
<common:Page1 Title="Page 1" Description="First page" IsValid="true" DataContext="{Binding}" />

Also I have read post on SO that the DataContext is automatically inherited, but its not working in this circumstance.
Looking at the detailed debug output it is as follows:
System.Windows.Data Warning: 60 : BindingExpression (hash=26218178): Default mode resolved to TwoWay
System.Windows.Data Warning: 61 : BindingExpression (hash=26218178): Default update trigger resolved to LostFocus
System.Windows.Data Warning: 62 : BindingExpression (hash=26218178): Attach to     System.Windows.Controls.TextBox.Text (hash=35377412)
System.Windows.Data Warning: 67 : BindingExpression (hash=26218178): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=26218178): Found data context element: TextBox (hash=35377412) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=26218178): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=26218178): Resolve source deferred

It states DataContext is null, but I just don't know why its not automatically finding my VM instance.
MyWizardControl is a user control
Page1 is a ContentControl

A: Seems working as expected for me.
From the structure of your code I assume that common:MyWizardControl is an ItemsControl, as it contains a Pages Property.
If that's true, then ItemsControl elements (in your case your page) inherit the ViewModel from the ItemControl's  Source ItemsSource property, which would be an ObservableCollection<WizardPageViewModel> in your case.
Since you don't set the ItemSource property on the ItemsControl, it's empty, WPF can't assign any data context to it.
The static one works, because you set it explicitly, overriding any possible DataContext set by ItemSource.
That being said, you got three options:

*

*Instantiate it statically and assign it yourself, as you did in your example (not very elegant)

*Use an MVVM Framework with an ViewModelLocator (i.e. Microsofts Prism Framework), that would explicitly resolve the View each time the view is instantiated (either by code or from XAML)

*Create a MyWizardViewModel which contains an ObservableCollection<WizardPageViewModel> Pages {get;set;} and bind it to ItemsSource of WizardPageViewModel.

First option feels a bit dirty, but may be fine for a demo or teaching project.
Second one works well for reusable Views/ViewModels and in case of Prims ViewModelLocator will create a new instance of the ViewModel for each Page1 view you insert in your XAML. You can use a single instance of the ViewModel in multiple Page1 controls if you use dependency injection framework (like Unity, MEF, Autofac etc.)
Third option is preferred one, as a ViewModel is meant to be used with a view and your View is the Page1, not the MyWizardControl (Actually MyWizardControl is a view on it's own with subviews, each of them meant to have it's own ViewModels representing the data that the View needs).
Third option is the easiest to implement, without having to work into a MVVM framework or dependency injection
Edit: An example
// Prism ViewModel base class, adjust for your framework or whatever you use as base
public class MyWizardViewModel : BindableBase
{
    public ObservableCollection<WizardPageViewModel> Pages { get; set; }

    public MyWizardViewModel()
    {
        Pages = new ObservableCollection<WizardPageViewModel>()
        {
            new WizardPage1ViewModel(), // public class WizardPage1ViewModel : WizardPageViewModel
            new WizardPage2ViewModel() // public class WizardPage2ViewModel : WizardPageViewModel
        }
    }
}

XAML:
<Window x:Class="WPFToolkitWizard.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:common="clr-namespace:WPFToolkitWizard"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <common:WizardPageViewModel/>
</Window.DataContext>
<Grid>
    <common:MyWizardControl ItemsSource="{Binding Pages}" />
</Grid>

Then you just need to make DataTemplates for each ViewModel and then the ContenControl will display the correct template depending on the type of the DataContext. See here


text:
Q: New WPF window only shows underneath originating window In my WPF application, I have a ListView on the main form that displays bound data from a DataSet. When a user double-clicks a row in the ListView, it opens a detail window.
In my XAML, I used a style to create a double click handler on the listview:
<Style x:Key="ListViewDoubleClick" TargetType="{x:Type ListViewItem}">
    <EventSetter Event="MouseDoubleClick" Handler="HandleDoubleClick" />
</Style>
...
<ListView Name="searchResults" ItemContainerStyle="{StaticResource ListViewDoubleClick}>

In the code-behind, I have a Dictionary that keeps track of the open Details windows (multiple can be open at a time) so that if a detail window is already open, it's brought to the front. I handle the double-click like so:
private void HandleDoubleClick(object sender, MouseEventArgs e)
{
    DataRowView clickedRow = ((ListViewItem)sender).Content as DataRowView;
    int row = (int)clickedRow.Row["ID"];
    if (!displayedCards.ContainsKey(row))
    {
        DetailWindow window = new DetailWindow(RetrieveData(row));
        //window.Owner = this;
        displayedCards.Add(row, window);
        window.Show();
    }
    else
    {
        displayedCards[row].Activate();
    }
}

My problem is that with the code like it is above, the detail windows are opened behind the main form. If I set the owner information (window.Owner = this), the detail windows are opened on top of the main form, but the main form is never able to come in front of the detail windows.
The displayedCards[row].Activate() works as I expected, bringing that detail window to the front of all other detail windows, but it falls victim to the same problem as above - it doesn't come in front of the main window.
What I want to accomplish is to have the detail windows on the same level/layer (/z order?) as the main window so that both can appear on top of one another, and to have the detail windows show up on top of the main form when they are opened.
Edit: If it's important, the detail window has no WindowStyle and AllowsTransparency is set to true. I also don't have a window title and the window doesn't appear in the taskbar. When trying to figure this out, I tried setting the WindowStyle to SingleBorderWindow, and the same problem occurs, except that the border of the detail window is shown on top of the main form as the detail window is being drawn, and then it's pushed behind the main form. Could my double-click handler essentially be pulling the main form to the front after the detail window is shown?

A: It looks like you aren't telling the event routing system that you have handled the event. Try setting e.Handled to true to tell WPF to not allow any further processing of your events. See RoutedEventArgs.Handled Property and Marking Routed Events as Handled, and Class Handling for more information on how the Handled property changes event routing.


text:
Q: Create, read and print to stdout using C This is my first time asking on Stack Overflow, i'll try my best to make a good question.
Fell free to correct me if i miss relevant information or stuff like that.
I'm writting a little program that creates a simple options menu.
My plan consist in very few steps:

*

*Read file names from that macro #define file_dir "/home/me/dir"

*Store that file names into names.txt.

*I have to display the content of names.txt as options in my simple menu.

At the moment i was able to accomplish two of three steps but not so well i guess.
I create 2 function to do these 2 jobs. create_file(), read_file(), respectively.
Now is where my question really begins:
Each function works ok when i execute isolated. If i call as it intended to be
The second function read_file() instead to print the content of the file to stdout
it rewrite the names.txt and put a "square" character at the end of the file.
My plan is to redirect the return of the read_file() to an array.
So i can display as options in this bare bone menu.
Please help me understand.
Why i can't use this two functions like that ?
I know i am new to C and this program is far from be complete.
Here's my code:
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>

#define my_dir "/home/me/dir"

  int roms_list;

  int create_list()
    {
    /* redirect stdout to a file */
    freopen("names.txt", "a+", stdout);

      /* open dir and print their content */
      DIR *dir;
      struct dirent *ent;
        if ((dir = opendir (nes_dir)) != NULL)
      {
            while ((ent = readdir (dir)) != NULL)
        {
                printf ("%s\n", ent->d_name);
          }
        }
      closedir(dir);
      close(names.txt);
    }

  int read_list()
  {
    FILE * list;
    char  ch;

    list = fopen("names.txt", "r+");

    if(NULL == list)
      {
        printf("file cant' be opened \n");
        return 1;
      }

    do
      {
        ch = fgetc(list);
        printf("%c", ch);
      }
    while (ch != EOF);

    fclose(list);
  }

int main()
{
  create_list();
  read_list();

  return 0;
}

A: It looks like you are printing EOF. You should check if ch is EOF before printing that.
Also fgetc() returns int and convering the return value to char will prevent it from distinguishing EOF from one of valid byte, so you should use int instead of char for ch.
Instead of this:
    char  ch;

    /* ... */

    do
      {
        ch = fgetc(list);
        printf("%c", ch);
      }
    while (ch != EOF);

You should use:
    int  ch;

    /* ... */

    while ((ch = fgetc(list)) != EOF)
      {
        printf("%c", ch);
      }

Or:
    int  ch;

    /* ... */

    ch = fgetc(list);
    while (ch != EOF)
      {
        printf("%c", ch);
        ch = fgetc(list);
      }

A: As MikeCAT points out, you attempt to printf("%c", ch); before checking ch != EOF resulting in attempting to print the int EOF values with the %c conversion specifier resulting in Undefined Behavior due to the mismatch in argument type and conversion specifier. ch must be type int to match the return type of fgetc() and to make a valid comparison with EOF.

If a conversion specification is invalid, the behavior is undefined.
If any argument is not the correct type for the corresponding
conversion specification, the behavior is undefined.

C11 Standard - 7.21.6.1(p9)
Additional Areas Where Your Code Needs Improvement

*

*Your create_list() function is type int, but fails to return any value. Since create_list() can succeed or fail, it is imperative that the return type be able to communicate whether it succeeded or failed. Type int is fine, you can for example return 0; on a failure to read or on success, return the number of entries written to the file;

*Your read_list() function is simply an output function that outputs the contents of the file written. While it can succeed or fail, it isn't critical to the continued operation of your program. Choosing type void for an output function is fine.

*Do not hardcode file or directory names in functions. You shouldn't have to recompile your program just to read from a different directory or write to a different filename. Pass the directory to read and the filename to write as arguments to your program. That is what the arguments to main() are for, e.g. int main (int argc, char **argv). (or prompt the user to input both string values)

*open your file in main() once and on successful open, pass a FILE* pointer for the open file stream to each of your functions as a parameter. You validate the open in main() because there is no need to call either function if fopen() fails.

*pass the directory name to read to create_list() as a const char * parameter.

*condition your call to read_list() on a successful return from create_list(). If create_list() fails, there is no need to call read_list().

Putting the improvements together, you could do something similar to the following:
#include <stdio.h>
#include <dirent.h>

/* returns 0 on failure, no. of files written on success */
int create_list (FILE *fp, const char *dname)
{
  /* open dir and print their content */
  DIR *dir;
  struct dirent *ent;
  int n = 0;              /* simple counter for no. of entries read */

  if ((dir = opendir (dname)) == NULL) {  /* return 0 on failure to open */
    return 0;
  }

  while ((ent = readdir (dir)) != NULL) {
    /* skip dot files */
    if ((ent->d_name[0] == '.' && !ent->d_name[1]) ||
        (ent->d_name[0] == '.' && ent->d_name[1] == '.')) {
      continue;
    }
    fprintf (fp, "%s\n", ent->d_name);
    n++;                                  /* increment counter */
  }

  closedir(dir);

  return n;     /* return the number of enteries written */
}

/* read list can be type void - it simply outputs contents of file */
void read_list (FILE *fp)
{
  int  ch;    /* must be int  */

  while ((ch = fgetc (fp)) != EOF) {  /* read char, validate not EOF */
      putchar (ch);                   /* write to stdout */
  }
}

int main (int argc, char **argv) {

  char *dname, *fname;    /* dirname and filename pointers */
  int nfiles = 0;         /* no. of files written */
  FILE *fp = NULL;        /* file pointer */

  if (argc != 3) {  /* validate 2 arguments given (dirname filename) */
    fputs ("error: dirname and filename required\n"
           "usage: ./program \"/path/to/files\" \"filename\"\n", stderr);
    return 1;
  }
  dname = argv[1];        /* assign arguments to give descriptive names */
  fname = argv[2];        /* (you could just use argv[x], a name helps) */

  fp = fopen (fname, "w+");   /* open file for reading/writing */

  if (!fp) {  /* validate file open for reading/writing */
    perror ("file open failed");
    return 1;
  }

  /* validate create_list succeeds */
  if ((nfiles = create_list (fp, dname))) {
    printf ("%d files:\n\n", nfiles);     /* number of entries in file */
    rewind (fp);                          /* rewind file pointer */
    read_list (fp);                       /* read list */
  }

  if (fclose (fp) != 0) {             /* always validate close-after-write */
    perror ("fclose fp");
  }
}

Example Use/Output
You provide the directory to read as the first argument and the filename to write as the second. ./progname /path/to/read /file/to/write
A short example:
$ ./bin/dirlist_names ./km dat/dnames.txt
47 files:

startstop.o
kernelmod_hello1.c
.chardev.o.cmd
hello-4.o
.hello-2.mod.cmd
hello-2.mod

<snip>

hello-5.mod
.startstop.o.cmd
.hello-4.mod.cmd
chardev.mod
Makefile
hello-2.c


text:
Q: Splitting data in SQL (separating a string of data) I am looking to split up some data in SQL. We currently use databox's in SQL to store data. e.g. the following bit of information would be stored in a databox called: {Script.Details01}.
{Script.Details01} = Mr J Bloggs and Miss M Bloggs
What we are trying to do is validate our data, however due to other departments who enter it manually we need to pull through the two names and split them into two different databox's. For example {Script.Details02} and {Script.Details03}.
Because of the data we need to validate we have tried setting them into cols.
"SELECT '{Script.Details01}' as Col1,
'{Script.Details01}' as Col2,
'{Script.Details01}' as Col3"

Col1 Part1 = Item('Col1') Entry(1,'')

Is there anyway we can split the data, so that Mr J Bloggs would go into details02 and Miss M Bloggs would go into 03? We can store the data entered and pull it through into questions, messages or ask it to go down a certain route depending on the answer.
Mr J Bloggs   and   Miss M Bloggs
{Script.Details02} {Script.Details03}
p.s. we do not care about "and" and want everything between this.
If I have confused anyone feel free to let me know and I will try and be clearer :)

A: Here is a possible solution. This isn't the cleanest, most concise possible way of writing this, and you will need to modify this a bit to work with your table names, intended column names / databoxes etc. but it should give you a good starting point. Bear in mind that if your data entry folks aren't 100% consistent about how they input pairs of names, you're going to run into trouble. You may need to use more sophisticated techniques to clean up the remaining information.
 SELECT
 LEFT({Script.Details01}, CHARINDEX(' and ', {Script.Details01})) AS FirstName,
 RIGHT({Script.Details01}, (CHARINDEX(' and ', {Script.Details01}) + 5)) AS SecondName
 FROM MyTable

See these articles for more information regarding CharIndex and the Left and Right functions:
https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql
https://social.technet.microsoft.com/wiki/contents/articles/17948.t-sql-right-left-substring-and-charindex-functions.aspx


text:
Q: Jquery UI Datepicker doesn't load if input has value I have the following code
<script type='text/javascript'>

$(function() {

    $( "#datepicker" ).datepicker({dateFormat:'yy-mm-dd'});

});

</script>

<input type='text' id='datepicker' name='date' value='<?php echo $date_from_mysql_query;?>'>

If the field doesn't have any value, the Datepicker loads, if the field is completed, it doesn't load the Datepicker.
How can I solve this?
Thanks

A: my problem actually was to make the datepicker to load on each  tagged via id, instead I used the class attribute and it worked marvelous, as I said 6 hrs ago.