Gdb can't connect to OpenOCD on stm32

Question: Trying to debug my sample blink_led code on STM32L476 Nucleo-64 board but gdb can't connect to OpenOCD (connection drops almost instantly with error). I've read plenty of posts here and there but none of them helped. Tried adding commands to OpenOCD using -c but no change of behavior.
My code compiles both in Release and Debug config in Eclipse. I can flash the bin file using drag and drop (while the board has built-in STLink add-on) and looks the code runs perfectly on the board (LED blinks).
Cross compiling on Centos7 using the following versions:

Toolchain (gdb): gcc-arm-none-eabi-8-2018-q4-major
OpenOCD: 0.10.0-11-20190118-1134

As using eclipse didn't work I tried the command line,
(I'm not an experienced developer in this environment so I could not find any config file closer to my stm32l476 board than the stm32l4discovery.cfg, please let me know if there might be some issues using it)
./bin/openocd -f scripts/board/stm32l4discovery.cfg -c "init"

It starts,
GNU MCU Eclipse 64-bit Open On-Chip Debugger 0.10.0+dev-00462-gdd1d90111 (2019-01-18-11:37)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 500 kHz
adapter_nsrst_delay: 100
none separate
srst_only separate srst_nogate srst_open_drain connect_deassert_srst
Info : clock speed 500 kHz
Info : STLINK V2J28M17 (API v2) VID:PID 0483:374B
Info : Target voltage: 3.244386
Info : stm32l4x.cpu: hardware has 6 breakpoints, 4 watchpoints
Info : Listening on port 3333 for gdb connections
Info : Listening on port 6666 for tcl connections
Info : Listening on port 4444 for telnet connections

Then starting GDB:
./arm-none-eabi-gdb ~/eclipse-workspace/test-blink-led/Debug/test-blink-led.elf

then running the following command in gdb:
(gdb) target remote localhost:3333
Remote debugging using localhost:3333
Remote connection closed

As it shows gdb connection drops instantly and OpenOCD prompts the following errors:
Info : accepting 'gdb' connection on tcp/3333
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x080022e6 msp: 0x20017ff8
Info : device id = 0x10076415
Warn : STM32 flash size failed, probe inaccurate - assuming 1024k flash
Info : flash size = 1024kbytes
Error: auto_probe failed
Error: Connect failed. Consider setting up a gdb-attach event for the target to prepare target for GDB connect, or use 'gdb_memory_map disable'.
Error: attempted 'gdb' connection rejected
Error: jtag status contains invalid mode value - communication failure
Polling target stm32l4x.cpu failed, trying to reexamine
Examination failed, GDB will be halted. Polling again in 100ms

So from those geeks who do it on a similar platform on a daily basis, can anyone help and tell me where am I doing wrong. Does missing any compile-time flag might result in this problem?
I'm scratching my head for a couple of days now so please let me have your hints.
Answer: One of the reasons may be that your STLINK firmware seems pretty old (STLINK V2J28M17 as your log shows). I suggest downloading the STSW-LINK007 application to upgrade the firmware. The software is a multiplatform Java application. It works flawlessly in Debian GNU/Linux.
Currently, I use another gdb server texane/stlink for my debugging task with GDB without any problem on some Nucleo and also custom boards. I use target extended-remote command to join the port of the server. Maybe you can try to connect with this command also under OpenOCD.
Comment: You are the goddess. I could never think of this. Looks like the firmware was outdated. After upgrading to **V2J34M25 (API v2)**, it connected successfully, although i still have some other issues. Thanks for your time.
Answer: Try
telnet localhost 4444
it worked for me, while 3333 didn't
Comment: The port 4444 is indeed for telnet connection, but actually 3333 is the gdb server port.

Gdb can't connect to OpenOCD on stm32


Creating a gently moving 2D fog effect

Question: I am trying to create a fog-like effect, similar to that found using perlin noise. I know where I can find information about that effect, but it's harder for me to tell if it's an efficient route for what I want to achieve. A similar effect can be seen here, although I'd imagine what I want is much lower in detail: Animated perlin noise | youtube.com
I am currently working in openframeworks. What I have done so far is build a grid of noise values, and have worked towards linearly interpolating in-between those. I feel like I am on the right track, but it very blocky, which makes me wonder if my approach is totally off-mark. This page on Perlin noise has been helpful: Understanding Perlin Noise | flafla2.github.io
for(int x = 0; x < grid.getWidth(); x++){
    if(x % g_size == 0){
        for(int y = 0; y < grid.getHeight(); y++){
            if(y % g_size == 0){
                noise = ofNoise(x,y,ofGetElapsedTimef());
                grid.setColor(x,y,ofFloatColor(noise));
            }
        }
    }
}

ofVec2f g1, g2, g3, g4;
float f1, f2, f3, f4, u, v, t_1, t_2;

for(int x = 0; x < grid.getWidth(); x++){
    for(int y = 0; y < grid.getHeight(); y++){
        //find neigboring grid points
        g1 = ofVec2f(x-(x % g_size),y-(y % g_size));
        g2 = ofVec2f(g1.x + g_size,g1.y);
        g3 = ofVec2f(g1.x,g1.y + g_size);
        g4 = g1 + g_size;

        //get noise values from the grid neighbors
        f1 = grid.getColor(g1.x,g1.y).r;
        f2 = grid.getColor(g2.x,g2.y).r;
        f3 = grid.getColor(g3.x,g3.y).r;
        f4 = grid.getColor(g4.x,g4.y).r;

        u = (float)(x % g_size)/g_size;
        v = (float)(y % g_size)/g_size;

        t_1 = ofLerp(f1,f2,u);
        t_2 = ofLerp(f3,f4,u);

        ofColor average = ofLerp(t_1,t_2,v);

        fog.setColor(x,y,average);
    }
}

Answer: Animated noise can be created by using time as an extra dimension. So instead of 2D noise, you'd use 3D noise with time as the z-axis position, like ofNoise(x, y, time).
To control the level of detail, you'd use octaves of noise: multiple noise layers with different scales and amplitudes, mixed together. The basic Perlin routines just generate a single octave, so you can re-invoke it with scaled coordinates to add more detail, something like:
float noise = ofNoise(x, y, time);          // first octave
noise += 0.5 * ofNoise(2*x, 2*y, 2*time);   // second octave
noise += 0.25 * ofNoise(4*x, 4*y, 4*time);  // third octave

and so on. The more octaves you put in, the more detailed the noise will be. The article you linked describes this in more detail if you scroll down to Working with Octaves.
Comment: You can animate the FBM noise also by scrolling the octave textures without the need for extra texture dimension.
Comment: Great! Do you have any advice on how to begin changing the level of detail?
Comment: @fluffological_studies Yeah, you do it by mixing multiple octaves of noise together. I added something to the answer about that.
Comment: How does that work @JarkkoL

Creating a gently moving 2D fog effect


When are you allowed to attack?

Question: In Runeterra, there's an "attack token" that alternates between players each round and allows you to attack.
If you have the attack token and want to attack that round, do you need to do it as soon as the round begins, or can you play minions and/or spells first, then attack later in the round?
Answer: You can atack any time you have your attack token. So playing some units or spells first is possible.
Cards that say "ready your attack" let you gain an attack token, so multiple attacks per round are possible as well.

When are you allowed to attack?


Simulator and my iphone are not running my apps?

Question: I have checked multiple times in my code there are no errors or warnings. When i install it in simulator or my iphone it doesn't get past the splash screen. It just quits and doesn't say anything about crashing.
Any ideas?
Comment: Are you using IB in your project? if so, is everything hooked up properly? also try debugging your app delegate to see how far it gets (if IB isn't the issue).
Comment: Look at the GDB console first.
Answer: You should take a look at the crash logs for the device. After you sync it to your computer they will be stored at:
<code>~/Library/Logs/CrashReporter/MobileDevice/<DEVICE_NAME>
</code>
Simulator crash logs are here:
<code>~/Library/Logs/DiagnosticReports/
</code>
They have a file extension of <code>.crash</code>
See Here:
http://www.anoshkin.net/blog/2008/09/09/iphone-crash-logs/
Comment: Never mind I misspelled one view controller name, it didn't give me a warning but now it works.


Missing brace error on give command

Question: I'm typing in the command:
/give @p lever 64 0 {can_place_on : ["minecraft:iron_block"]}

and it keeps on coming up with:

line 1 column 2 missing '}' or object member name

I don't see what I'm doing wrong
Comment: I'm not familiar with xbox commands, but I know that in 1.13 Java Edition the correct synax is /give @p lever{CanPlaceOn:["iron_block"]} 64. You could also try /give @p lever 64 0 {CanPlaceOn:["iron_block"]} If you're in 1.12 or under.
Comment: @SpiceWeasel the data tag is in the correct spot.  I think the issue is the spaces, which you aren't allowed to have within the data tag AFAIK.
Comment: I tried it without spaces but I didn't work
Answer: the spaces may be messing it up. try only doing give @p lever 64 0 {CanPlaceOn:["iron_block"]}.
Comment: The command didn't work
Comment: okay. i'm not sure how accurate it is since i don't have my Xbox One near me at the moment to test, but the [Minecraft Bedrock Wikia page](https://minecraftbedrock.fandom.com/wiki/Thread:217291) says that ``/give @p  1 0 {"minecraft:can_place_on":{"blocks":[""]}}`` should work effectively.

Missing brace error on give command


parallel build not working with release plugin

Question: Maven -T not working with release plugin
Comment: Can you explain in detail what you mean by `maven does recognizes correct no. of threads used`? Do you know exactly what `-T 1C` means? `mvn deploy` have you tried it? and what is `mvn release`? What do you mean exactly by: `While using it with release simply fails with..`? Can you show the exact commands you have use? Does your build correctly work ? How many modules do you have? Do you have unit tests?
Comment: @khmarbaise Added errors and testing done. Have read about parallel build support with maven 3.x, but have only seen its implementation with install phase
Comment: Which  Maven version do you use? And which JDK do you use? You have not answered the questions about: How many modules do you have ?
Comment: Can you please show full pom files etc. and answer the questions...
Answer: I start to write as answer cause the comment area is too limited.
The mentioned point 2. must have failed with an error cause -T requires parameters (Missing argument for option: T`)
Furthermore the given call release:prepare release:perform clean install deploy is simply wrong.
Let us begin with some basics. A combination of install and deploy shows that there is a misunderstanding about the Maven life cycle.
So using install only makes sense if you want to install the artifacts only into your local repository ($HOME/.m2/repository) to be consumed by other project on the same machine which is usually not the case.
Using deploy (which includes install) is used to upload the created artifacts into a remote repository (like Nexus, Artifactory) which is in corporate environments the case.
Based on the output I can see that you are using extremely old plugin versions like maven-dependency-plugin:2.1: this version is ten years old. Furthermore I see the usage of a sources goal which is used to resolve sources of the dependencies where I would ask: Why do you need that?
The mentioned point 1:
mvn deploy -U -T 1C -DskipTests -Dmaven.install.skip=true

this shows that you have not understand the purpose of install and deploy phase cause the install phase is needed to install the artifacts and deploy phase will transfer them to the remote repository which means it does not make sense to skip the install part (I doubt that this will work). Furthermore using -U only would make sense if you have SNAPSHOT dependencies otherwise this is waste of time.
The usage of -DskipTests gives me the impression you seemed to have long running unit tests (or they might be integration tests instead?)...
To make a release with Maven you should go:
mvn release:prepare release:perform

Nothing else. Based on the supplemental parameters you are giving during a release it looks like your pom files seemed to be not in optimal state.
The given option -DcheckModificationExcludeList=pom.xml looks from my point of view like a problem cause usually you don't need that and furthermore during a release the pom.xml will be changed (the version) so from that point of view it does not make sense. The modification is to check if something not checked in before running a release..(The whole thing looks not concise to me).
Based on the error message you have given:
[ERROR] Failure executing javac, but could not parse the error:

I bet your maven-compiler-plugin version is very old? Which version do you use?
I recommend to use an up-to-date version of maven-release-plugin which is hopefully correctly configured in your pom file (which I can't tell you cause you haven't showed the full pom files).
Also I recommend to use a most recent version of Maven and check all plugins (using most recent versions) and in particular the configuration of the appropriate plugins if the configuration is correct and really needed and fulfills your needs.


Opposite to jQuery .remove

Question: I have an input form I am trying to remove/add on a click function.
Here is my code:

Share as @<?php echo $_SESSION['username']  ?>

  <input id="twitter" type="hidden" name="twitter" value="yes"/>

You can see that on click of the span id="1" it removes the image and the input form. And when you click on the img id="2" it hides that one and bring backs the original image. How can I bring back or add the input form that I originally remove on the click of the img id="2". Is there a function that is opposite of .remove?
Thanks!
Comment: FYI: api.jquery.com - just peruse for 30 mins - it will blow your mind.  The problem with asking for specific methods is sometimes you don't even know there is a question to ask.  Learn the whole API and become a NINJA!
Answer: Use detach if you need to preserve existing jQuery data:
var twitpar = $('#twitter');
var twit = $('#twitter').detach();

then to reattach:
twitpar.append(twit);

Comment: `detach()` removes the selected element, so `twitpar = $("#twitter").parent();`.
Answer: you can .clone() what you want
you can replaceWith() what you want
;)
Answer: you have such a weird case and code here.
After remove it, you need to add or append it again.
 $(document).ready(function(){
    var $one = $('#1');
    var $two = $('#2');
     var $twitter = $('#twitter');
            $one.click(function () {
                $one.hide();
                $two.show();
                $twitter.remove();
            });

            $two.click(function () {
                $one.show();
                $two.hide();
                $twitter.parent().append('<input id="twitter" type="hidden" name="twitter" value="yes"/>');
            });
 });

instead of 'hard-coding' the element, you can use template like jQuery template or mustache.js, etc.
usually I use iCanHaz. so that the code could be like this
$twitter.parent().append(ich.twitter({value: 'yes'});

and you define the twitter in

Opposite to jQuery .remove


Java Instantiating the implementation of Queueadt

Question: This is a general question about the syntax of instantiating an ADT implementation.
So I created a class call Airline that implements the Queue interface and I needed an instantiation of an arrival queue, for example, based off of the Airline type
What is the difference between
private Queue<Airline> queue = new Queue<>();

and
private Queue<Airline> queue = new Queue<Airline>();

Comment: No difference, the former is syntactic sugar
Comment: The only difference is that first code sample would only compile with java 7 and higher.
Answer: private Queue<Airline> queue = new Queue<Airline>();

The above is how generic types have had to be specified since they were released in Java 5. You have a Queue of generic type Airline, so you instantiate it as such (on the right hand side) and declare it as such (on the left hand side.)
Java 7 however introduced the diamond operator, which allows the generic type that's being instantiated to be infered from the generic type that's declared:
private Queue<Airline> queue = new Queue<>();

So in this example, the compiler infers that the instantiated type should be Queue<Airline> from the declaration, and treats it as such.
As said in the comments above, the difference is purely syntactic sugar, so purely with compilation. The compiled bytecode and thus runtime behaviour will be identical for both cases.


Date formatting on x-axis highchart

Question: I am a beginner in highcharts. I was trying something and got stuck. I tried to plot a line graph using json data . The graph is plotting correctly but in x-axis date is not showing correctly always it showing jan 1 1971. I want the exact date that given in the json data.
<code>    "linechart":[{
                "name":"Average Conversation Length (In minutes)",
                "data":[["2020,02,12",12],["2020,02,13",13],["2020,02,14",5],["2020,02,15",6],["2020 02,16",8],["2020,02,17",23],["2020,02,18",11]]},
             {
                 "name":"Average Number of Conversations",
                 "data":[["2020,02,12",10],["2020,02,13",21],["2020,02,14",19],["2020,02,15",2],["2020,02,16",3],["2020,02,17",38],["2020,02,18",8]]
             }]
</code>
I tried these much options in x-axis but no result
<code>        xAxis: {
        title: {
            text: 'Average session length (in minutes)'
        },
        tickAmount: 5,
        type: 'datetime',
        dateTimeLabelFormats: {
          day: '%m/%d/%Y',
          week: '%m/%d/%Y',
          month: '%m/%d/%Y',
        },
        labels: {
          style: {
            fontFamily: "Open Sans"
          },
        }
    },
    time: {
        useUTC: false
    },
</code>
Comment: Have you considered to use the xAxis `category` type rather than the `datetime`? Demo: https://jsfiddle.net/BlackLabel/tjyw2cr1/ This solution doesn't require to parse your data.
Answer: Please try this
<code> var data = chartdata.linechart;
for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    obj.data.forEach(d => {
        d[0] = Date.parse(d[0]);
    });
}

console.log(data);
Highcharts.chart('linechart', {
    title: {
        text: 'Average session length by day'
    },

    yAxis: {
        title: {
            text: 'Day'
        }
    },

    xAxis: {
        title: {
            text: 'Average session length (in minutes)'
        },
        type: 'datetime',
    },

    legend: {
        align: 'center',
        verticalAlign: 'bottom',
        x: 0,
        y: 0
    },
    plotOptions: {
        series: {
            label: {
                connectorAllowed: false
            }
        }
    },

    series: data,
    credits: {
        enabled: false
    }
});
Highcharts.setOptions({lang: {noData: "No Data Available"}});
</code>

Date formatting on x-axis highchart


Why do I see two VGA compatible controllers on my PC?

Question: I want to use Ubuntu on a hp pavilion g7-1246ef, but I seem to have problems with the VGA when running Ubuntu on this computer - the cooler is very loud and the laptop is hot, and this doesn't happen when booting in Win7.
Running sudo lspci |more I see this line:

00:02.0 VGA compatible controller: Intel Corporation 2nd Generation
  Core Process or Family Integrated Graphics Controller (rev 09)

But after pressing enter several times (for "more" info) I also see the line:

01:00.0 VGA compatible controller: Advanced Micro Devices [AMD] nee
  ATI Seymour [Radeon HD 6400M/7400M Series]

Why are there two VGA?
Comment: You seems to have exactly the seem config of my Samsung -- it is an hybrid graphic. See http://askubuntu.com/a/390050/16395 and the other answers...
Answer: You see two because you have two. It's called ATI Dynamic Switchable Graphics.

One on-CPU Intel for energy-efficiency
One discrete card (an ATI/AMD Radeon HD 6470M in your case) for rendering.

This is a very similar setup to the Nvidia Optimus and it carries similar issues under Linux, only it seems there hasn't be as much effort go into fixing the situation as there might have been with Nvidia... There are some pretty hacky guides out there:

http://ubuntuforums.org/showthread.php?t=1930450
https://wiki.archlinux.org/index.php/hybrid_graphics#ATI_Dynamic_Switchable_Graphics

Looking at the Arch guide there, it looks like this is going to get better with the open drivers now they've landed power management but really, until then you're stuck hacking in the proprietary driver with the first guide.
You could just ignore this until things are "better" (14.04 should give you a better base) but until then your ATI card is going to be running at full power.
Comment: But now that I see --- he has a 12.10. For my instruction to work, he'll need at least kernel 3.11 (In 13.10).
Comment: I have quite good behavior (at least for normal graphic usage) with the open source drivers, see the answer I posted here: http://askubuntu.com/a/390050/16395. Got very low temperatures and a quite silent laptop. Not so bad really.
Comment: @Rmano - i will upgrade if that would help, i was just about to try linux on this laptop and was wandering whether to keep it or not
Comment: My laptop went from 90 °C and fan on constantly to 60 °C and fan almost silent, 3.5 hours on battery. YMMV... Notice that I need to instfall with nomodeset and then add the parameters as explained there...
Comment: Yeah it's almost certainly worth it (if only to get some power management for the discrete card) but it still looks like a fair amount of work.


Font "Ubuntu" is missing the U+26B7 Chiron Unicode Character

Question: It seems like the default font "Ubuntu" is missing the character "⚷" Which makes smartgit to fallback to the next font "Noto" which has a strange line-height, so all commit lines with that kind of "key" icon are half a line off to the bottom:

We found out that the Noto font is used as replacement for the Ubuntu font with
FC_DEBUG=4 pango-view --font=Ubuntu -t "⚷ testString"

The problem comes from 26b7 being almost twice as high as regular text:
81x17 = GC.stringExtent("X test string")
80x31 = GC.stringExtent("⚷ test string")
The entire font 'Noto Sans Symbols' is bigger then its regular counterpart 'Noto Sans'.
How do I add the missing character to the "Ubuntu" font? Or where do I have to complain about the missing icon?
Note: I have installed the package kubuntu-settings-desktop which maybe caused Noto to be the fallback font.
Update:
I installed gucharmap with which I can view all installed fonts search for the CHIRON character (⚷) and it is not there (You need to enable 'View' -> 'Show only glyphs from this font').
Comment: https://bugs.launchpad.net/ubuntu-font-family
Comment: https://askubuntu.com/questions/689607/how-do-i-resolve-missing-characters-in-my-unicode-font check if helps
Answer: There seems no easy solution. But at least it is fixed in SmartGit 20.2 now.
As a Workaround you could disable the "Noto Sans Symbols" font with
sudo mkdir /root/fonts-backup/
sudo mv /usr/share/fonts/truetype/noto/NotoSansSymbols* /root/fonts-disabled/

to restore the font, restore from the backup folder or reinstall with
sudo dpkg -l |grep noto|grep ii|cut -d" " -f 3 | xargs sudo apt install --reinstall


Activate Steel Series Laptop Keyboard backlight on MSI GT72

Question: After installing Linux 14.04 on my new MSI GT72 gaming laptop I can not seem to figure out how to get my back lite LEDs to work on my keyboard. The laptop has a steel series keyboard. I have searched for possible answers, but the closest I could find was some unable to find drivers for his external LED mouse. On Windows you would use the steel series engine to manage your LED keyboard. Is there a way to get them to work on Linux?
Thank you all for any help or advice!
Answer: From my experience with Lenovo's Thinkpad keyboards I would at least try the following button combinations from the MSI manual:

Also check that you have installed the latest firmware, the following caught my attention:

Support Fn/Win key swap function

If they can do that, then they should be able to implement at least basic backlight functionality like on other notebooks.
As always, make your voice heard, tell their support team nicely that you also want to use Ubuntu on the laptop and have the full experience.
Answer: Having purchased the same laptop i can tell you that the backlight is initialised and controlled through the steel series utility bundled with your windows install. Notice how the LEDs don't come on until it initialises?
Unless an ubuntu steel series utility is released its not going to happen!
Answer: On the new MSI Sword laptop, you hold down the FN Key located bottom right of keyboard and press the F8 key to turn on and repeatedly to dim the LED's or cycle through for on-dim-dimmer-dimmest then off. How did I find this to work? through hunt and peck..


CGridView Filter Multiple Models

Question: I have searched and searched for an answer to my problem but neither of them worked. My problem is regarding the filtering/searching in the CGridView for Yii.
In my Applicant model I have the following:
<code>private $_city = null;
private $province_id = null;
public function getCity()
    {
        if($this->_city === null && $this->address_id !== null) {
            $this->_city = $this->address->city;
        }

        return $this->_city;
    }

    public function setCity($value)
    {
        $this->_city = $value;
    }

public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->with = array('address'=>array('alias'=>'address'));

        $criteria->compare('id',$this->id);
        $criteria->compare('phn',$this->phn);
        $criteria->compare('gender',$this->gender);
        $criteria->compare('dob',$this->dob,true);
        $criteria->compare('first_name',$this->first_name,true);
        $criteria->compare('last_name',$this->last_name,true);
        $criteria->compare('band_id',$this->band_id);
        $criteria->compare('note',$this->note,true);
        $criteria->compare('address.city',$this->city);
        $criteria->compare('address.province_id',$this->province_id);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'sort'=>array(
                'attributes'=>array(
                    'id',
                    'phn',
                    'first_name',
                    'last_name',
                    'band_id',
                    'city'=>array(
                        'asc'=>'address.city ASC',
                        'desc'=>'address.city DESC',
                    ),
                    'province_id'=>array(
                        'asc'=>'address.province_id ASC',
                        'desc'=>'address.province_id DESC',
                    ),
                )
            )
        ));
    }
</code>
In my View I have
<code>$this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'applicants-grid',
        'dataProvider'=>$model->search(),
        'filter'=>$model,
        'columns'=>array(
            'first_name',
            'last_name',
            'phn',
            array(
                'name'=>'band_id',
                'value'=>'$data->band->name',
                'filter'=>CHtml::listData(Band::model()->findAll(), 'id', 'name')
            ),
            array(
                'name'=>'city',
                'value'=>'$data->address->city', // causes 'Trying to get property of non-object' - no error if $data->city
                'filter'=>CHtml::listData(Address::model()->findAll(), 'city', 'city'),
            ),
            array(
                'class'=>'CButtonColumn',
                'template'=>'{view}',
                'buttons'=>array(
                    'view'=>array(
                        'url'=>'Yii::app()->createUrl("/applicant/view", array("id"=>$data->id))',
                    )
                )
            ),
        )
    ));
</code>
I have the cities and drop down list showing but when I choose are city from the dropdown it does not filter the widget with the proper results.
I have tried doing the solutions in the following pages
http://www.yiiframework.com/forum/index.php?/topic/11546-cgridview-with-mulitple-model/
http://www.yiiframework.com/forum/index.php?/topic/19913-cgridview-with-multiple-models/
Answer: Are you searching on the primary key of the city table in your compare statement?
E.g., if the PK of city is "city_id" you would need to change the lines below in your model and view, respectively:
<code>$criteria->compare('address.city_id',$this->city);

'filter'=>CHtml::listData(Address::model()->findAll(), 'city_id', 'city')
</code>
(In this example you would leave "city" as the name so it displays as text in the grid, but specify the PK, city_id, in the listData in the value attribute.)
Comment: No. I'm just trying to filter the cities. There's not lookup table for the city since the user can put any city they want so I the dropdown list is a list of the cities that the users have entered.
Comment: Well then I would use Firebug or similar to make sure the right data is getting passed and that there are no JS errors. If the city names are getting into the list ok, then your relation would seem to be ok there, but it's not clear if you are still getting errors as per the php comment. You could also turn on query logging or use MySql log to get some insight as to what the query is trying to do.
Comment: Also, if it's an issue of the city fields sometimes being blank, you could see: http://stackoverflow.com/questions/6775347/yii-framework-picking-up-field-value-from-other-model for how to structure the value.
Comment: some city fields can be blank. I shall look into firebug next time i work on it again. thanks for the help.

CGridView Filter Multiple Models


Oracle ODBC connection to SQL Server: Table Name Length Issues

Question: I'm running into a problem when accessing a SQL Server table from an Oracle setup via ODBC.
I can access 90% of the tables absolutely fine, but there's a few tables that have a name that's longer than 30 characters.  Whenever I try to interact with the table (describes, selects, etc) Oracle throws an "identifier too long" error and gives up.
Is there a way to coax Oracle into playing nice with the SQL Server tables?
Answer: Assuming that we are talking about an Oracle database that has a database link created to a SQL Server database via Heterogeneous Services, you would need to write code using the DBMS_HS_PASSTHROUGH package to interact with the tables in question.  You'd also need to use this package if you have tables where there are column names that are not valid Oracle identifiers.
Comment: Wow, that really adds a layer of complexity.  Suddenly doing a "create table ____ as select" is a lot more roundabout.
Comment: @GigaWatt - Yeah.  It's definitely not as slick.  But it's not that bad if you've ever done anything with `DBMS_SQL` or with a client API like OCI-- it's very similar.


Alternatives to table view within a table view for two levels of detail view

Question: Imagine an app that allowed the Beatles to work on multiple albums at the same time. So on the left you have a list of two albums (Abbey Road and Sergent Pepper's) and if you select Abbey Road, it gives you a list of all the songs on Abbey Road. If you select one of those songs ("Come Together" in the example below), it opens the text of that song in a detail view and allows you to edit the song lyrics. So instead of a Master Detail set up, it's like a Master Master Detail arrangement with two table views and a detail view. Persistence will be done with Core Data.
Is this the recommended way to do it? I've seen some comments online that nesting table views is not great UI.

TableView                 TableView                                 Detail

    Albums (list)              **AbbeyRoad**   (songlist)            Come Together (songtext)

    1.AbbeyRoad            ComeTogether                       Here come old flattop blah blah
    2.Sergent Pepper's     Something
                           Maxwell's Silver Hammer
Comment: I guess you need this https://github.com/OliverLetterer/SLExpandableTableView
Answer: Never, ever, ever put one table view inside another. Gack. That's a user interface disaster in the making.
You could use a sectioned table view, where the sections are albums, and the rows within a section are the songs.
For iPad, you could have side-by-side table views, but that doesn't work on iPhone.
Apple intends you to use a split view controller for that on iPad, and a sequence of master>detail>sub_detail view controllers on iPhone. You can go down as many levels as needed.
Comment: Isn't a `master > detail >sub_detail` set up similar?  if I used that pattern, the `detail` would contain a list of songs, each of which would need to be able to segue to a sub_detail with the lyrics for each song. Can you explain how your suggestion is much different?
Comment: Different from what? I got the impression you were talking about trying to put table views inside each cell of a table view, which would be a disaster.


How to read a large number of LDAP entries in perl?

Question: I already have an LDAP script in order to read LDAP user information one by one. My problem is that I am returning all users found in Active Directory. This will not work because currently our AD has around 100,000 users causing the script to crash due to memory limitations.
What I was thinking of doing was to try to process users by batches of X amount of users and if possible, using threads in order to process some users in parallel. The only thing is that I have just started using Perl, so I was wondering if anyone could give me a general idea of how to do this.
Comment: http://perldoc.perl.org/Thread/Queue.html
Answer: If you can get the executable ldapsearch to work in your environment (and it does work in *nix and Windows, although the syntax is often different), you can try something like this:
my $LDAP_SEARCH = "ldapsearch -h $LDAP_SERVER -p $LDAP_PORT -b $BASE -D uid=$LDAP_USERNAME -w $LDAP_PASSWORD -LLL";
my @LDAP_FIELDS = qw(uid mail Manager telephoneNumber CostCenter NTLogin displayName);
open (LDAP, "-|:utf8", "$LDAP_SEARCH \"$FILTER\" " . join(" ", @LDAP_FIELDS));
while (<LDAP>) {
  # process each LDAP response
}

I use that to read nearly 100K LDAP entries without memory problems (although it still takes 30 minutes or more).  You'll need to define $FILTER (or leave it blank) and of course all the LDAP server/username/password pieces.
If you want/need to do a more pure-Perl version, I've had better luck with Net::LDAP instead of Net::LDAP::Express, especially for large queries.


Regular expression capturing groups

Question: With the following regular expression:
InitValue\((\w*)\)

and the test string:
InitValue(Input1)

I get the following result:
Full match: InitValue(Input1)
Group1: Input1

With the following regular expression:
InitValue\((\w*)\s*,\s*(\w*)\)

and the test string:
InitValue(Input1, Input2)

I get:
Full match: InitValue(Input1, Input2)
Group1: Input1
Group2: Input2

Now I would like to capture any number of arguments to the InitValue-method. The number of arguments to InitValue are unknown.
Full match: InitValue(Input1, Input2, ..., Inputn)
Group1: Input1
Group2: Input2
....
Groupn: Inputn

Of course I can't repeat the following pattern in my regular expression since I don't know the number of arguments in advance:
\s*,\s*(\w*)

How do I write a regular expression which outputs n number of capture groups?
I use the regular expression in C#-code (Regex, Match)...
Answer: .NET supports infinite lookbehind (?<=. Instead of getting capturing groups, another option could be to get the matches instead:
(?<=\bInitValue\([^()]*)[^, ]+(?=[^()]*\))

Explanation

(?<= Positive lookbehind, check what is on the left matches:

\bInitValue\([^()]* Match wordboundary, InitValue( and then 0+ times not any of ( or )

) Close positive lookbehind
[^, \t]+ Negative character class, match 1+ times not a space or comma
(?= Positive lookahead to check what is on the right matches:

[^()]*\) Match 0+ times not any of ( or ), then match )

) Close positive lookahead

For example:
string pattern = @"(?<=\bInitValue\([^()]*)[^, ]+(?=[^()]*\))";
string str = "InitValue(Input1, Input2, Input3)";
foreach (Match m in Regex.Matches(str, pattern))
{
    Console.WriteLine(m.Value);
}

Result
Input1
Input2
Input3

See the Regex demo | C# demo
Answer: It is possible to do this in .NET - you use a single capture Group, and then you access the Group's Captures collection to see all the items it captured, not just the final Value.
You'll have to write a regex that can repeat the argument-matching group, something like
InitValue\((?:(\w+)\s*(?:,(?!\s*\))|(?=\s*\)))\s*)*\)

Have a play around with the Debuggex Demo to get it to match what you want.
Answer: static void GetParams()
{
    int x = 0;
    var strings = new[]
    {
        "InitValue()",
        "InitValue(Input1)",
        "InitValue(Input1, Input2, Input3, Input4)"
    };

    var pattern = @"(\w+)\((?:(\w+)(?:,?\s*))*\)";

    foreach (var s in strings)
    {
        WriteLine($"String: '{s}'");
        var match = Regex.Match(s, pattern);
        if (match.Success)
        {
            WriteLine($"\tMethod: '{match.Groups[1].Value}'");
            WriteLine("\tParameters:");
            var captures = match.Groups[2].Captures;
            if (captures.Count > 0)
            {
                x = 0;
                foreach (Capture capture in captures)
                {
                    WriteLine($"\t\tParam {++x}: '{capture.Value}'");
                }
            }
            else
            {
                WriteLine("\t\tNo params found.");
            }

            WriteLine();
        }

        else
            WriteLine("No matches found.");
    }
}

/*
Output:

String: 'InitValue()'
        Method: 'InitValue'
        Parameters:
                No params found.

String: 'InitValue(Input1)'
        Method: 'InitValue'
        Parameters:
                Param 1: 'Input1'

String: 'InitValue(Input1, Input2, Input3, Input4)'
        Method: 'InitValue'
        Parameters:
                Param 1: 'Input1'
                Param 2: 'Input2'
                Param 3: 'Input3'
                Param 4: 'Input4'
*/

Answer: Don't let anyone tells you what it's impossible and what it's not

You will have to touch it a little bit but I think it can guide you =D.
Edit, answering your question. b.Count will give you the number of matchings.
Edit 2, I post the picture to show the debug info. But here is the code for the sibarist.
string bar = "test, othertest";
Regex reg = new Regex(@"[\w]+");

MatchCollection b = reg.Matches(bar);

string b1 = b[0].Value;
string b2 = b[1].Value;

int numberGroups = b.Count;

Edit 3, as suggested in the comment this is the complete solution, you will need to clear the InitValue(*) part with another Regex or with a Substring
string input = "InitValue(test, othertest, bleh, blehTest, foo)";

Regex regArgs = new Regex(@"(?:InitValue\()(.*)(?:\))");
Match matchArgs = regArgs.Match(input);

string valueArgs = matchArgs.Groups[1].Value;

Regex reg = new Regex(@"[\w]+");

MatchCollection b = reg.Matches(valueArgs);

string b1 = b[0].Value;
string b2 = b[1].Value;

int numberGroups = b.Count;

Comment: Please, show how do you apply this technique to the test string: `InitValue(Input1, Input2, Input3, Input4)`
Comment: What do you mean? As I said, this is only ilustrative, not the full solution, but close enough. You can easily delete the `InitValue(*)` with a `Substring`and keep the arguments, if you mean that it is impossible when it's written InitValue, then yes, you are right, but that's far from being impossible =D

Regular expression capturing groups


XPath validation using Regex

Question: Try as much as possible to describe the problem in detail.
For example, I have xml file:
<?xml version="1.0"?>
<root>
   <paths>
      <path>
         <file>
        <id>1</id>
        <name>example</name>
     </file>
     <options>
        <isreadonly>true</isreadonly>
     </options>
      </path>
   </paths>
</root>

And have XPahts:

root/paths/path/file/id
root/paths/path/file/name
root/paths/path/options/isreadonly

How to validate this paths with regex?
I can validate one xml element name with this regex - ^(?!XML)[a-zA-Z][\w]*$, but I need String.Split(this string) and then use regex in loop.
This is naming rules of xml element name:

Names can contain letters, numbers, and other characters
Names cannot start with a number or punctuation character
Names cannot start with the letters xml (or XML, or Xml, etc)
Names cannot contain spaces

Not valid paths:

xml/...
.../xmlang/...
.../1asdf/...
1/.../...
.../_asdf/... etc.

Thanks.
Comment: `XPathExpression.Compile` ?
Comment: I need a simply regex string. I need to mark a property of model with [RegularExpression("")] attribute or use this regular expression on the client side with java script.
Answer: If you intend to mark a property on your model anyway you would just make a custom property that checks if the expression compiles.
This will be a lot easyer then trying to regex it.
As since regex is not the tool you want to parse => https://softwareengineering.stackexchange.com/questions/113237/when-you-should-not-use-regular-expressions (see the accepted answer).
A custom attribute can be made as following:
public class MyCustomAttribute : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
     {
        //Your logic here.
        return ValidationResult.Success;
     }
}

Comment: In my opinion both aren't regular and should only be parsed by a parser. None the less it's not impossible to use regular expressions on them like it's not impossible to do the same for HTML. It's just something most would frown upon.
Comment: I'm wondering does the language defines XPath's syntax is regular or not? have you any information about that?
Comment: Can you rephrase your question?
Comment: Are you familiar with language theories, right? actually, XPath syntax defines a language that determines whether a given string is in the language or not, in other words it determines whether it can be considered as valid Xpath. only if the language is regular we can write a regular expression that generates the same language else we can not. for example if the language is Context-free language we only describe it using a parser and there is no way to define it using a regular expression. So my question is Do you know what the class of Xpath syntax language belongs to.
Comment: I have the same question about JsonPath syntax because these two syntaxes have lots of common

XPath validation using Regex


Does the Hopper Minecart trick work on Minecraft Bedrock edtion

Question: In Minecraft Java, a Minecart with Hopper will still collect items from the block immediately above that block, unlike a hopper on its own. My question is whether this still works in Bedrock Edition.
Answer: According to the wiki:

A minecart with hopper pulls in items lying nearby (within a range slightly larger than the cart itself), or inside a container above the track, at a rate of up to 20 items per second, much faster than an ordinary hopper. It also picks up items that are lying on a block directly above the track. It does not push items into containers, but a hopper underneath the track can remove items from a minecart with hopper on the track. Ordinary hoppers can also drop items into a minecart with hopper like other containers, at the normal speed of 2.5 items per second.

After a quick test, yes, it does work in minecraft-bedrock-edition:
Answer: Yes, it does work exactly as it does in Minecraft Java edition. Placing a minecart under a block will allow you to pick up items that are on the block that the minecart is placed under. I have done this many times in things like sugarcane farms or key-card piston doors.


How to Drag and Drop DataGrid column header?

Question: I am working with WPF DataGrid. I have to drag the Column Header, drop it to some other control(say Label) and do some operation. But i am not able to achieve drag and drop of DataGrid Column Header. I have tried with ColumnHeaderDragStarted event, but I am not able to find Column Header object or just the Name of header in the handler.
Any help plz!!
Answer: Maybe this can help you:
On XAML:
<DataGrid Name="DataGrid" MouseRightButtonUp="DataGrid_MouseRightButtonUp" />
On C# Code:
<code>    private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;

        while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridColumnHeader)
        {
            DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;

            // find the property that this cell's column is bound to
            string boundPropertyName = FindBoundProperty(columnHeader.Column);

            int columnIndex = columnHeader.Column.DisplayIndex;

            ClickedItemDisplay.Text = string.Format(
                "Header clicked [{0}] = {1}",
                columnIndex, boundPropertyName);
        }

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;

            // navigate further up the tree
            while ((dep != null) && !(dep is DataGridRow))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            if (dep == null)
                return;

            DataGridRow row = dep as DataGridRow;

            object value = ExtractBoundValue(row, cell);

            int columnIndex = cell.Column.DisplayIndex;
            int rowIndex = FindRowIndex(row);

            ClickedItemDisplay.Text = string.Format(
                "Cell clicked [{0}, {1}] = {2}",
                rowIndex, columnIndex, value.ToString());
        }
    }

    /// <summary>
    /// Determine the index of a DataGridRow
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    private int FindRowIndex(DataGridRow row)
    {
        DataGrid dataGrid = ItemsControl.ItemsControlFromItemContainer(row) as DataGrid;

        int index = dataGrid.ItemContainerGenerator.IndexFromContainer(row);

        return index;
    }

    /// <summary>
    /// Find the value that is bound to a DataGridCell
    /// </summary>
    /// <param name="row"></param>
    /// <param name="cell"></param>
    /// <returns></returns>
    private object ExtractBoundValue(DataGridRow row, DataGridCell cell)
    {
        // find the property that this cell's column is bound to
        string boundPropertyName = FindBoundProperty(cell.Column);

        // find the object that is realted to this row
        object data = row.Item;

        // extract the property value
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(data);
        PropertyDescriptor property = properties[boundPropertyName];
        object value = property.GetValue(data);

        return value;
    }

    /// <summary>
    /// Find the name of the property which is bound to the given column
    /// </summary>
    /// <param name="col"></param>
    /// <returns></returns>
    private string FindBoundProperty(DataGridColumn col)
    {
        DataGridBoundColumn boundColumn = col as DataGridBoundColumn;

        // find the property that this column is bound to
        Binding binding = boundColumn.Binding as Binding;
        string boundPropertyName = binding.Path.Path;

        return boundPropertyName;
    }
}

// This XAML and C# where extracted from a link contained on this URL:
//    http://social.msdn.microsoft.com/Forums/en/wpf/thread/61707b8a-e6c6-474b-ac2b-3446319625bd
</code>


Executable jar closes immediately after launching (Slick2D)

Question: So I made an executable file with Eclipse but when I double-click it nothing happens. It IS NOT because I've got wrong association for running .jar files (I'm running okey my another jar program just by double-clicking it).
I also tried with command prompt and the console doesn't print anything at all and get back to be "normal".
I think it's something with main class so the thread doesn't last but closes after running (however it looks like the code isn't run because console would print lot of Slick stuff).
So here is the main method:
public static void main(String[] args) {
    Shiftjumper shiftjumper = new Shiftjumper("Shiftjumper - behavior prototype");
    try {
        AppGameContainer gc = new AppGameContainer(shiftjumper);
        gc.setDisplayMode(TILE_SIZE*RIGHT_LEFT_TILES, TILE_SIZE*UP_DOWN_TILES, false);
        //gc.setTargetFrameRate(60);

        gc.start();
    } catch (SlickException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

And here the manifest:
Manifest-Version: 1.0
Rsrc-Class-Path: ./ lwjgl.jar slick.jar
Class-Path: .
Rsrc-Main-Class: engine.Shiftjumper
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader

Answer: You need to download a tool known as JarSplice. JarSplice is a very simple GUI based application which packages all libraries and native code into the form of either a .JAR, a .EXE, a.SH or a .APP. Here is a link to the site: http://ninjacave.com/jarsplice
Hope this helps :)
Answer: Try running the jar in your terminal or command prompt, if there are any exceptions it will print to the console and you can debug


How can I make a short timer using only command blocks in 1.9?

Question: Using only MC command blocks (I am using 1.9) how can I create a short timer?
It needs to be command block-only because I am trying to make a 1-block command; I want to make it night time and give the player a night-vision effect for ten seconds, but after the ten seconds I want to revert it back to day-time. I haven't yet figured out how to achieve this final part, of setting it back to day after ten seconds.
So far I have got the command:
summon FallingSand ~ ~1 ~ {
  Block: command_block,
  Time: 1,
  TileEntityData: {
    Command: /time set 18000
  },
  Passengers: [
    {
      id: FallingSand,
      Block: chain_command_block,
      Time: 1,
      TileEntityData: {
        Command: /effect @a 16 10 1 true
      },
      Passengers: [
        {
          id: FallingSand,
          Block: redstone_block,
          Time: 1
        }
      ]
    }
  ]
}

Sorry for the hierarchical mess, but basically, the above code spawns this structure:

Which does exactly what I want it to do: the top command block, just underneath the redstone, gives night vision for 10 seconds, and the bottom command block sets the time to midnight (18000.)

How can I add a bit to this setup to make it wait roughly ten seconds before setting the time back to day?
Comment: Possible duplicate of [How to delay or slowly loop commands?](https://gaming.stackexchange.com/questions/363578/how-to-delay-or-slowly-loop-commands)
Answer: You can make a scoreboard:
/scoreboard objectives add time dummy

Create a entity which counts for you:
/summon ArmorStand ~ ~1 ~ {CustomName:"timeCounter",CustomNameVisible:1}

Make it it invisible and a marker if you want:

/summon ArmorStand ~ ~1 ~ {CustomName:"timeCounter",CustomNameVisible:0,Marker:1b,Invisible:1,Invulnerable:1,NoBasePlate:1,NoGravity:1}

Then a repeating command block which increases this scoreboard every tick (20 ticks = 1 second):
/scoreboard players add @e[CustomName:"timeCounter"] time 1

Put your commands into an execute:
/execute @e[score_time_min=200] ~ ~ ~ effect @a 16 10 1 true

/execute @e[score_time_min=200] ~ ~ ~ time set day

Change the 200 to whatever seconds you want * 20:
Sorry, I first understood your question wrong, just remove the reset.
Comment: You could remove the scoreboard after the 10 seconds: `/scoreboard objectives remove time` So the scoreboard would be there only for 10 seconds
Comment: Thank you for your comprehensive answer! Because this is, undoubtedly, the easiest (and most intuitive) way of accomplishing what I posted in my question, I upvoted this because it could be helpful to browsing users. However, this is not the perfect answer for me, as I wanted to rely on as few external variables as possible (it is eventually going to be a player server, so I don't want any redundant scoreboards left lying around.)
Answer: When I myself was struggling with this problem,  I had an epiphany; why not use a chicken timer?
I could spawn a Chicken far above the command block, and because Chickens fall so slowly I could set up a proximity detector to activate the next set of commands.

While experimenting with the idea I set up this demo (which uses the new 1.9 command blocks):

In the image, there is a repeating command block pointing into a chain command block.
The repeating command block is set to be Unconditional and Always Active, whereas the chain command block is set to be Conditional, but also Always Active.

The repeating command block's /kill @e[type=Chicken,r=2] command will kill any chicken near to it (radius of two), but it also acts as a sort-of testfor command; its output will be successful only if it does manage to kill a chicken.
This means that whenever it can kill a chicken (ie. there is a chicken within two-blocks' distance of it) the chain command block will also execute, because it is set to be Conditional. This means that the chain command block will only execute its command when the repeating command block behind it has been successful, which only happens when there is a chicken within range of the repeating command block's kill selector.
All we need to do now is set the chain command block's command to be something more useful (you want to set the time to day after the command finishes, so therefore the chain command block's command should be /time set day) and use another command block to summon a chicken far above the structure to act as the timer.

Here is the final minified command:
summon FallingSand ~ ~1 ~ {Block:command_block,Time:1,TileEntityData:{Command:/time set 18000},Passengers:[{id:FallingSand,Block:chain_command_block,Time:1,TileEntityData:{Command:/effect @a 16 10 1 true},Passengers:[{id:FallingSand,Block:command_block,Time:1,TileEntityData:{Command:/summon Chicken ~ ~28 ~ {NoAI:1}},Passengers:[{id:FallingSand,Block:redstone_block,Time:1,Passengers:[{id:FallingSand,Block:chain_command_block,Data:8,Time:1,TileEntityData:{Command:/time set day},Passengers:[{id:FallingSand,Block:repeating_command_block,Time:1,TileEntityData:{Command:/kill @e[type=Chicken,r=3]},Passengers:[{id:FallingSand,Block:redstone_block,Time:1}]}]}]}]}]}]}

It creates this structure (the command is placed into the normal bottom command block):

The sequence of events which follow from activating the bottom command block are (in order):

The structure is generated, with all the necessary commands and redstone blocks in place.
A chicken is summoned 28 blocks above the summoning command block (24 blocks above the structure)
The players are all given night vision for ten seconds, and the time is set to midnight.
The chicken, with no AI, slowly falls down towards the structure.
When it is in range of the repeating command block, which tries to kill chickens within three blocks' distance, it is killed.
This successful command then activates the conditional command block below the repeating command block, which sets the time back to day.

A walkthrough of the command:
summon FallingSand ~ ~1 ~ {            // Summon the first command block
  Block:command_block,                 // using falling sand entities.
  Time:1,                              //
  TileEntityData:{                     // This command block sets the
    Command:/time set 18000            // time to midnight, and is at the
  },                                   // bottom of the structure.
Passengers:[{
    id:FallingSand,                    // The next command block is a chain
    Block:chain_command_block,         // command block so that it can pass
    Time:1,                            // the signal to ones underneath it.
    TileEntityData:{                   // This command block gives the
      Command:/effect @a 16 10 1 true  // players the night vision effect.
    },
Passengers:[{
    id:FallingSand,                    // This command block summons
    Block:command_block,               // a chicken with no AI 28
    Time:1,                            // blocks above it.
    TileEntityData:{
      Command:/summon Chicken ~ ~28 ~ {NoAI:1}
    },
Passengers:[{                          // This redstone block activates only
    id:FallingSand,                    // The bottom half of the tower, so
    Block:redstone_block,              // every command block summoned so far
    Time:1,
Passengers:[{                          // This next command block sets the time
    id:FallingSand,                    // back to day. It is a chain command block
    Block:chain_command_block,         // and has to be conditional, the Data: 8
    Data:8,                            // attribute makes it a conditional command
    Time:1,                            // block which points downwards. It is
    TileEntityData:{                   // activated only when the repeating block
      Command:/time set day            // above it is successful.
    },
Passengers:[{
    id:FallingSand,                    // This repeating command block tries to
    Block:repeating_command_block,     // kill a chicken within three blocks of
    Time:1,                            // itself.
    TileEntityData:{
      Command:/kill @e[type=Chicken,r=3]
    },
Passengers:[{                          // I couldn't figure out how to summon an
    id:FallingSand,                    // "Always Active" repeating command block,
    Block:redstone_block,              // so it needs this final redstone block
    Time:1                             // to run.
}]}]}]}]}]}]}

Important Notes
During my testing, I found 28 blocks above to be the optimal distance to summon the chicken for a roughly ten-second timer, however this can be easily adjusted by changing the
/summon Chicken ~ ~28 ~ {NoAI:1}

command to summon at a greater or lesser height.
Also, note that the Passengers attribute in 1.9 has replaced the Riding attribute of earlier versions. Read about these changes here: 15w41a - Official Minecraft Wiki
Finally, the new 1.9 command blocks use their damage values to decide whether to be conditional or not. This is why I had to set the Data property of the second-highest command block to 8, to ensure it was conditional.
Anyone, please post any questions in the comments if you are still confused.


Parallel exists function in F#

Question: Motivation
I have a long-running boolean function which should be executed in an array and I want to return immediately if an element in the array satisfies the condition. I would like to do the search in parallel and terminate other threads when the first complete thread returns an correct answer.
Question
What is a good way to implement parallel exists function in F#? Since my goal is performance, an efficient solution is preferred to an easy or idiomatic one.
Test case
Suppose that I want to find whether one value exists in an array or not. And the comparison function (equals) is simulated as a computation-expensive one:
open System.Diagnostics
open System.Threading

// Source at http://parallelpatterns.codeplex.com/releases/view/50473
let doCpuIntensiveOperation seconds (token:CancellationToken) throwOnCancel =
        if (token.IsCancellationRequested) then
            if (throwOnCancel) then token.ThrowIfCancellationRequested()
            false
        else
            let ms = int64 (seconds * 1000.0)
            let sw = new Stopwatch()
            sw.Start()
            let checkInterval = Math.Min(20000000, int (20000000.0 * seconds))

            // Loop to simulate a computationally intensive operation
            let rec loop i =
                // Periodically check to see if the user has requested
                // cancellation or if the time limit has passed
                let check = seconds = 0.0 || i % checkInterval = 0
                if check && token.IsCancellationRequested then
                    if throwOnCancel then token.ThrowIfCancellationRequested()
                    false
                elif check && sw.ElapsedMilliseconds > ms then
                    true
                else
                  loop (i + 1)

            // Start the loop with 0 as the first value
            loop 0

let inline equals x y =
    doCpuIntensiveOperation 0.01 CancellationToken.None false |> ignore
    x = y

The array consists of 1000 randomly generated elements and the searching value is guaranteed in the 2nd half of the array (so sequential search has to go through at least a half of the array):
let rand = new System.Random()
let m = 1000
let N = 1000000
let xs = [|for _ in 1..m -> rand.Next(N)|]
let i = rand.Next((m-1)/2, m-1);;

#time "on";;
let b1 = parallelExists (equals xs.[i]) xs;; // Parallel
let b2 = Array.exists (equals xs.[i]) xs;; // Sequential

Comment: I updated my answer with an example.
Comment: If the element is guaranteed to be in the second half of the array, why not search on the ``.[xs.Length/2..]`` slice (which copies the array btw) or start searching at xs.Length/2.
Comment: It's just an example to avoid the scenario that the search terminates too early.
Answer: I think you can take the following steps:

Spawn a number of workers (threads or async computations), and pass each an equal slice of the array and a cancellation token which will be shared by all workers
When a worker finds the searched item, it calls Cancel on the token (each worker should check the cancel state of the token on each iteration and bail if needed)

I don't have time at the moment to write the code, so there could be some detail I'm omitting.
This answer, and related question, may be helpful.
UPDATE
This is an example of what I'm thinking
open System
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks

let getChunks size array =
  let rec loop s n =
    seq {
      if n > 0 then
        let r = n - size
        if r > 0 then yield (s, size); yield! loop (s + size) r
        else yield (s, size + r)
    }
  loop 0 (Array.length array)

[<Literal>]
let CHUNK_SIZE = 3

let parallelExists f (array:_[]) =
  use cts = new CancellationTokenSource()
  let rec checkSlice i n =
    if n > 0 && not cts.IsCancellationRequested then
      if f array.[i] then cts.Cancel()
      else checkSlice (i + 1) (n - 1)
  let workers =
    array
    |> getChunks CHUNK_SIZE
    |> Seq.map (fun (s, c) -> Task.Factory.StartNew(fun () -> checkSlice s c))
    |> Seq.toArray
  try
    Task.WaitAll(workers, cts.Token)
    false
  with :? OperationCanceledException -> true

Usage
let array = Array.init 10 id
let exists =
  array |> parallelExists (fun i ->
    Thread.Sleep(500)
    i = 9)
printfn "%b" exists //true

Comment: This would work but `async` makes no attempt to exploit locality so the cache behaviour would be bad and, consequently, it won't scale as well as it could on a multicore because the bottleneck will be IO to shared memory.
Comment: Your idea is nice but `async` is not really suitable to my scenario. I want to speedup a CPU-bound computation while `async` is mainly for IO-bound computation.
Comment: Jon: This may sound lame, but you could copy each slice of the array before passing it to the worker. What solution would you propose?
Comment: @pad: It's trivial to switch this to work with `Task`s, which perform better for CPU bound computations (but have a slightly less desirable syntax).
Comment: @pad: I changed it to use `Task`.
Comment: @Daniel: You approach looks much appealing now. Thanks!
Answer: The F# Powerpack has PSeq.exists which maps to PLINQ's ParallelEnumerable.Any which is part of the BCL. There's also ParallelEnumerable.First
I tried to decompile but wouldn't understand right away what was going on. So instead I went and executed the following side-effecting code to confirm that it's using some sort of cancellation once it found the element:
let elems = seq {
    for x = 0 to 1000000 do
        printfn "test"
        yield x }

open System
open System.Linq;;

ParallelEnumerable.First (ParallelEnumerable.AsParallel(elems), Func<_,_>(fun x -> x = 1))

Comment: I'm aware of `PSeq` but I'm more interested in a solution working directly on the array. In this way, I can avoid the cost of type casting and have more control over degree of parallelism.

Parallel exists function in F#


Automatic screen brightness on Ubuntu 14.10 not working right, manual controls not working at all

Question: My Samsung NP740 has been running Ubuntu fine for 18 months. I did an upgrade to 14.10 and the screen brightness controls stopped working correctly. I did a wipe and fresh install and I still have the same problem.
The symptom is that the brightness is now set automatically, regardless of setting it using the controls. In a bright room, it tries to turn up the brightness automatically, although it's very hit-and-miss. Conversely, in a darker place, it tries to turn the brightness down.
The brightness control has no effect until it's turned down to zero, when the display switches off entirely (and, fortunately, comes back on again when you reverse the process).
How do I switch back from automatic to manual brightness control?
Answer: You can also use command line option to control brightness.
Steps:

Open terminal using ctrl+alt+t.
Type command "xrandr".
It will display something like this:

4.You need to see (in the underlined part) which display is connected. (Here in my case it is LVDS1).

Use following command to adjust brightness:

xrandr --output "your connected display name" --brightness
  "brightness value"

For example, in my case it'd be:

<code>xrandr --output LVDS1 --brightness .75
</code>

Note: Brightness value should be less than 1. (Otherwise it will be too much brightness).
That's it. Hope this helps.
Comment: Good - this works quite well and allows some control over brightness. Is there a way to turn off automatic control (ambient light sensing)? I know the laptop's camera is being used because if I cover the camera lens, it dims the screen right down automatically.


How to debug deadlock in this small multithreaded program

Question: I am new to multithreading and hence started with a small program. The job expected from the program is, to print integers one after the other by means of two threads in such a way that one thread should print one number and the other thread should print the next number and this process should continue till a maximum number defined.
For this I wrote a small program and iam facing dead lock. I tried to find mutex owner using gdb but it;s just printing $3 = 2 when I execute print mutex command.
Here is the source code:
#include <iostream>
#include <fstream>
#include <pthread.h>
#include <signal.h>

const int MAX_NUM = 13;

pthread_cond_t cond[1] = {PTHREAD_COND_INITIALIZER,};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int Count = 0;

using namespace std;

void* thread1(void*)
{
    do {
        cout<<"inside thread 1 abt to acquire lock"<<endl;
        // Increment counter in thread1
        pthread_mutex_lock(&mutex);
        cout<<"inside thread 1 blocked"<<endl;
        pthread_cond_wait(&cond[0],&mutex);
        cout<<"after pthread_cond_wait in thread1"<<endl;
        pthread_cond_signal(&cond[1]);
        if(Count < MAX_NUM)
        {
            Count++;
            pthread_mutex_unlock(&mutex);
            cout<<"Printing from thread 1"<<endl;
            cout<<Count<<endl;
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            pthread_exit(NULL);
        }
    }while(1);
 }

 void* thread2(void*)
 {
     do{
         cout<<"inside thread 2 abt to acquire lock"<<endl;
         pthread_mutex_lock(&mutex);
         cout<<"inside thread 2 blocked"<<endl;
         pthread_cond_wait(&cond[1],&mutex);
         // Increment counter in thread2
         pthread_cond_signal(&cond[0]);
         if(Count < MAX_NUM)
         {
             Count++;
             pthread_mutex_unlock(&mutex);
             cout<<"Printing from thread 2"<<endl;
             cout<<Count<<endl;
         }
         else
         {
             pthread_mutex_unlock(&mutex);
             pthread_exit(NULL);
         }
    }while(1);
}

int main()
{
    pthread_t t[2];
    void* (*fun[2])(void*);
    fun[0]=thread1;
    fun[1]=thread2;

    for (int i =0 ; i < 2; ++i)
    {
        pthread_create(&t[i],NULL,fun[i],NULL);
    }
    cout<<"threads created"<<endl;

    pthread_cond_signal(&cond[0]);

    cout<<"In main after sending signal"<<endl;

    pthread_join(t[0],NULL);
    pthread_join(t[1],NULL);

    pthread_exit(NULL);
}

Output is:
        inside thread 1 abt to acquire lock
    inside thread 1 blocked
    inside thread 2 abt to acquire lock
    inside thread 2 blocked
    threads created
    In main after sending signal
I expected main() thread to send a signal to thread 1 which does it's job (i.e. updating counter) and then passes signal to thread 2 which does it's job (i.e. updating counter) and passes signal to thread 1. This process should continue until max number is reached. If max number is reached each process unlocks mutex and exits gracefully.
Please help me. I really tried a lot nothing worked.
Answer: the line
pthread_cond_t cond[1] = {PTHREAD_COND_INITIALIZER,};

defines an array of size 1, but later on you use cond[1], the second entry in the array, which is undefined. Did you mean
pthread_cond_t cond[2] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER};

This looks like an unlucky typo. (Due to the preceeding MAX_NUM = 13?)
Comment: +1 at least for the nice joke! I also avoid defining constants of _666_, _13_, aso. Baaaad stuff ;o) ...
Answer: In addition to @TooTone's observation you need to understand one aspect of how condition variables work. If you signal a condition variable when no thread is blocked on it nothing will happen. The condition variable has no memory, so if a little bit later a thread blocks on in it will stay locked until the condition is signaled again.
Your main function signals cond[0] right after it started the threads, so it is possible that the threads haven't reached their blocking point yet. Or if they are blocked then it can happen that when one thread signals the other one that other one isn't blocked. So after you fix your condition variable array you will see that the test runs a bit more, but eventually deadlocks again.
I was able to make it work using a quick & dirty trick of introducing delays before signaling the condition variables. This gives the threads time to reach their blocking points before the signaling happens. Here is the modified code:
const int MAX_NUM = 13;

pthread_cond_t cond[2] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int Count = 0;

using namespace std;

void* thread1(void*)
{
    do {
        cout<<"inside thread 1 abt to acquire lock"<<endl;
        // Increment counter in thread1
        pthread_mutex_lock(&mutex);
        cout<<"inside thread 1 blocked"<<endl;
        pthread_cond_wait(&cond[0],&mutex);
        cout<<"after pthread_cond_wait in thread1"<<endl;
        if(Count < MAX_NUM)
        {
            Count++;
            pthread_mutex_unlock(&mutex);
            cout<<"Printing from thread 1"<<endl;
            cout<<Count<<endl;
            usleep(1000000);
            pthread_cond_signal(&cond[1]);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            usleep(1000000);
            pthread_cond_signal(&cond[1]);
            pthread_exit(NULL);
        }
    }while(1);
 }

 void* thread2(void*)
 {
     do{
         cout<<"inside thread 2 abt to acquire lock"<<endl;
         pthread_mutex_lock(&mutex);
         cout<<"inside thread 2 blocked"<<endl;
         pthread_cond_wait(&cond[1],&mutex);
         // Increment counter in thread2
         if(Count < MAX_NUM)
         {
             Count++;
             pthread_mutex_unlock(&mutex);
             cout<<"Printing from thread 2"<<endl;
             cout<<Count<<endl;
             usleep(1000000);
             pthread_cond_signal(&cond[0]);
         }
         else
         {
             pthread_mutex_unlock(&mutex);
             usleep(1000000);
             pthread_cond_signal(&cond[0]);
             pthread_exit(NULL);
         }
    }while(1);
}

int main()
{
    pthread_t t[2];
    void* (*fun[2])(void*);
    fun[0]=thread1;
    fun[1]=thread2;

    for (int i =0 ; i < 2; ++i)
    {
        pthread_create(&t[i],NULL,fun[i],NULL);
    }
    cout<<"threads created"<<endl;
    usleep(1000000);
    pthread_cond_signal(&cond[0]);

    cout<<"In main after sending signal"<<endl;

    pthread_join(t[0],NULL);
    pthread_join(t[1],NULL);

    pthread_exit(NULL);
}

Using condition variables for this kind of thing isn't the best idea. Semaphores are better suited to the task because those do have memory and remember their signaled state even if nobody is waiting on them when they are signaled.
Comment: It's working fine after correcting condition variables declaration...costly typo :)
Comment: @suresh Glad you fixed the typo :)   Re Miguel's post, I thought it was v valuable. Multi threaded programs will sometimes work 99.9% of the time and fail 0.1% of the time. They're not as "deterministic" as single threaded programs, so your code might look ok, but on, for example, a production server might cause significant downtime and problems.


Inclusion-Exclusion Principle; why is this wrong?

Question: I'm unsure where I'm going wrong with this.
In a class of 40 people studying music: 2 play violin, piano and recorder, 7 play at least violina nd piano, 6 play at least piano and recorder, 5 play at least recorder and violin, 17 play at least violin, 19 play at least piano, and 14 play at least recorder. How many play none of these instruments?
This is what I did:
$|A| = $ plays violin
$|B| = $ plays piano
$|C| = $ plays recorder.
From the information:
$|A\cap B\cap C| = 2 \\ |A\cup B| = 7 \\ |A\cup C|  =5 \\ |B \cup C| = 6 \\ |A| = 17 \\ |B| = 19 \\ |C| = 14.$
I want $|A^c \cap B^c \cap C^c|$.
By considering
$$|A^c \cup B^c \cup C^c| = |A^c| + |B^c| + |C^c| - |A^c\cap B^c| - |A^c \cap C^c| - |B^c \cap C^c| + |A^c \cap B^c \cap C^c|\\ = (40-17)+(40-19) + (40-14) - (40-7) - (40-5) + (40-6) + |A^c \cap B^c \cap C^c|\\ = -32 + |A^c \cap B^c \cap C^c| = 40 - |A \cap B \cap C| = 38 \\ \implies |A^c \cap B^c \cap C^c| = 70...?$$
Comment: 7 Play violin and piano should be "$|A \cap B| = 7$".  Also, $A \cup B$ is the set of those who play violin OR piano, including those who only play 1 instrument.
Comment: How is $A^c\cap B^c$ larger than $A^c?$ In general, $X\cap Y\subseteq Y$.
Comment: I'm not sure. It's also why I got a negative answer for a cardinality.
Answer: Your computations for the pairs is wrong. $|A^c\cap B^c|=40-|A\cup B|$, and you don't know $|A\cup B|$. You are computing it as $|A^c\cap B^c|=40-|A\cap B|$, which is false.
Instead, just computes $|A\cup B\cup C|$ with inclusion-exclusion, and then subtract from $40$.
Comment: What above indicates I think you interpreted the question incorrectly? I'm showing the error that you made, and suggesting an alternate approach.
Comment: Did I interpret the question incorrectly then?
Answer: As previously stated, take the information you know. Your events for more than 1 instrument should be intersections, not unions. That is $\cap$ not $\cup$

$|A\cap B\cap C| = 2 \\ |A\cap B| = 7 \\ |A\cap C|  =5 \\ |B \cap C| =
6 \\ |A| = 17 \\ |B|
 = 19 \\ |C| = 14.$

You want $|A^c \cap B^c \cap C^c|$ which is simply $40-|A \cup B \cup C|$
Then for $|A \cup B \cup C|$ we have $|A| + |B| + |C| - |A \cap B| - |A\cap C| - |B \cap C| + |A \cup B \cup C|$
$=17+19+14-7-5-6+2=34$
Don't forget final step of $40-34=6$


How can I install a curtain rod on a drywall?

Question: Originally I though this would be an easy process, however where I used to live all the houses are pure concrete, therefore something like this used to be relatively simple. My question is how can I attach a rod to a drywall?. I realize this questions might sound really ignorant, but please bear with me, I've never done anything with a drywall, I am currently living in the U.S., and my house like pretty much every other house here has drywalls.
It seems to me that if I just do it in the Drywall it will surely fall down, as it is not strong enough, my intuition tells me that behind the drywall there has to be some wood frame where presumably people attach the rods?. I do not have blue prints for my house, what would be a good way to know where I should install this rod?.
As a note the previous owner had curtain rods installed, but he removed them. So it is clear to me that this is possible, I just have no idea how.
This is a 2000 house that I just bought if that is relevant. Wood frame, brick veneer on the outside and drywall on the inside.
Any help, or perhaps good tutorials on how to do this, or what I need to buy would be really appreciated.
Comment: Is this question a repeat? Another post has the same question and is tagged "drywall", though it doesn't often refer to drywall: http://diy.stackexchange.com/questions/8868/how-do-i-hang-curtain-rods.
Answer: Typically most wood framed houses will have wood framing running from floor to ceiling on either side of the window.  If you mount an inch and half away from the edge of the window opening you will most likely hit wood.
But the best way is to head to the store and buy a stud finder.  It's a small hand held device that will find the wood/metal framing under the drywall.  It's a handy item to keep around the house when ever you need to hang something that needs more support.
Comment: just read the instructions that comes with it, with a little playing around it will be pretty easy to find things behind the wall.  Don't buy the absolute cheapest, but the step up from the cheapest is fine for the average home owner.  Any hardware store will have them.
Comment: +1 for the stud finder, was hoping something like this would exist!
Answer: Use drywall anchors which come in many shapes and sizes. Select the one suitable for the load being applied.
For heavier loads, such as bookshelves, use a stud finder and attach the shelves through the drywall to the wood stud.
Comment: Drywall anchors are great for hanging photos and other decorations, they are not recommended for curtains. Especially if you have children or cats.
Comment: The most you can support with a drywall anchor is 50 pounds.  But this is 50 pounds sheer, which means downward force flush with the dry wall.  Curtain rods support there weight 3-5 inches from the wall causing a lot of leverage against the drywall anchors.  Sheers or thin curtains might not weight much, but if you go with nice ones you can be looking at 30 pounds of fabric.  Plus the abuse they get from opening and closing, those drywall anchors will not hold for very long.  And you do have to take the kid/cat factor in as @Tester101 says.  If only takes a second for a kid to climb.
Comment: @benrudgers The size and strength of the anchor is not the weak point in the system, the drywall is. Drywall (gypsum board) is a finishing material, not a structural one. It's nothing more than plaster between two sheets of paper.
Comment: Much as 2 phase electrical service is suitable for many use cases - despite some needing three phase, hollow wall anchors come in many sizes. Some suitable for loads imposed by many window treatments in normal circumstances. If children are climbing the curtains, the priority solution is not stronger anchors.
Comment: @diceless There are drywall anchors that will fasten ADA grab bars and more conventionally styled anchors rated for several hundred pounds. See: http://www.wingits.com//pdfs/71183455WINGITS_Fasteners.pdf In the US, the big box home improvement stores often carry similar or identical products in stock.
Comment: @tester101 Gypsum board is frequently used as a structural component particularly as a shear diaphragm, both internally and as sheathing. The relevant aspect being that in these applications the fasteners transfer load to the *structural frame*. Like all materials, gypsum board has its limitations and capabilities and as is typical in construction there are standards to which it is manufactured and certifications such as UL. Rules of thumb are useful but of necessity lack insight.
Comment: @benrudgers Here is a real work test of dry wall anchors.  http://www.popularmechanics.com/home/reviews/4224987.  Note the line, "When they did fail at 63 pounds, the fasteners took massive chunks of drywall with them"


Map array values to the ruby hash key

Question: here i have the sample code , mapping array to hash and appending hash to array but expected output is missing the array value
data = {"a"=>5,"b"=>["e","f"]}
data1 = [44,55]
s = []
data1.each_with_index do |i,index|
    a = data1[index]
    data["b"] = i
    s << data
end
p s

output:
[{"a"=>5, "b"=>55}, {"a"=>5, "b"=>55}]

Expected output:
[{"a"=>5, "b"=>44}, {"a"=>5, "b"=>55}]

Comment: Why e and f what's the relation? You gave 44 but 45 is in the result? What kind of question is this?
Comment: thanks for correcting me its a 44
Comment: What is e and f?
Comment: that are just strings i want to replace with integers
Answer: Your main problem is that you are putting the same object reference into each of your array elements. Think of it as putting two keys to the same locker in two different places. If you change the stuff in the locker, both keys will open it, and they will both see the same stuff. So, when you change the value of 'b', you change it for the object in both array elements, because they're the same object.
The solution is to start your block by creating a copy of the data object, changing its 'b' value, and putting the result into the resulting array.
I've also changed your each_with_index to map, because map is best to use when you are transforming the values in the array. Also, you don't need to have the index available in your block; you're just running through the array elements without caring which element you're working with while you're working with it.
  data = {"a"=>5,"b"=>["e","f"]}
  data1 = [44,55]
  s = []
  data1.map do |num|
    the_copy = data.clone
    the_copy['b'] = num
    s << the_copy
  end
  p s

Map array values to the ruby hash key


Makefile can not find files in subfolders

Question: I am trying to write Makefile for my project in C.
I have my .c files in src subfolder,
.o files in build subfolder,
.h files in src/header subfolder
 and .c files for testing in tests subfolder.
In my Makefile I am using vpath:
 vpath %.c src:tests
 vpath %.h src/header
 vpath %.o build

When I want to compile file1 , Makefile do not have problem with finding file1.c in subfolder and compile object file into subfolder as build/file1.o. But when it compile file1 to executable file, Makefile can not find file1.o
This is my code in Makefile for specific file:
test_file1: test_file1.o file.o
    $(CC) $^ -o tests/$@

test_file1.o: test_file1.c file1.h
    $(CC) $(CFLAGS) -c $< -o build/$@

file1.o: file1.c file1.h file2.h file3.h
    $(CC) $(CFLAGS) -c $< -o build/$@

From test_file1.o I get:
gcc -std=c99 -Wall -Wextra -pedantic -g -c tests/test_file1.c -o
build/test_file1.o without problem.
From file1.o I get:
gcc -std=c99 -Wall -Wextra -pedantic -g -c src/file1.c -o build/file1.o also without problem.
But from test_file1 I get files without path to subfolders:
gcc test_file1.o file1.o -o tests/test_file1.
And get this error:
gcc: error: test_file1.o: No such file or directory
gcc: error: file1.o: No such file or directory
gcc: fatal error: no input files
Both files are in subfolder build.
Where is a problem?
Comment: Welcome to Stack Overflow. It looks as if you have a couple of typos in the code you posted. Please take some pains to avoid that; such errors are much easier for you to catch that for us.
Answer: The trouble is that some of your rules do not actually build what they claim to build, violating Mad Scientist's Second Law of Makefiles.
Make sees that it must build file1.o. That file does not exist at the outset, and vpath cannot find files that do not yet exist. So Make looks for a rule and finds this:
file1.o: file1.c file1.h file2.h file3.h
    $(CC) $(CFLAGS) -c $< -o build/$@

The target of this rule is file1.o. Make assumes that this will build file1.o, executes it, then tries to use file1.o in another recipe-- which fails because file1.o still does not exist.
That rule actually builds build/file1.o. No, Make is not smart enough to deduce this fact from the recipe.
Solution: change the rule.
build/file1.o: file1.c file1.h file2.h file3.h
    $(CC) $(CFLAGS) -c $< -o $@

Likewise:
build/test_file1.o: test_file1.c file1.h
    $(CC) $(CFLAGS) -c $< -o $@

Comment: Thanks for explaining me it. I wanted to have it clean and without path, but as I see it is not possible. Also thanks for great link.
Comment: @mato0: one of my guidelines for makefiles is that Make is good at using files *there* to build files *here,* but not vice-versa.


For displaying of audit logs, is it better to show date and time on separate lines?

Question: I have to design a page with a table for an audit log, and one of the columns is the Timestamp.
I am torn on how to handle this however, and I find examples of both on the web.
A) Without  line break
2020-12-20  01:59:20 GMT+8

or
B) With line break
2020-12-20
01:59:20 GMT+8

What would be the best practice in this case?
Answer: I'd definitely go for option A. It makes it much easier to see that certain events happened close together, as can be seen from this example:
2020-12-20  02:45:30 GMT+8
2020-12-20  01:59:30 GMT+8
2020-12-20  01:59:26 GMT+8
2020-12-20  01:59:24 GMT+8
2020-12-20  01:59:20 GMT+8
2020-12-20  00:45:30 GMT+8

2020-12-20
02:45:30 GMT+8
2020-12-20
01:59:30 GMT+8
2020-12-20
01:59:26 GMT+8
2020-12-20
01:59:24 GMT+8
2020-12-20
01:59:20 GMT+8
2020-12-20
00:45:30 GMT+8

If you lack the horizontal space for this, consider dropping the timezone indication (but show it in the table footer), use a shorter date time format (e.g. "Dec 20, 01:59") or do use option B, but show the date only when it changes, e.g.
2020-12-21
08:15:10 GMT+8
2020-12-20
02:45:30 GMT+8
01:59:30 GMT+8
01:59:26 GMT+8
01:59:24 GMT+8
01:59:20 GMT+8
00:45:30 GMT+8
2020-12-19
16:15:10 GMT+8

The ability to quickly compare them matters less when showing only a single log, e.g. on a detail page or as a tooltip.


Type 'String' has no call signatures

Question: I have no idea what the hell is wrong with this and why TS is complaining.  I must be missing something I don't know about TS:
App.js
<code>function fullName(firstName: string, lastName: string): string {
  return `${firstName} ${lastName}`;
}

function toUser(view: any, body: any, emailAddress: any) {
  const fullName: string = fullName(firstName, lastName);
  ...
}
</code>
Errors:
<code> Type 'String' has no call signatures.

    86  const fullName: string = fullName(firstName, lastName);

TS2448: Block-scoped variable 'fullName' used before its declaration.

    86  const fullName: string = fullName(firstName, lastName);

const fullName: string = fullName(firstName, lastName);
                  ~~~~~~~~
        'fullName' is declared here.

error TS2454: Variable 'fullName' is used before being assigned.

    86  const fullName: string = fullName(firstName, lastName);
</code>
Comment: I didn't downvote but have you read the error messages? _"Block-scoped variable 'fullName' used before its declaration."_, _"'fullName' is declared here."_, _"Variable 'fullName' is used before being assigned."_
Comment: What is your desired output?
Comment: the function fullName returns a string.  I'm just trying to get this damn code to compile without TS bitching here.  The errors make absolutely no sense to me.  The functions look fine to me.
Comment: The error message says `String`. In your code you are using `string`. That are two different types. Is this your actual code? Please provide a [mcve].
Comment: of course I read them and it just was not obvious.  I was thinking wtf my function is defined before I used it.  Those errors were not obvious to the fact that I was naming 3 things the same, as again I thought the scopes were diff.
Answer: The function and the variable have the same name. You are shadowing the function.
Comment: hmm I figured the const name was out of scope of the function so it would be ok..

Type 'String' has no call signatures


Minecraft PE Creation to share

Question: I created an epic village on PE and would love to share with anyone.  Is it possible to make it a seed or share file?  If so, how would I go about doing this?  Thanks!
Comment: Could you enlighten us as to what device you are playing on? The general theory is that you need to locate your world save folder, and zip the files, and then change for extension to .mcworld. But specifics differ according to device.
Answer: If you are using iOS, there is already a guide here.
If you are using Android, install ES File Explorer and go to the games folder in your sdcard. Inside there, go to com.mojang then saves. Find the folder with your world name and copy it to the other device using Bluetooth or something else.
Answer: To share a save file for minecraft PE on iOS (iPhone/iPod/iPad) you would have to jailbreak your device and install Cydia. Then in Cydia you can install an application called iFile which will allow you to import and export minecraft PE worlds.
Comment: If you want to add Android to your answer... the path to the saves on Android are, by default, accessible at `/sdcard/games/com.mojang/minecraftWorlds`. The world folders made by the game are normally weirdly named, but you can find what the world's name as shown in the world select screen by looking in each world folder's `levelname.txt` (it is a plain text file, but be careful when editing it as it may break you from loading the world, or cause Minecraft to crash).
Comment: Also, I forgot if you can still do it, but it might be possible (if it still works) without Jailbreaking the iOS device by connecting it to a computer with iTunes on it and making sure you have it in "storage" mode after the device syncs with your computer.
Answer: It is extremely hard to do that, especially as you would have to jailbreak your device. Maybe try building it again on a server/LAN world.

Minecraft PE Creation to share


How to pull different components into divs with v-for?

Question: I'm trying to get different components into tabs content here https://codepen.io/iTaurus85/pen/KbrBEa
When switching tabs I need to get the content from those components. BUt I just get a text.
How can I solve this problem? Or maybe I have chosen the wrong way to show different pages via tabs?

    <v-content>
    <v-layout row wrap class="tab-layout">
    <v-toolbar color="cyan" dark tabs>
      <v-toolbar-side-icon></v-toolbar-side-icon>

      <v-toolbar-title>Page title</v-toolbar-title>

      <v-spacer></v-spacer>

      <v-btn icon>
        <v-icon>search</v-icon>
      </v-btn>

      <v-btn icon>
        <v-icon>more_vert</v-icon>
      </v-btn>

      <v-tabs
        slot="extension"
        v-model="tab"
        color="cyan"
        align-with-title
      >
        <v-tabs-slider color="yellow"></v-tabs-slider>

        <v-tab v-for="item in levels" :key="item">
          {{ item.name }}
        </v-tab>
      </v-tabs>
    </v-toolbar>

    <v-tabs-items v-model="tab">
      <v-tab-item v-for="item in levels" :key="item">
        <v-card flat>
          {{ item.content }}
        </v-card>
      </v-tab-item>
    </v-tabs-items>
    </v-layout>
  </v-content>

new Vue({
  el: '#app',
  // components:{
  //     intro,
  //      Elementary,
  //   },
  data () {
    return {
       tab: null,
        levels: [
          {name:'Beginner', content: '<intro></intro>'},
          {name:'Elementary', content: '<elementary></elementary>'},
          {name:'Pre-Intermediate', content: 'Pre-Intermediate'},
          {name:'Intermediate', content: 'Intermediate'},
          {name:'Upper-Intermediate', content: 'Upper-Intermediate'}
        ]
    }
  }
})

Answer: You can use v-html directive: https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML - codepen: https://codepen.io/anon/pen/EGOOym.
But a better approach would be create separate components for each tab.
Answer: You can use is (Vue :is) for your v-for + components for each tab:

<component :is="item.componentName"></component>

Your item can be something like:
{componentName: 'Intermidiate', tasks: 100}

And in a Vue instance you should also add component like:
new Vuew({
   components: {
       Inetrmidiate,
   }
})

And the last point - just create new Vue-component named Intermidiate.
Answer: The answer is here https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components.
This example https://jsfiddle.net/chrisvfritz/o3nycadu/ showed exactly what I wanted.

  <button
    v-for="tab in tabs"
    v-bind:key="tab"
    v-bind:class="['tab-button', { active: currentTab === tab }]"
    v-on:click="currentTab = tab"
  >{{ tab }}</button>

  <component
    v-bind:is="currentTabComponent"
    class="tab"
  ></component>

Vue.component('tab-home', {
    template: '
Home component
'
})
Vue.component('tab-posts', {
    template: '
Posts component
'
})
Vue.component('tab-archive', {
    template: '
Archive component
'
})

new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Home',
    tabs: ['Home', 'Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})

.tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #ccc;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}
.tab-button:hover {
  background: #e0e0e0;
}
.tab-button.active {
  background: #e0e0e0;
}
.tab {
  border: 1px solid #ccc;
  padding: 10px;
}