text:
Q: how to solve the conv2d error? I am a beginner in python and tensorflow.
I have a error in dimention problem.
Is there anyone to solve this problem?
my code is as below and the error came from 'aux = Convolution2D'line.
The error message is "ValueError: Negative dimension size caused by subtracting 512 from 10 for 'conv2d_15/convolution' (op: 'Conv2D') with input shapes: [?,10,10,512], [10,512,512,1].
this is tensorflow backend.
def _conv_bn_relu(nb_filter, nb_row, nb_col, subsample=(1, 1)):
        def f(input):
            conv = Convolution2D(nb_filter=nb_filter, nb_row=nb_row, nb_col=nb_col,
                                 subsample=subsample, init="he_normal",
                                 border_mode="same")(input)
            norm = BatchNormalization()(conv)
            return ELU()(norm)
        return f

def get_unet():
    inputs = Input((img_rows, img_cols, 1), name='main_input')
    conv1 = _conv_bn_relu(32, 7, 7)(inputs)
    conv1 = _conv_bn_relu(32, 3, 3)(conv1)
    pool1 = _conv_bn_relu(32, 2, 2, subsample=(2, 2))(conv1)
    drop1 = Dropout(0.5)(pool1)

    conv2 = _conv_bn_relu(64, 3, 3)(drop1)
    conv2 = _conv_bn_relu(64, 3, 3)(conv2)
    pool2 = _conv_bn_relu(64, 2, 2, subsample=(2, 2))(conv2)
    drop2 = Dropout(0.5)(pool2)

    conv3 = _conv_bn_relu(128, 3, 3)(drop2)
    conv3 = _conv_bn_relu(128, 3, 3)(conv3)
    pool3 = _conv_bn_relu(128, 2, 2, subsample=(2, 2))(conv3)
    drop3 = Dropout(0.5)(pool3)

    conv4 = _conv_bn_relu(256, 3, 3)(drop3)
    conv4 = _conv_bn_relu(256, 3, 3)(conv4)
    pool4 = _conv_bn_relu(256, 2, 2, subsample=(2, 2))(conv4)
    drop4 = Dropout(0.5)(pool4)

    conv5 = _conv_bn_relu(512, 3, 3)(drop4)
    conv5 = _conv_bn_relu(512, 3, 3)(conv5)
    drop5 = Dropout(0.5)(conv5)
    print(drop5.shape)

    # Using conv to mimic fully connected layer.
    aux = Convolution2D(nb_filter=1, nb_row=drop5._keras_shape[2], nb_col=drop5._keras_shape[3],
                        subsample=(1, 1), init="he_normal", activation='sigmoid')(drop5)
    aux = Flatten(name='aux_output')(aux)

    # up6 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(drop5), conv4], axis=3)
    up6 = merge([UpSampling2D()(drop5), conv4], mode='concat', concat_axis=1)
    conv6 = _conv_bn_relu(256, 3, 3)(up6)
    conv6 = _conv_bn_relu(256, 3, 3)(conv6)
    drop6 = Dropout(0.5)(conv6)

    # up7 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(drop6), conv3], axis=3)
    up7 = merge([UpSampling2D()(drop6), conv3], mode='concat', concat_axis=1)
    conv7 = _conv_bn_relu(128, 3, 3)(up7)
    conv7 = _conv_bn_relu(128, 3, 3)(conv7)
    drop7 = Dropout(0.5)(conv7)

    # up8 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(drop7), conv2], axis=3)
    up8 = merge([UpSampling2D()(drop7), conv2], mode='concat', concat_axis=1)
    conv8 = _conv_bn_relu(64, 3, 3)(up8)
    conv8 = _conv_bn_relu(64, 3, 3)(conv8)
    drop8 = Dropout(0.5)(conv8)

    # up9 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(drop8), conv1], axis=3)
    up9 = merge([UpSampling2D()(drop8), conv1], mode='concat', concat_axis=1)
    conv9 = _conv_bn_relu(32, 3, 3)(up9)
    conv9 = _conv_bn_relu(32, 3, 3)(conv9)
    drop9 = Dropout(0.5)(conv9)

    conv10 = Convolution2D(1, 1, 1, activation='sigmoid', init="he_normal", name='main_output')(drop9)

    # model = Model(inputs=[inputs], outputs=[conv10])
    model = Model(inputs=[inputs], outputs=[conv10, aux])

    # model.compile(optimizer=Adam(lr=1e-5), loss={'main_output': dice_loss},
    #               metrics={'main_output': dice},
    #               loss_weights={'main_output': 1})
    model.compile(optimizer=Adam(lr=1e-5), loss={'main_output': dice_loss, 'aux_output': 'binary_crossentropy'},
                  metrics={'main_output': dice, 'aux_output': 'acc'},
                  loss_weights={'main_output': 1, 'aux_output': 0.5})

    return model

A: I think you should change this line:
aux = Convolution2D(nb_filter=1, nb_row=drop5._keras_shape[2], nb_col=drop5._keras_shape[3],
                    subsample=(1, 1), init="he_normal", activation='sigmoid')(drop5)

to:
aux = Convolution2D(nb_filter=1, nb_row=drop5._keras_shape[1], nb_col=drop5._keras_shape[2],
                    subsample=(1, 1), init="he_normal", activation='sigmoid')(drop5)

A: I don't use Keras, but I believe the problem in your code lies within the filter size you put into
aux = Convolution2D(nb_filter=1, nb_row=drop5._keras_shape[2], nb_col=drop5._keras_shape[3], subsample=(1, 1), init="he_normal", activation='sigmoid')(drop5)
It is quite hard to deduce the dimensions of your tensors, but after having read through Keras documentation of Convolution2D, as well as having analysed the dimensions of your tensors, I assume drop5 outputs a tensor of shape (samples, new_rows, new_cols, nb_filter) ([?,10,10,512] in your error message). In other words, yourdrop5 outputs an image with dimensions 10 x 10 x 512, or equivalently speaking 512 10 x 10 images (this is a great read if you want to learn more about CNNs).
When you now set nb_row=drop5._keras_shape[2] and nb_col=drop5._keras_shape[3], you set the dimensions of the filter to nb_row=10 and nb_col=512. This means that you will try to perform convolution on 512 10 x 10 images with a 10 x 512 shaped filter. In order to see if a filter fits an image, I would assume TensorFlow subtracts the image and filter dimensions. [10, 10] - [10, 512] = [0, -502] shows that the filter is much larger than the image, and thus convolution cannot be performed, and thus your error message.
A solution to this problem is to change your nb_row and nb_col dimensions. If you want a bigger filter size than 10 x 10, you could resize the output image from drop5.


text:
Q: Installing TrueCrypt on dual boot Mac/Win7 laptop A friend (not much of a technician) owns a Mac laptop with dual boot Win7/Mac.
Now he wants to encrypt the entire drive (both systems) using TrueCrypt.
I read a lot and found a lot of outdated guides and comments. Some stating it wouldn't be possible to encrypt an entire harddrive of a multi-boot system (but the window partition only).
Will the encryption wizard do the job? Are there any problems that will arise? Is there something he needs to know before starting?

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want my object to continue moving but it won't work So I want it to keep moving with the assigned speed, but it just moves once and it stops.
I thought the after function would help but it doesnt..
Also I want to know what the number does inside the after brackets
    import tkinter as tk

    root = tk.Tk()
    canvas = tk.Canvas(root, width=1000, height=1000, background='black')
    canvas.pack()

    circle = canvas.create_oval(0, 0, 10, 10, fill='white')

    def move():
        canvas.move(circle, 100, 100)

    move()
    canvas.after(40, move())

    root.mainloop()

A: You have to pass only function name in after() as below...
canvas.after(40, move)

Instead of...
canvas.after(40, move())

Mean after 40 milliseconds after() function will be call and then your object will be move.

A: You need to call after(...) inside move():
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=1000, height=1000, background='black')
canvas.pack()

circle = canvas.create_oval(0, 0, 10, 10, fill='white')

def move():
    canvas.move(circle, 10, 10)
    canvas.after(50, move)

move()

root.mainloop()

Refer here on how to use after() function.


text:
Q: Is there any alternative for  in asp.net? I was trying to display lblName1 and lblName2 only if they have text. Even when i dont have any value for lblName2, the break still has an impact. Can someone please advice me if there is any other way to display  or conditionally display
<asp:Label ID="lblName1" runat="server" Visible= "false" ></asp:Label>

<asp:Label ID="lblName2" runat="server" Visible= "false">  </asp:Label>

Thanks in advance..

A: Give the label a CSS class name and set the margin for that class:
<asp:Label ID="lblName1" CssClass="Testing123" runat="server" Visible= "false" ></asp:Label>

.Testing123{ margin-bottom: 20px; }

If the Label is not rendered then no gap will be created.

A: You might consider adding a litteral to handle the br and this way play with its visibilty :
<asp:Literal runat=server Id=C_lit_Br>
</asp:Literal>

with in your codebehind :
if (!lblName2.Visible)
    C_lit_Br.Visible=false;

It is a quick patch, but it should work.

A: It is better to use literal in that case:
In literal text you also write html in it

A: wrap the labels in p tags:

<label1>

<label2>

A: Going with what you have and ignoring using any code behind changes, you can use some css to provide a break without using a
 tag.
By this, I mean if you were to give your  controls a css class, class="labelStyle
.labelStyle{
     float: left;
     clear: left;
 }

Your html produced would look like
Some TextMore Text

If there is no value in the Labels, then your html would contain two empty span tags.
This will move the 2nd label onto the next line. However this may not fit in with the rest of your html, and because you are floating elements, then your overall layout might break.
An example is here http://jsfiddle.net/2v93f/


text:
Q: Save coordinates as polygon type in Mysql I have the coordinates of polygon in JSON object and I want to save them as polygon type in database. This is my code-
$Coordinates   = $conn->real_escape_string($_POST['Coordinates']);

"INSERT into table_name (polygon) VALUES(PolyFromText('POLYGON('" .($Coordinates). "')'))";

where $coordinates are the stringified Lat and Long of the polygon vertices.
For ex.- Coordinates=
"[[36.37485644939407,-96.68243408203125],[35.94465937365276,-96.998291015625],[36.117908916563685,-96.10015869140625]]"
and these are generating from this code-
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
var coordinates_poly = polygon.overlay.getPath().getArray();

    var lat_poly = [];
    var lng_poly = [];
    var Coordinates = [];
    for(var i = 0; i <coordinates_poly.length; i++){
    lat_poly = coordinates_poly[i].lat();
    lng_poly = coordinates_poly[i].lng();
    Data = [lat_poly,lng_poly];
    Coordinates.push(Data);
    }
    var JSON_Coordinates = JSON.stringify(Coordinates);
    document.getElementById("coordinates").value= '"'+JSON_Coordinates+'"';

but the error is-
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\"[[36.37485644939407,-96.68243408203125],[35.94465937365276,-96.998291015625],[' at line 1
Please someone help me how to resolve this issue.
Thanks.

A: Use correct syntax. For example:
POLYGON((50.866753 5.686455, 50.859819 5.708942, 50.851475 5.722675, 50.841611 5.720615, 50.834023 5.708427, 50.840744 5.689373, 50.858735 5.673923, 50.866753 5.686455))

See here https://dev.mysql.com/doc/refman/5.7/en/gis-polygon-property-functions.html


text:
Q: Programmatic access to application context and context locations I have some tests (I didn't write them, I am maintaining them) that use the spring ContextConfiguration annotation to supply application contexts:
@ContextConfiguration(locations = { "testCustomContext.xml" })
public class MyTest  {
}

Anyway, a couple of questions.  I am not so familiar with spring custom context locations that don't specify file:/ or classpath:/.  What does it mean?  There are a lot of resources on this test class path with that name.  Are they all loaded?  If not, how does Spring know which to load?
Second, is there a way to programmatically access a spring context that has been wired in this way?
I.e. is there a static Spring Class or ThreadLocal variable that would give me access to the current context?
Thanks in advance for the help.

A: You can gain access to application context by just autowiring it inside test class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

    @Autowired
    private ApplicationContext applicationContext;

    // class body...
}

As for your second question:

I am not so familiar with spring custom context locations that don't
  specify file:/ or classpath:/. What does it mean? There are a lot of
  resources on this test class path with that name. Are they all loaded?
  If not, how does Spring know which to load?

From Java Docs:

A plain path — for example, "context.xml" — will be treated as a
  classpath resource that is relative to the package in which the
  specified class is defined.  A path  starting with a slash is treated
  as an absolute classpath location,  for example:
  "/org/springframework/whatever/foo.xml".  A path which references a
  URL (e.g., a path prefixed with classpath:,  file:, http:, etc.) will
  be added to the results unchanged.

You can learn about Spring Resources in docs: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/resources.html
Also JavaDocs for @ContextConfiguration can give you more knowledge.
I encourage you to study Spring Docs.


text:
Q: Ramdom com.rabbitmq.client.ShutdownSignalException: connection error we have an application where we use Spring-AMQP to connect to a remote server through AMQP. Lately, and randomly, we are receiving connection errors. These errors occur once or twice a day at different times, and it is beginning to be a major problem.
The trace that remains in the log is the following:
com.rabbitmq.client.ShutdownSignalException: connection error
    at com.rabbitmq.client.impl.AMQConnection.startShutdown(AMQConnection.java:868)
    at com.rabbitmq.client.impl.AMQConnection.shutdown(AMQConnection.java:858)
    at com.rabbitmq.client.impl.AMQConnection.handleFailure(AMQConnection.java:681)
    at com.rabbitmq.client.impl.AMQConnection.access$400(AMQConnection.java:47)
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:582)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:210)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
    at sun.security.ssl.InputRecord.read(InputRecord.java:503)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:940)
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
    at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:288)
    at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:91)
    at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:164)
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:578)
    ... 1 more

I need to get more information about these errors to try to see where the problem is. What do you think that I can look / do?

A:
Connection reset

Means the client received a RST TCP packet - the socket was closed. First place to look is in the server log. But it might be some other component in the network (firewall, router etc).


text:
Q: Drag and drop list with hierarchy/nested behavior I only want to do this with vanilla javascript. But if there is some lightweight library I might reconsider. Anyway, I basically want to emulate a file system with a list of elements.

 First

 First

As you can see in my HTML structure. Each container can be dragged and placed inside another .children-nodes, however the items themselves can also be dragged and moved around in the hierarchy. There are multiple of these containers with items nested inside eachother. I have written several algorithms to try to make this work I just can't seem to make it happen. I get errors like "new child contains parent" and etc.
Here's the latest logic i tried:
const draggables = document.querySelectorAll('.draggable');

draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', () => {
        draggable.classList.add('is-dragging');
    })

    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('is-dragging');
    })

    draggable.addEventListener('dragover', (event) => {
        event.stopPropagation()
        event.preventDefault();

        if(!draggable.classList.contains('.is-dragging')){
            const item = document.querySelector('.is-dragging');
            const containerOfItem = document.querySelector('.container:has(.is-dragging)');
            const childrenContainer = containerOfItem.querySelector('.children-nodes');
            const children = childrenContainer.querySelectorAll('div');
            if(children.length == 0) {
                const childrenDropContainer = draggable.parentNode.querySelector('.children-nodes');
                childrenDropContainer.appendChild(containerOfItem);
            } else {

            }
        }
    })
})

And like I said. I've written it multiple different ways. I changed the markup too and searched around for some information. The kind of help that I would want would be what to consider, in which direction should I move, how do I solve this problem. Any help is gladly received.


text:
Q: Sending an object through the internet and invoking it's method I've got a java web server and I made it so that the server will respond to a certain a http* request by sending back a java object that contains a "execute" method.
I'd like to be able to execute a remote object's method.

*

*I can't use reflection because I don't send the class, thinking about making a local class that has the same method + package-name so i can try to object.getClass()

*I won't like to put the entire block of code in the toString() from the object that I will send. (Override)

*I can't cast to an interface.
I'm also thinking about making a .jar library that has the definition for the class file that will be created on the server and accessed on the client, how can this work?
I couldn't find another question regarding this, so I will leave this here.
EDIT:

*

*I'm using URLConnection to communicate with a servlet, the servlet makes an instance of the object on the server then it will send it to the client using ObjectOutputStream, as well as ObjectInputStream on the client for it to get it.

*Looking for some alternatives to RMI, if none, I will lookup some RMI tutorials.

*Regarding about my choice to not use RMI in the first place: maybe I don't want every time to make a connection between client-server , maybe I want to deserialize objects and check/invoke it's methods.

A: If you are going to "send" serialized objects from one java virtual machine (java process) to another, you need to have the .class files already present at both ends. If you decide to continue with your current approach, you would need the following:

*

*Your client must be Java, or be able to run Java, and have the .class files that correspond to the objects that it is receiving locally available, or must download them from the server before accessing them.

*You must somehow wrap serialized object streams within HTTP. HTTP is a protocol for requesting and sending web pages. It is incompatible with Java's serialization protocol (it contains extra headers, for example), and you would need to wrap Java serialization inside HTTP payloads for things to work as you seem to expect.

*When you send serialized objects, you are actually sending "object graphs" (the object and all objects accessible by navigating its fields). This can end up being inefficient. Serialization may not be the best answer for you for this reason.
It is far easier to use other mechanisms:

*

*If you avoid HTTP, you avoid the need for extra wrappers. Writing a simple server that, when connected to, receives and sends serialized objects is much easier and efficient than writing a wrapper for HTTP within a traditional Java webapp (Java app servers tend to be resource-hungry).

*Consider using Kryo or other Java serialization/networking libraries - they come with built-in servers, and allow very fine-grained control over what is being sent.

*Java has in-built support for RMI ("Remote Method Invocation"). This seems to be what you are actually trying to achieve. You no longer need to be aware that objects are local or remote - they appear to work the same, and all required networking and serialization is done behind the scenes. Read all about it.


text:
Q: How to share imports between components in react How to avoid retyping different imports all around different components.
Like if App has
 import A from a
And Component needs this import, but I dont want to rewrite the it any every component.


text:
Q: Syncing data between MySQL and Node.js In my project, I am storing a lot of data in MySQL automatically. I want, however, the same things to sync with Node.js application's own data storage. What would be the fastest and easiest way to do this when storing data in both storages simultaneously isn't possible?
So, for example, I am storing variable "balance" in MySQL inside one Node.js application. I would want this same balance updated into other Node.js application's own storage but my current Node.js app is not connected to socket or other kind of data transporting mechanism. So how could I fetch data from MySQL in that other Node.js application?

A: sound look like your project structure is saga pattern.
in your question about update data is can use Kafka to create a topic and 2 node application consume message on same topic to update data into own database.


text:
Q: PHP cURL download progress using jquery I can't figure out how to push the progress out every time it updates using php. For the sake of clarity, I will write an example.
jQuery:
function uploadMovieDownload(link){
    $.post("php/downloadmovie.php", { source:link }, function(json){ console.log(json); });
}

uploadMovieDownload(url);

PHP (php/downloadmovie.php):
session_start();
ob_start();
date_default_timezone_set("Europe/Bucharest");
ini_set('display_errors',true);

require_once(dirname(__FILE__)."/functions.php");

$url = $_POST['source'];
$headers = getHeaders($url);
$url = $headers['url'];
$path = dirname(__FILE__)."/temp/test.mp4";

$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch, CURLOPT_PROGRESSFUNCTION, 'progress' );
curl_setopt( $ch, CURLOPT_NOPROGRESS, false );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 100 );
curl_setopt( $ch, CURLOPT_FILE, $fp );
curl_exec( $ch );
curl_close( $ch );
fclose( $fp );

function progress($resource,$download_size, $downloaded, $upload_size, $uploaded){
    if($download_size > 0) echo $downloaded / $download_size  * 100;
    ob_flush();
    flush();
}

echo "Done";
ob_flush();
flush();

The problem I have is that it returns the progress after it completes, it isn't pushing it while downloading. Thanks in advance if you have any sugestions.

A: with that method, you'll run in to all kind of caching problems, is php output buffering? you'll have a problem. are you behind a web server, ala nginx/apache/lighthttp/anything? you'll have a problem. is the browser cacheing output? (all mainstream browsers do), you'll have a problem.
i suggest an alternative which will have none of those problems: using $_SESSION to store download percentage, and querying the percentage with XMLHttpRequests (actually querying the percentage over WebSockets would be optimal, lagless, use less bw, etc,  but much harder to implement)
downloadmovie.php
<?php
require_once(dirname(__FILE__)."/functions.php");

$url = $_POST['source'];
$headers = getHeaders($url);
$url = $headers['url'];
//after validation of input
session_start();
$_SESSION['download_percentage']=0.0;//initialize it
session_write_close();
fastcgi_finish_request();//or if you're not using fcgi, some equivalent..

$path = dirname(__FILE__)."/temp/test.mp4";

$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch, CURLOPT_PROGRESSFUNCTION, 'progress' );
curl_setopt( $ch, CURLOPT_NOPROGRESS, false );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 100 );
curl_setopt( $ch, CURLOPT_FILE, $fp );
curl_exec( $ch );
curl_close( $ch );
fclose( $fp );

function progress($resource,$download_size, $downloaded, $upload_size, $uploaded){
    $percentage=$download_size==0? 0.0 : (($downloaded/$download_size)*100);
    session_start();
    $_SESSION['download_percentage']=$percentage;
    session_write_close();
}

getProgress.xhr.php
<?php
if(""===session_id()){
session_start();
}
echo $_SESSION['download_percentage']??'?';

then monitoring the progress in the browser:
(function checkProgress() {
    "use strict";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "getProgress.xhr.php");
    xhr.addEventListener("readystatechange", function(ev) {
        var xhr = ev.target;
        if (xhr.readyState !== 4) {
            return;
        }
        console.log(xhr.responseText + " percent downloaded!");
        if (xhr.responseText === "100") {
            return; /*stop checking for progress when its finished*/
        }
        setTimeout(checkProgress, 1000); //<<check for progress every 1 second

    });
    xhr.send();
})();

important edit: as @drew010 pointed out, it won't work without session_write_close();session_start(); each time curl updates the value, fixed that.

A: Quote from cURL download progress in PHP
echo "<pre>";
echo "Loading ...";

ob_flush();
flush();

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
//curl_setopt($ch, CURLOPT_BUFFERSIZE,128);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false); // needed to make progress function work
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);

function progress($resource,$download_size, $downloaded, $upload_size, $uploaded)
{
    if($download_size > 0)
         echo $downloaded / $download_size  * 100;
    ob_flush();
    flush();
    sleep(1); // just to see effect
}

echo "Done";
ob_flush();
flush();

?>

A: Don't use ob_flush(), just flush().
(Remove all the ob_ functions).
Also, consider modifying the buffersize:
curl_setopt($ch, CURLOPT_BUFFERSIZE, 16000);

Experiment with the size.

A: PHP will show the results when all the scripts are done. This is the reason that you just the finish progress.
You can execute the curl downloading in the background, and write the progress to session, database, session or memory such as redis, memchche. Then in the client side read the process every very short time.
You also can use Iframe to do this.


text:
Q: Issue on Using One Switch Botton to Toggle Functions in jQuery I am using two buttons to slide up and down the page at this sample  as:

<button type="button" class="btn btn-default green goinfo">Go Info</button>

 <button type="button" class="btn btn-default green gomap">Go Map</button>

can you please let me know how I can reduce the buttons to do do the same job? something like :
 <button type="button" class="btn btn-default slider">Switch View</button>

jQuery
jQuery('body').css('overflow','hidden');
     var viewheight = $('#map').height();

 $('.goinfo').fadeIn();
    $(window).scroll(function () {
        if ($(this).scrollTop() < 100) {
            $('.goinfo').fadeIn();
        } else {
            $('.goinfo').fadeOut();
        }
    });

     $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('.gomap').fadeIn();
        } else {
            $('.gomap').fadeOut();
        }
    });

    $('.gomap').click(function () {
        $("html, body").animate({
            scrollTop: 0
        }, 600);
        return false;
    });

     $('.goinfo').click(function () {

        $("html, body").animate({
            scrollTop: viewheight
        }, 600);
        return false;
    });

    $( window ).resize(function() {
    var mapheight = $('#mapview').height();

});

A: *

*Put the button outside both divs, below them.

*Using CSS, style the button so it appears where you want (probably roughly position: absolute; bottom: 10px; right; 10px; but it is hard to say without knowing more about your page.

*Put a local variable into your ready handler: var down = false;

*In the button handler, do this:

Code:
if (down) {
   down = false;
   $('html, body').animate(...);
}
else {
   down = true;
   $('html, body').animate(...);
}

But honestly, I think what you have now is less complicated and not problematically wordy, so I wouldn't change it myself.


text:
Q: Finding $\phi(k)$ If you have $\Psi(x,0) = c(\psi_1 + \psi_2)$ where $\psi_n$ is an Energy eigenfunction for a quantum number $n$.  I'm supposed to find $\phi(k,t)$ at $t$ = 0.  This is for an infinite square well from 0 to a.
I'm not exactly sure how to do this.  I assume since $V(x)=0$ from $0<x<a$ then $\phi(k,t)$ will not evolve in time, thus $\phi(k,t) = \phi(k)$.
$$\phi(k,0) = \frac{1}{\sqrt{2\pi}}\int_{0}^{a} \Psi(x,0) e^{-ikx} dx.$$
While, I believe that I'm on the right track the $\phi(k)$ I get is not correct in the sense that when I find $|\phi|^2$ it is still complex, which can't be right.  Can someone guide me in the correct direction?

A: Firstly, the Shroedinger's equation is:
$$H\Psi(x,t)=i\hbar\frac{\partial}{\partial t}\Psi(x,t)$$
so, every wave funtion does evolve in time.
In the case of infinite square well (and also for cases where the potential V is independent of t), we can use separation of variable for the above Shroedinger's equation. Then:
$$\Psi(x,t)=e^{\frac{-iEt}{\hbar}}\Psi(x,0)$$
Now, the wave equation in momentum space is just a Fourier transform of $\Psi(x,t)$ with integral in $x$ variable as you presented.
Moreover, $|\phi|^2$ is always a positive real number for all complex $\phi$. So, if you find $|\phi|^2$ is complex after calculating, please re-check.


text:
Q: Backbone.js - Is my model is correct - in case of multiple level datas I am getting json data from server for make the navigation menu (has the sublinks ) - for that, i am making my model as follow. is this correct..? any one help me please?
Here is the json i am getting from server:
[
    {
        "label": "General",
        "link": "#/general",
        "subLinks": [
            {
                "label": "Dashboard",
                "link": "#/dashboard"
            },
            {
                "label": "My Task",
                "link": "#/mytask"
            },
            {
                "label": "My Documents",
                "link": "#/mydocuments"
            },
            {
                "label": "My Templates",
                "link": "#/mytemplates"
            },
            {
                "label": "Search",
                "link": "#/search"
            }
        ]
    },
    {
        "label": "Repositories",
        "link": "#/reposotories",
        "subLinks": []
    },
    {
        "label": "SavedSearches",
        "link": "#/savedSearches",
        "subLinks": []
    },
    {
        "label": "Favourites",
        "link": "#/favourites",
        "subLinks": []
    },
    {
        "label": "Reports",
        "link": "#/reports",
        "subLinks": []
    },
    {
        "label": "Preferences",
        "link": "#/preferences",
        "subLinks": []
    }
]

after i receive my json i use the parse method to manipulate the models:
 define(["backbone","models/model","collection/baseCollection"], function (Backbone,model,baseCollection) {

    var mainLinkModel = model.extend({
        defaults:{
            label:"mainLink",
            link:"#",
            subLinks:[
                          label:"mainLink",
                  link:"#"
                   ]
        }
    })

    var headerCollection = baseCollection.extend({
        url:function(){
            return this.path + "edms/navigationLinksTest"
        },
        model:model,
        initialize:function(){

        },
        parse:function(response){

            var mainNavi = [];

            _.each(response.navList, function(m){
                            // i am making new models.. but how to handle the sublinks?
                mainNavi.push(new mainLinkModel(m));
            })

        }
    });

    return new headerCollection;

})

how to handle this kind of models.. any one help me in this please..?


text:
Q: Issue With Redirecting & Query Strings On our CMS, we use the following piece .htaccess code to serve pages from our CMS:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ index.php?slug=$1

So the page is served by passing through the slug of the page to index.php
The problem we are having is if you go to this page for example:
http://www.example.com/index.php?slug=contact
You get redirected to this page:
http://www.example.com/?slug=contact
We also have this in our .htaccess to send index.php back to the root:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index.php
RewriteRule ^index.php$ http://www.example.com/ [R=301,L]

What can we do to end up with this URL:
http://www.example.com/contact

Any help is greatly appreciated.

A: You can use this code in root .htaccess:
RewriteEngine On
RewriteBase /

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(?:index\.php)?\?slug=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L]

RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*?)index\.php$ /$1 [L,R=302,NC,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/([^/]+)/?$ index.php?slug=$1 [L,QSA]


text:
Q: tablesorter formatting issues between numbers with commas and numbers without them I have a price field and a total amount field:
Price field has a value of 0.9999900 or 0.9000000 Total amount can be 10,000.00 or 1,000,000.00. I am using tablesorter library to sort the table.
Issue is If I set s like below (total amount sorting works fine)
s=s.replace(new RegExp(/[^0-9\/A-Za-z ]/g),"");

If I set s like below (price sorting works fine)
s=s.replace(new RegExp(/[^0-9\/A-Za-z. ]/g),"");

But I cant get both to work at the same time.. What am I missing:
ts.addParser({
    id: "digit",
    is: function(s,table) {
        var c = table.config;
        s=s.replace(new RegExp(/[^0-9\/A-Za-z ]/g),"");
        return $.tablesorter.isDigit(s,c);
    },
    format: function(s) {
        return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9\/A-Za-z ]/g),""));
    },
    type: "numeric"
});

A: I found a work around the different columns:
1) I made both columns points to different functions in tablesorter, that way I could have both price and total amount work their own way.
Under tablesorter I modified the header to have digits for total amount column and thousands for "total amount" column.
headers: {8: { sorter: 'digit' },13: { sorter: 'thousands' }}

Where 8, 13 are my column numbers on my table.
2)For "Total amount" columns number 8, i used id:digits
3)For "Price" column number 13, I used a custom parser id:"thousands"
Tablesorter code for both included below
id: "digit"-->Existing code in the Tablesorter library
ts.addParser({
    id: "digit",
    is: function(s,table) {
        var c = table.config;
        s=s.replace(new RegExp(/[^0-9\/A-Za-z ]/g),"");
        return $.tablesorter.isDigit(s,c);
    },
    format: function(s) {
        return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9\/A-Za-z ]/g),""));
    },
    type: "numeric"
});

id: 'thousands'-->Custom table sorter added to the tablesorter lib.
ts.addParser({
    id: 'thousands',
    is: function(s) {
        return false;
    },
    format: function(s) {
        return s.replace(new RegExp(/[^0-9\/A-Za-z. ]/g),"");
    },
    type: 'numeric'
});

$(function() {
    $("table").tablesorter({
        headers: {
            6: {//zero-based column index
                sorter:'thousands'
            }
        }
    });
});


text:
Q: How to get Cuda to use gcc 4.6 I am trying to install Cuda on my machine and as usual it causes problem with gcc 4.7 when trying to run the installer.
I have now installed gcc 4-6 which should work and I am now thinking about the best way to install CUDA.
I have thought about creating a symlink to gcc-4.6 so that the installer uses version 4.6 instead of 4.7.
Do you have any suggestions to do that or is there a better solution? It feels a bit stupid erase 4.7 from the machine in order to use cuda.
Thanks in advance!
/ Erik

A: Another solution to your problem is to download CUDA 5.5, which works with gcc 4.7. It is currently only available to CUDA registered developers: link to forum announcement

A: Create alternatives so that you can switch between versions at any time check out this helpful page:
How to change the default GCC compiler in Ubuntu?


text:
Q: scp connection to remote host times out? So, I am trying to retrieve a file from a remote host and copy it to my local ubuntu instance. I can ssh into the remote host from my ubuntu instance just fine, but when I try to connect with scp to transfer the file I get the error "connection timed out".
I am using the following command:
sudo scp angela@192.168.194.57:/bm/data/'2021-02-03 21.22.23 - northvancouver.pdf' /home/angela
I think it might have to do with the firewall/security settings on the server. The server requires an ssh key to connect, which I have set up on my ubuntu instance, but if I try to connect in the same way as I do with ssh (like trying angela@buildmapperserver-arbutus which is the server name I ssh into) it does not recognize the address (which I assume is because you need to exclusively use an ip address with scp?)
I don't know what the issue is or how to fix it. We have a github repository synced to the server and I would just push the files to the repo as a shortcut, but some of the files are too large for that.
Any ideas? If you need more information, just ask.

A: Are you able to successfully connect to the remote server using the command below?
ssh angela@192.168.194.57

If the ssh works, then check the firewall settings. It may be blocking the file transfer protocol.

A: Using sftp instead of scp works so I am doing that.

A: You can try to specify the path to the key
scp -i path/to/private/key user@ip:source/path target/path


text:
Q: COPIANDO UM REPOSITORIO PARA OUTRO Boa Tarde,
Pessoal estou trabalhando em uma empresa onde estamos num processo de mudança, tinhamos um repositorio GIT no ar interno aqui na empresa que toda noite atualiza a MASTER com o repositorio master que fica no cliente, porem devido as novas orientações devemos não utilizar mais esse repositorio da empresa e sim diretamente o repositorio do cliente.
Minha duvida, tenho um monte de branch no repositorio da minha empresa, e alguns deles não subiu ainda para a master do cliente.
Gostaria de de alguma forma copiar todos os branchs que tenho norepositorio da minha empresa para o repositorio do cliente, afim de manter todos os historicos de branchs.
imagina que tenho dois links
http://minhaempresa/git/master
http://cliente/git/master
a ideia é copias todos os branches do link minha empresa para o link cliente, sem copiar a master e develop

A: O GIT é um repositório distribuído, sendo possível simplesmente fazer push para um servidor qualquer. Sendo assim, os passos para "migrar" de um servidor para o outro pode ser simplesmente fazer um push para o novo servidor da sua própria máquina.
Caso o repo não exista localmente:
git clone <URL_SERVIDOR_ATUAL>
cd <NOME_DO_REPOSITÓRIO>

Faça o checkout em cada branch que se pretende "migrar".
git checkout <NOME_DA_BRANCH>

Para percorrer todas as branches vc pode tentar algo como: (não testei esta parte!)
for remote in $(git branch -r); do
if [[ "${remote}" != "origin/HEAD" ]]; then
git checkout ${remote:7}
fi
done

Pegue também as tags, se desejar:
git fetch --tags

Troque um origin pelo outro:
git remote rm origin
git remote add origin <URL_SERVIDOR_NOVO>

Envie tudo para o novo origin:
git push origin --all
git push --tags


text:
Q: Swap lines conditionally with awk I have the following file,
{
  "number": "12",
  "question": "Sample Question",
  "options": [
    {
      "text": "sample option 1",
      "type": "check",
      "isAnswer": "false"
    },
    {
      "text": "sample option 2",
      "type": "check",
      "isAnswer": "false"
    },
    {
      "text": "sample option 3",
      "type": "check",
      "isAnswer": "true"
    },
    {
      "text": "sample option 4",
      "type": "check",
      "isAnswer": "true"
    },
    {
      "text": "sample option 5",
      "type": "check",
      "isAnswer": "false"
    }
  ],
  "explanation": "sample explanation",
  "reference": "sample ref"
}

I would like to re-order the lines in such a way that type comes before text.
   {
      "type": "check",
      "text": "sample option 1",
      "isAnswer": "false"
    }

I know it is doable, I was able to swap some lines by using awk, but not getting the desired results. It seems to be an interesting problem, Can anyone help?

A: I was able to fix this with the following command.
awk -v r="text" -v o="type" ' $0 ~ o { s = 1 } $0 ~ r && ! s { cur = $0; getline; print; print cur; next; }  1 ' file.json

A: $ awk '$1~/^"text"/{txt=$0; next} {print} txt{print txt; txt=""}' file
{
  "number": "12",
  "question": "Sample Question",
  "options": [
    {
      "type": "check",
      "text": "sample option 1",
      "isAnswer": "false"
    },
    {
      "type": "check",
      "text": "sample option 2",
      "isAnswer": "false"
    },
    {
      "type": "check",
      "text": "sample option 3",
      "isAnswer": "true"
    },
    {
      "type": "check",
      "text": "sample option 4",
      "isAnswer": "true"
    },
    {
      "type": "check",
      "text": "sample option 5",
      "isAnswer": "false"
    }
  ],
  "explanation": "sample explanation",
  "reference": "sample ref"
}

A: This might work for you (GNU sed):
sed -E '/"text":/{N;/"type":/s/(.*)\n(.*)/\2\n\1/;P;D}' file

If the line following "text": contains "type":, swap the lines.
N.B. This may ripple a "text": line down a file if the there are more than one line containing "type": following it.


text:
Q: "Cannot read property of undefined" when using chrome.tabs or other chrome API in content script chrome.tabs returns undefined despite the fact I set tabs in the permissions block.
"permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
],
"content_scripts": [
    {
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": [
            "js/myScript.js"
        ],
        "all_frames": true
    }
],

But in myScript.js the following returns undefined.
chrome.tabs

A: Content scripts have only limited access to Chrome APIs.  This access does not include the API  you are trying to use (e.g. chrome.tabs). If you need to use that API, you will have to do so in a background script1.
As listed in Chrome's content scripts documentation, the APIs available to a content script are [I have placed deprecated methods in strikethrough format]:

*

*extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )

*i18n

*runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )

*storage

A couple of the listed APIs are deprecated and have been for some time. Those that are deprecated have moved to different locations (also listed above):

*

*extension.onRequest ➞ runtime.onMessage

*extension.sendRequest ➞ runtime.sendMessage
While not officially deprecated, extension.lastError is also available as runtime.lastError. At this point, it is usually referred to at that location:

*

*extension.lastError ➞ runtime.lastError
Partition your extension into background scripts and content scripts
You are going to need to separate your code into what needs to be in a background script and what needs to be in content scripts, based on the capabilities available to each type of script. Content scripts have access to the DOM of the web page into which they are injected, but limited access to extension APIs. Background scripts have full access to the extension APIs, but no access to web page content. You should read the Chrome extension overview, and the pages linked from there, to get a feel for what functionality should be located in which type of script.
It is common to need to communicate between your content scripts and background scripts. To do so you can use message passing. This allows you to communicate information between the two scripts to accomplish things which are not possible using only one type of script.
For instance, in your content script, you may need information which is only available from one of the other Chrome APIs, or you need something to happen which can most appropriately (or only) be done through one of the other Chrome extension APIs.  In these cases, you will need to send a message to your background script, using chrome.runtime.sendMessage(), to tell it what needs to be done, while providing enough informaiton for it to be able to do so. Your background script can then return the desired information, if any, to your content script.  Alternately, you will have times when the processing will primarily be done in the background script.  The background script may inject a content script, or just message an already injected script, to obtain information from a page, or make changes to the web page.

*

*Background script means any script that is in the background context. In addition to actual background scripts, this includes popups and options pages, etc. However, the only page that you can be sure to have consistently available to receive messages from a content script are your actual background scripts defined in manifest.json. Other pages may be available at some times as a result of the user's interaction with the browser, but they are not available consistently.

This answer was moved from a duplicate question, and then modified.

A: As content script has its own limitations,
chrome.tabs is only available in background scripts and popup scripts.
If you wanna to use chrome.tabs then pass message from content_script to background script and play with chrome.tabs.

A: https://developer.chrome.com/extensions/tabs#method-getSelected shows

getSelected
chrome.tabs.getSelected(integer windowId, function
  callback)
Deprecated since Chrome 33. Please use tabs.query {active: true}.
  Gets the tab that is selected in the specified window.

Maybe, you should use chrome.tabs.query in popup.js like this
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    console.log(tabs[0].url);
});

, reload your extension and check the result in the inspect element of your extension.
result image
code image
https://developer.chrome.com/extensions/tabs#type-Tab shows that
The URL the tab is displaying. This property is only present if the extension's manifest includes the "tabs" permission.(Just for remind someone forgot. I was forgot it when I just test it.)

A: Check this answer also https://stackoverflow.com/a/6718277/449345
This one worked for me
chrome.tabs.getSelected(null, function(tab){
    console.log(tab);
});


text:
Q: 176VDC - 10A power supply This is what is required by my motor: 176VDC and 6A (10A for security)
I think this will be complicated to find one on second hand market.
My house is powered with 230VAC single phase and 380V 3-phase
Maybe I should built it from scratch?
What are my options and what is your advice?

*

*build my own transformer and add a rectifier bridge ?

*Other one maybe easier?

A: You should not use a "power supply" for a 176V, 6A DC motor. Such a motor is intended to be powered by some type of electronic speed control (ESC) that controls both the voltage and current so that the motor does not draw too much current when starting and accelerating. It is likely that the motor requires both a variable voltage for the armature and a fixed voltage for the field. To get the best advice on ECS requirements, you should post the complete data listed on the motor's rating plate. It is likely that an appropriate ESC could be supplied directly from 230V AC.


text:
Q: Why is an @ symbol after = symbol in excel formula with EPPLUS? This is how the formula appears in excel:

I want to use Forecast formula in Excel with EPPLUS from c#. The formula in the code is correct but in Excel appears =@FORECAST(params).
        ExcelRange targetDate = sheet.Cells[listItems + 2, 2];
        ExcelRange values = sheet.Cells[2, 3, listItems+1, 3];
        ExcelRange timeLine = sheet.Cells[2, 2, listItems+1, 2];

        sheet.Cells[8, 4].Formula = "=FORECAST.ETS(" + targetDate + "," + values + "," + timeLine + ",1,1)";
        sheet.Cells[8, 4].Calculate();

I want to trim the @ from the formula in the excel file, like this:
=FORECAST.ETS(B8,C2:C7,B2:B7,1,1)

A: In code you don't need to put the '=' character
Just use:
  sheet.Cells[8, 4].Formula = "FORECAST.ETS(" + targetDate + "," + values + "," + timeLine + ",1,1)";

A: Similar Problem
I'm having a similar problem with a different formula:
worksheet.Cells[y, x].Formula = "SUMME(C5:C35)";
gave me =@SUMME(C5:C35) within Excel.
Instead of =SUMME(C5:C35).

Solution
It seems that EPPLUS has problems with the German formula. The problem disappears when I use:
worksheet.Cells[y, x].Formula = "SUM(C5:C35)";
My generated Excel now looks like this: =SUMME(C5:C35) (which is what I need)

I know it's not the answer to the exact problem mentioned above. But I thought it might help someone. And maybe serves as a hint to the original question.


text: Q: Add Fing like/Network Scanning to Application I have seen a lot of questions related to obtaining a list of devices on the network and i'm not sure any of them meet my needs.  I need to be able to show a list of devices connected to the network, with IP address/Mac address.  I've seen ARP cache mentioned, as well as scanning a subnet mask, and ICMP broadcast.  Which of these is the best way to get this functionality?  I have concerns about some of the solutions I have seen posted, as most mention non-public API's it would seem.  A point in the right direction would be greatly appreciated, I am also not highly familiar with straight C, which a lot of the mentioned solutions use.


text:
Q: How to use rename_with() in pipe to change all column names from vector I want to apply new column names from a vector to a dataframe.
There are already good answers to this question:
Applying dplyr's rename to all columns while using pipe operator, How do I add a prefix to several variable names using dplyr?
My question is explicitly:
What is the equivalent of rename_with to this:
newcolnames <- c("one", "two", "three", "four", "five")

head(iris) %>%
  setNames(newcolnames)

head(iris) %>%
  `colnames<-`(newcolnames)

I tried:
head(iris) %>%
  rename_with(iris, newcolnames)

I want to use explicitly rename_with!

A: It doesn't seem like rename_with is the right function for this. I guess you could do
iris %>%
  rename_with(~newcolnames)

as kind of a hack. You can also use rename
iris %>%
  rename(!!!setNames(names(.), newcolnames))

But the setNames method just seems much more apt.


text:
Q: Start camera for capturing picture and store image after captureing it in gellary on button click I am working on android application. I have an Activity in which there is two button first one for selecting image from gallary. i have applied function on it. i have one more button capture image . i want to work on it .but don't know how to start camera .I want that when i click button capture image it should start camera for capture image.and there should be option to cancel if don't want to take picture. after pressing cancel camera should cancel.
if i captures image it should it should show in Image View and automatically store in SD card .how should i proceed.

A: http://developer.android.com/guide/topics/media/camera.html. Everything you need to know about  starting a camera. Go through the link.
 private static final int TAKE_PHOTO_CODE = 1;
 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
  startActivityForResult(intent, TAKE_PHOTO_CODE);

 get uri
 private File getTempFile(Context context){

  return new File(path, "/tourpath/yourfilename.jpg");
}

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == RESULT_OK) {
    switch(requestCode){
      case TAKE_PHOTO_CODE:
          try {
           Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file));
          iv.setImageBitmap(captureBmp);//show in imageview
       } catch (FileNotFoundException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
       }
      break;
    }
  }
}


text:
Q: Why do the JTAG parallel registers update on the falling edge? The TMS state is change on the falling edge of the TCK clock. It is logical that the state of the chip TAP FSM is changes on the rising edge of the TCK clock. Data loading to the shift register on the Capture-XX state or shifting the shift register on the Shift-XX state are also deploying on the rising edge. Why do JTAG parallel registers update on the falling edge? Is there any reason why the standard says to do so?

A: This does not apply only to Update-DR. Update-IR latches instruction on falling edge, TDO updates on falling edge as well. It looks more like a general design pattern rather than just chance.
Advocating for this kind of pattern is handling TCK distribution skew wrt. hold time.  Remember TCK is distributed in parallel on the board.
Let's say you have a board where TCK has some non-uniform clock delay, then chip A receives TCK x ps before chip B. If there are some nets from B to A (including B.TDO -> A.TDI, if applicable) with a propagation delay of less than x ps, you may have unresolvable skew issues in cases where sampling and update happens on rising edge.
OTOH, if update happens on falling edge and sampling happens on rising, ATE can always limit clock frequency to get in a working condition.
At first, this advocates for having TDO only updated on falling edge, but with topologies like in figure 4-2 of IEEE-1149.1-2001, (reproduced below: two chains sharing TDI and TCK and TDO but not TMS), there is no requirement for various TAPs of the same board to be in the same state. Then when some TAP is in Capture-DR and other is in Update-DR, we get to the same kind of problem with boundary scan cells. So the standard enforces this requirement everywhere.

A: From Freescale Semiconductor Application Note AN2074 - DSP56300 JTAG Examples

• Test Data Input (TDI). This input is used to transfer instructions and data serially into the device. TDI is sampled on the rising edge of TCK and has an internal pull-up resistor.

• Test Data Output (TDO). This output is used to transfer data out of the device serially. TDO changes on the falling edge of TCK.

The TAP [16-state TAP controller state machine] changes state based on the level of TMS. Transitions from one state to another occur on the rising edge of TCK. Instructions and data are transferred in through TDI, which is sampled on the rising edge of TCK, while data is transferred out through TDO, which changes on the falling edge of TCK. This sampling technique prevents the development of a race condition in the TAP.

From Multi-ICE JTAG port timing characteristics

In a JTAG device that fully complies to IEEE1149.1, TDI and TMS are sampled on the rising edge of TCK, and TDO changes on the falling edge of TCK. To take advantage of these properties, Multi-ICE samples TDO on the rising edge of TCK and changes its TDI and TMS signals on the falling edge of TCK. This means that with a fully compliant target, issues with minimum setup and hold times can always be resolved by simply decreasing the TCK frequency, because this increases the separation between signals changing and being sampled.

By using different edges, set and hold times can be established to avoid race conditions and if race conditions is a problem, then it can be fixed by slowing down the clock.


text:
Q: save files to a non-persistent bootable drive good morning / good evening everyone.
being a neophyte the question below might seem a bit obvious but I hope it will be useful to others as well.
in an USB I installed a Linux live distro (Kali Linux) in a NON persistent way.
I would like to understand if I can add some bash files that I will need every time I use the machine without making it persistence.
I have already tried to create a directory but this is not displayed by the machine and I cannot find the "cdrom" folder that some forums have talked about.
The directory is located directly in the root path of the drive, it is not a subdirectory.
i can see files and folders from windows 10.
to do this would you need a new partition or could it be done in a simpler way?
I've seen many other forums before but can't find the answer.
thanks
(edit)
how can i put some file from windows to my USB and be able to use them into the OS of the USB (Linux) without making a persistent live USB?


text:
Q: having trouble importing CSV I usually use AWS s3 to import csv files and it is really easy. Trying to import this csv file straight from the file explorer and continuing to get an error. Is it different?
import pd as pandas

month = pd.read_csv("12Month.csv")
print(month)

Error: [Errno 2] No such file or directory: '12Month.csv'

A: You probably will have to state the full path.
import pandas as pd
month = pd.read_csv(r"C: etc... 12Month.csv"")

or use :
 from pathlib import Path
 wdir = Path.cwd()
 filename = path(wdir,"12Month.csv")
 month = pd.read_csv(filename)


text:
Q: Center UILabel Subview I have a UIImageView as the background view of my table view. When there is no data for the table, I am adding a UILabel as a subview of the image view. I am having trouble getting the label centered though. The label is always off to the right.
UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:self.tableView.frame];
    backgroundImageView.image = [UIImage imageNamed:@"background"];
    backgroundImageView.center = self.tableView.center;

    self.noLocationsLabel = [[UILabel alloc]initWithFrame:backgroundImageView.frame];
    self.noLocationsLabel.center = backgroundImageView.center;
    self.noLocationsLabel.text = @"No saved locations";
    self.noLocationsLabel.textAlignment = NSTextAlignmentCenter;
    self.noLocationsLabel.textColor = [UIColor blackColor];
    self.noLocationsLabel.font = [UIFont fontWithName:@"Chalkboard SE" size:24.0];

self.tableView.backgroundView = backgroundImageView;

if (self.locationsArray.count == 0) {
        self.navigationItem.rightBarButtonItem.enabled = NO;

        [self.tableView.backgroundView addSubview:self.noLocationsLabel];
        self.tableView.userInteractionEnabled = NO;
    }

A: If your image frame is say 50,50,50,50, then your label will also be 50,50,50,50, but since it's a subview of the image view, it will never be in the center.  Same concept applies to center.  Center is only in respect to the views superview.
In order to make it center you could set the frame like:
CGRect rect = CGRectMake(0,0,backgroundImageView.frame.size.width,backgroundImageView.frame.size.height);

self.noLocationsLabel = [[UILabel alloc]initWithFrame: rect];

Or perhaps even:
self.noLocationsLabel = [[UILabel alloc]initWithFrame: backgroundImageView.bounds];

Edit:
You can use center on subviews.  But you have to set the correct center.
self.noLocationsLabel.center = CGPointMake(CGRectGetMidX(backgroundImageView.bounds),CGRectGetMidY(backgroundImageView.bounds));

Difference between frame and bounds


text:
Q: Audio playback for movie despite in silent mode? sorry for my question but i´ve implemented a intro- video and despite of the hardware silent-switch of my iPad, the audio is playing.
I´m also using the AVAudioplayer within my app just for playing short sound samples. Within this class, its the only region where i´ve set up the "AVAudioSessionCategory".
But for all audio playback only, there´s nothing hearable. Its just for my intro-video.
Any help how to fix that "audio-bug" so the movie player is silent?
Thanks you
Here´s my Audio-class:
- (id)initWithSoundfileName:(NSString*) file
{
    if ((self = [super init]))
    {
        NSString* filename =       [file stringByDeletingPathExtension];
        NSString* fileextension =  [file pathExtension];

        // get file path from bundle
        NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: filename ofType: fileextension];
        NSLog(@"AudioPlayer init: %@", soundFilePath);

        NSURL* fileurl = [[NSURL alloc] initFileURLWithPath:soundFilePath];
        NSError* error = nil;

        AVAudioPlayer* audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileurl error:&error ];
        if (error) { NSLog(@"Error creating AVAudioPlayer %@", [error description]);}

        // set audio policy
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:NULL];

        self.player =  audioplayer;
        [self.player prepareToPlay];
        [self.player setDelegate:self];
    }
    return self;

}
-(void) play{
    [self.player play];
}

And here´s my video-playback method:
- (void)playIntroVideo
{
    NSString *movpath = [[NSBundle mainBundle] pathForResource:@"mymovie" ofType:@"mp4"];

    NSURL *fileURL    =   [NSURL fileURLWithPath:movpath];
    self.moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
    self.moviePlayerController.fullscreen = YES;
    self.moviePlayerController.scalingMode = MPMovieScalingModeAspectFit;
    self.moviePlayerController.controlStyle = MPMovieControlStyleNone;
    self.moviePlayerController.movieSourceType = MPMovieSourceTypeFile;

    self.moviePlayerController.useApplicationAudioSession = NO;
    [self.moviePlayerController.view setFrame: self.view.bounds];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackComplete:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:self.moviePlayerController];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackStateChanged:)
                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification
                                               object:self.moviePlayerController];

    [self.view addSubview:self.moviePlayerController.view];

    [self.moviePlayerController prepareToPlay];
    [self.moviePlayerController play];
}

A: Like @Till mentioned:
When I change the MoviePlayerController property to useApplicationAudioSession=TRUE, it fixes my problem. Audio Playback is silent.


text:
Q: Excel VBA - Split Sheets of Saved excel Files I need some help with excel VBA code,
I have split a file into seperate files based on a column (Country) using the below VBA code. This produces around 40 seperate files,
Example data

Produces:
Australia.xslx
Costa Rica.xslx
Tanzania.xslx
United Kingdom.xslx
Is there a way to then split each of the files by another column (with row entries 1,2,3), so that each file has three sheets without having to open each file and running a macro for each file?
 -> -  -

VBA - Split Sheet
Sub Split_Sheet()
Const FirstC As String = "A" '1st column
Const LastC As String = "C" 'last column
Const sCol As String = "A" '<<< Column to Split data by
Const shN As String = "Countries" '<<< Source Sheet
Dim ws As Worksheet, ws1 As Worksheet
Set ws = Sheets(shN)
Dim rng As Range
Dim r As Long, c As Long, x As Long, r1 As Long
Application.ScreenUpdating = False
r = ws.Range(FirstC & ":" & LastC).Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

 c = ws.Cells.Find(What:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column + 2

Set rng = ws.Range(ws.Cells(1, FirstC), ws.Cells(r, LastC))

ws.Range(sCol & ":" & sCol).Copy
ws.Cells(1, c).PasteSpecial xlValues

Application.CutCopyMode = False
ws.Cells(1, c).Resize(r).RemoveDuplicates Columns:=1, Header:=xlYes
r1 = ws.Cells(Rows.Count, c).End(xlUp).Row
ws.Cells(1, c).Resize(r1).Sort Key1:=ws.Cells(1, c), Header:=xlYes
ws.AutoFilterMode = False
Application.DisplayAlerts = False
For x = 2 To r1
For Each ws1 In Sheets
If ws1.Name = ws.Cells(x, c) Then ws1.Delete
Next
Next
Application.DisplayAlerts = True
For x = 2 To r1
ws.Range(ws.Cells(1, sCol), ws.Cells(r, sCol)).AutoFilter Field:=1, Criteria1:=ws.Cells(x, c)
Set ws1 = Worksheets.Add(after:=Worksheets(Worksheets.Count))
ws1.Name = ws.Cells(x, c).Value
rng.SpecialCells(xlCellTypeVisible).Copy
Range("A1").PasteSpecial Paste:=xlPasteFormats
Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Next x
With ws
.AutoFilterMode = False
.Cells(1, c).Resize(r).ClearContents
.Activate
.Range("A1").Select
End With
Application.ScreenUpdating = True
End Sub

VBA - Save Each File
Sub SaveEachWorksheet()

Dim FPath As String

FPath = Application.ActiveWorkbook.Path

Application.ScreenUpdating = False

Application.DisplayAlerts = False

For Each ws In ThisWorkbook.Sheets

    ws.Copy

    Application.ActiveWorkbook.SaveAs Filename:=FPath & "\"ws.Name & ".xlsx"

    Application.ActiveWorkbook.Close False

Next

Application.DisplayAlerts = True

Application.ScreenUpdating = True

End Sub

A: EDIT - took a different approach.  Tested with 20k records/15 countries, 5 categories.
Try something like this:
Sub SplitToFiles()

    Dim wsData As Worksheet, rngData As Range, data, country, category, ws As Worksheet
    Dim col As New Collection, wb, dict As Object, r As Long, k, categories As Collection

    Set dict = CreateObject("scripting.dictionary")

    Set wsData = ThisWorkbook.Worksheets("Countries")
    Set rngData = wsData.Range("A1").CurrentRegion 'assuming no empty rows/columns in data
    data = rngData.Value

    'collect unique countries (as dictionary keys) and categories (in collections, by country)
    For r = 2 To UBound(data, 1)
        country = data(r, 1)
        category = data(r, 2)
        If Len(country) > 0 And Len(category) > 0 Then
            If Not dict.exists(country) Then dict.Add country, New Collection
            On Error Resume Next                 'ignore error
            dict(country).Add category, category 'add the category (unique using key)
            On Error GoTo 0
        End If
    Next r

    Application.ScreenUpdating = False
    For Each country In dict
        Set categories = dict(country)
        Set wb = GetWorkbook(country, dict(country)) 'create workbook/sheets for this country
        For Each category In categories
            Debug.Print country, category
            ResetFilters wsData
            With rngData
                .AutoFilter Field:=1, Criteria1:=country
                .AutoFilter Field:=2, Criteria1:=category
                .Columns(2).Resize(, .Columns.Count - 1).SpecialCells(xlCellTypeVisible).Copy
            End With
            With wb.Worksheets(category).Range("A1")
                .PasteSpecial Paste:=xlPasteFormats
                .PasteSpecial Paste:=xlPasteColumnWidths
                .PasteSpecial Paste:=xlPasteValues
            End With
        Next category
        wb.Close savechanges:=True
    Next country
    ResetFilters wsData
End Sub

'Creates workbook and worksheets as needed
Function GetWorkbook(country, categories As Collection)
    Dim wb As Workbook, i As Long

    Set wb = Workbooks.Add(xlWBATWorksheet) 'new wb with one sheet
    wb.Sheets(1).Name = categories(1)
    For i = 2 To categories.Count 'name the rest of the sheets (if any)
        wb.Worksheets.Add(after:=wb.Worksheets(wb.Worksheets.Count)).Name = categories(i)
    Next i
    wb.SaveAs ThisWorkbook.Path & "\" & country & ".xlsx"
    Set GetWorkbook = wb
End Function

Sub ResetFilters(ws As Worksheet)
    On Error Resume Next
    ws.ShowAllData
End Sub


text:
Q: Regex to match all the strings between two identical strings E.g. I have this string
-- This -- is -- one -- another -- comment --
I want the matched elements to be
"This", "is", "one", "another", and "comment"
I was trying this regex
--\s+([^--]+)\s+--
which gives me the matched elements as
"This", "one" and "comment"
I have searched for other problems, they all provide solution like this i.e. #A# and I will get A but for #A#B# also I get A, but in this case I want both the elements A and B as both of them are between two # chars.
I am  testing it for javascript regex, but I think solution should be irrespective of platform/language.

A: In general, you need to use  a pattern like
STRING([\s\S]*?)(?=STRING|$)

It will match STRING, then capture into Group 1 any zero or more chars, as few as possible, up to the first occurrence of STRING *stopping right before this word** because the (?=...) is a positive lookahead that, being a zero-width assertion, does not consume matched text or end of string.
A generic variation of the pattern is
STRING((?:(?!STRING)[\s\S])*)

It uses a tempered greedy token, (?:(?!STRING)[\s\S])*, that matches any char, 0 or more occurrences, that does not start a STRING char sequence.
To get all the substrings in the current solution, use a lookahead like
/--\s+([\s\S]*?)(?=\s+--)/g
                ^^^^^^^^^

See the regex demo.
Note that [^--]+ matches 1 or more symbols other than a -, it does not match any text that is not equal to --. [...] is a character class that matches a single character. To match any text of any length from one char up to the first occurrence of a pattern, you can rely on a [\s\S]*? construct: any 0+ chars, as few as possible (due to the lazy *? quantifier).
JS demo:

var s = '-- This -- is -- one -- another -- comment --';
var rx = /--\s+([\s\S]*?)(?=\s+--)/g;
var m, res=[];
while (m = rx.exec(s)) {
  res.push(m[1]);
}
console.log(res);

A: To read all I would use positive look ahead:

const data = '-- This -- is -- one -- another -- comment --'

const readAll = data => {
  const regex =/--\s*(.*?)\s*(?=--)/g
  const found = []
  let temp
  while (temp = regex.exec(data)) {
    found.push(temp[1])
  }
  return found
}

console.log(readAll(data))

And to remove comments just do this:

const data = `-- This -- is -- one -- another -- comment -- this is not a comment`.replace(/--.*--/g, '')

console.log(data)


text:
Q: Why I get this errors when I install Sitecore 9?
I following official documentation - "Sitecore Experience Platform 9.0 Update 1", and after running the powershell script below
 ...
#install client certificate for xconnect
$certParams = @{
    Path = "$PSScriptRoot\xconnect-createcert.json"
    CertificateName = "$prefix.xconnect_client"
}
18: Install-SitecoreConfiguration @certParams -Verbose <----------------

#install solr cores for xdb
$solrParams = @{
    Path = "$PSScriptRoot\xconnect-solr.json"
    SolrUrl = $SolrUrl
    SolrRoot = $SolrRoot
    SolrService = $SolrService
    CorePrefix = $prefix
    Name = "SC9"
}
Install-SitecoreConfiguration @solrParams
...

I get errors...I can't understood what I do wrong. Help me please!


text:
Q: How to make a Storyboard image fill its frame entirely? Notice how the System image: Person.crop.circle does not touch the edges of the frame. How do I fix that?
(Also I don't want to write code for this, please let me know how to fix this in storyboard).

Storyboard screenshot

A: What worked for me was to set point-Size within Configuration under in the Attributes Inspector equal to 1


text:
Q: Java int vs. Double public double calc(int v1) {
return v1 / 2 + 1.5;
}

public double cald (double v) {
return v / 2 + 1.5;
}

Do the functions return the same result?
I would argue that they don't return the same result, as the second function would include the decimal point, where as the second function would round the number up.
Is that correct?

A: when you divide a by b  i.e a/b
if both a & b are int then result will be int
else any or both a & b are double then result will be double
Edit:
Also see my answer to this Question Simple Divide Problem

A: They don't: see sample on IDEONE, clone it and play with it.
System.out.println(calc(1));// gives 1.5
System.out.println(cald(1.0));// gives 2.0

A: int v1 = 1;
return v1 / 2 + 1.5; // = 1.5

it is an integer divided by an integer more double.
Or in your case 1 / 2, that it is 0.5, but it is a division amoung ints, so will be 0, more 1.5, return 1.5.
double v = 1.0;
return v / 2 + 1.5; // = 2.0

This case, the division is between an double and an int, returning an double  of value 0.5, summing with 1.5 will return 2.0.

A: They don't return the same. / on default is integer division if the numbers are integers, i.e., the result of a/2 is an integer without the reminder if a is an integer. while if a is a double, then the result of this division is a double.
5/2 = 2
5.0/2 = 2.5


text:
Q: laravel eloquent - need help coverting a restrictions white list into a black list I currently have a resources table :

*

*Resources table has the columns: id - title- description - path

and a resource_user_role_restrictions table

*

*resource_user_role_restrictionstable has the columns: id - resource_id - role_id - viewable

My model contains the following function that checks the resource_user_role_restrictions table and returns all resources whose resource_user_role_restrictions.role_id matches the passed in $userRoleId and if it's viewable column set to 1:
public function scopeResourcesFilter($query, array $filters) {
     $userRoleId = $filters[0];

     $query->whereHas('resourceUserRoleRestrictions', function  ($query) use($userRoleId){
         $query->where('viewable', 1)->where("role_id", $userRoleId );
     });
    }

This function is called in my controller:
$userRoleId = Auth::user()->role_id;

$resources = Resource::resourcesFilter([$userRoleId])->with('country', 'resourceUserRoleRestrictions')->get();

However, this now needs to be converted into a black list whereby the viewable column is removed and any resource on the table is assumed to be restricted and not viewable, thus not returned. I cant figure out how to get it woking. Ideally this function should now return all items from the resources table except those whose  resource_user_role_restrictions.user_role matches the passed in $userRoleId.
Any help at all would be greatly appreciated.

A: looks like whereDoesntHave() is what I needed.
$query->whereDoesntHave('resourceUserRoleRestrictions', function  ($query) use($userRoleId){
            $query->where("role_id", $userRoleId );
        });


text:
Q: Ember.Select content vs contentBinding The docs for Ember.Select use the following:
{{view Ember.Select content=foo ... }}

However, the guide uses the following
{{view Ember.Select contentBinding="foo" ... }}

Both work.  Which is preferred and why?

A: When you use:
{{view Ember.Select content=foo ... }}

You are creating a property called content with the value foo (or the value from the property foo) in the View. In this case the Select. Given you are only assigning a value, nothing happens in the View if the value foo changes in the 'parent' context. I use this approach when  I don't need bindings. i.e. When passing a generic String
{{view Ember.Select message="Mi message" ... }}

When you use:
{{view Ember.Select contentBinding="foo" ... }}

You are setting up a binding. It basically means that you connect one property with another. When one changes the other changes too. Specifically it means that a content property inside the View is created with the value from the property foo. Whenever the property foo changes in the 'parent' context the content property in the View will change as well. The same is true in the other direction, whenever the content property in the View is changed the foo property from the 'parent' context will be modified.
Another nice resource.
I hope this helps you!

A: contentBInding="foo" is old Syntax content=foo is new. Old syntax must be deprecated.
check API docs


text:
Q: Android DatePickerDialog Show only current month remain dates selectable I am trying to show only the current month with the remaining dates selectable in Date Dialog Piker.
My Code:
val calendar = Calendar.getInstance()
//getting current day,month and year.
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)

val datePickerDialog =
    DatePickerDialog(
        context, DatePickerDialog.OnDateSetListener
        { view, year, monthOfYear, dayOfMonth ->
            val currentDate: String = "$year-${(monthOfYear + 1)}-$dayOfMonth"

        }, year, month, day
    )

// Max = current
val maxTime = calendar.timeInMillis

// Move day as first day of the month
calendar.set(Calendar.MONTH, 1)
// Move "month" for previous one
calendar.add(Calendar.MONTH, 1)

// Min = time after changes
val minTime = calendar.timeInMillis
datePickerDialog.datePicker.maxDate = maxTime
datePickerDialog.datePicker.minDate = System.currentTimeMillis()
datePickerDialog.show()

It's showing the current month and current date selectable but future dates are also disabled. I only want previous dates to be disabled and future remaining dates can be selectable of current month.

A: You are clearly setting maxDate minDate to present day so all the other days in calendar was blocked.
val minTime = calendar.timeInMillis

datePickerDialog.datePicker.maxDate = maxTime

// above for maxTime you assigned current date don't provide maxDate datepickerdialog remove above line and check
datePickerDialog.datePicker.minDate = System.currentTimeMillis()
datePickerDialog.show()


text:
Q: Getting rid of outer parentheses on a list The particular problem I have is with creating a solution for question 4.16b of Structure and Interpretation of Computer Programs. Here a procedure needs to be created that transforms
(lambda (a b)
  (define u 'u)
  (define v 'v)
   'e1))

Into:
(lambda (a b)
  (let ((u '*unassigned*)
        (v '*unassigned*))
    (set! u 'u)
    (set! v 'v)
    'e1))

My procedure (see below) does not do this, but instead transforms it into:
(lambda (a b)
  (let ((u *unassigned*)
        (v *unassigned*))
    ((set! u 'u)
     (set!  v 'v))
    ('e1)))

Here we have a problem with the list of sets! produced by make-sets (see below) and the rest of the body (('e1) above) produced by cons current-element rest-of-body (see below). They are added into lists, while I want to have them as single statements, i.e., (set! u 'u) (set! v 'v) instead of ((set! u 'u) (set! v 'v)) and 'e1 instead of `('e1).
Procedure:
;; b.  Write a procedure scan-out-defines that takes a procedure body and returns an
;; equivalent one that has no internal definitions, by making the transformation
;; described above.

(define (scan-out expr)
  (let ((vars (cadr expr))
        (body (cddr expr)))
    (make-lambda vars
                 ; loop over body,
                 ; store all definition names and bodies of the defines
                 ; once finished looping transform those into lets
                 ; where the rest is added to the body
                 (let body-transform ((body-elements body)
                                      (definition-names '())
                                      (definition-bodies '())
                                      (rest-of-body '()))
                   (if (null? body-elements)
                     (transform-define-into-let definition-names
                                                definition-bodies
                                                rest-of-body)
                     (let ((current-element (car body-elements)))
                       (if (tagged-list? current-element 'define)
                         (body-transform (cdr body-elements)
                                         (cons (get-definition-name current-element)
                                               definition-names)
                                         (cons (get-definition-body current-element)
                                               definition-bodies)
                                         rest-of-body)
                         (body-transform (cdr body-elements)
                                         definition-names
                                         definition-bodies
                                         (cons current-element rest-of-body)))))))))

(define (tagged-list? exp tag)
  (if (pair? exp)
    (eq? (car exp) tag)
    false))

(define (get-definition-name expr)
  (cadr expr))

(define (get-definition-body expr)
  (caddr expr))

(define (transform-define-into-let vars vals rest-of-body)
  (list (list 'let (make-unassigned-vars vars)
        (make-sets vars vals)
        rest-of-body)))

(define (make-unassigned-vars vars)
  (let aux ((var-elements vars)
            (unassigned-vars '()))
    (if (null? var-elements)
      unassigned-vars
      (aux (cdr var-elements)
           (cons (list (car var-elements) '*unassigned*) unassigned-vars)))))

(define (make-sets vars vals)
  (let aux ((var-elements vars)
            (val-elements vals)
            (sets '()))
    (if (null? var-elements)
      sets
      (aux (cdr var-elements)
           (cdr val-elements)
           (cons (list 'set! (car var-elements) (car val-elements)) sets)))))

(define (make-lambda parameters body)
  (cons 'lambda (cons parameters body)))

; testing
(scan-out '(lambda (a b)
             (define u 'u)
             (define v 'v)
             'e1))

; Should be transformed into:

; => (lambda (a b)
;      (let ((u '*unassigned*)
;            (v '*unassigned*))
;        (set! u 'u)
;        (set! v 'v)
;        'e1))

; But is transformed into:

; => (lambda (a b)
;      (let ((u *unassigned*)
;            (v *unassigned*))
;        ((set! u (quote u))
;         (set!  v (quote v)))
;        ((quote e1))))

What I tried is flattening the lists like so:
(define (transform-define-into-let definition-names definition-bodies rest-of-body)
  (list (list 'let (make-unassigned-vars definition-names)
        (append* (make-sets definition-names definition-bodies))
        (append* rest-of-body))))

but then only the rest-of-body is stripped of its outer parentheses, make-sets is still a list: e.g.,
(lambda (a b)
  (let ((u *unassigned*)
        (v *unassigned*))
    ((set! u 'u)
     (set! v 'v))
    'e1))

What is the proper way to get rid of the outer parentheses?
If anyone can help me out with this that would be greatly appreciated.

A: You should change:
(define (transform-define-into-let vars vals rest-of-body)
  (list (list 'let (make-unassigned-vars vars)
        (make-sets vars vals)
        rest-of-body)))

into:
(define (transform-define-into-let vars vals rest-of-body)
  (list (append (list 'let (make-unassigned-vars vars))
                (append (make-sets vars vals)
                        rest-of-body))))

and also:
(define (make-unassigned-vars vars)
  (let aux ((var-elements vars)
            (unassigned-vars '()))
    (if (null? var-elements)
      unassigned-vars
      (aux (cdr var-elements)
           (cons (list (car var-elements) '*unassigned*) unassigned-vars)))))

into
(define (make-unassigned-vars vars)
  (let aux ((var-elements vars)
            (unassigned-vars '()))
    (if (null? var-elements)
      unassigned-vars
      (aux (cdr var-elements)
           (cons (list (car var-elements) ''*unassigned*) unassigned-vars)))))

Finally note that 'u is identical to (quote u).


text:
Q: cd using empty string inconsistencies According to "chdir" xopen specification, using an empty string ("") as argument should results in an error (enoent):
[ENOENT]
A component of path does not name an existing directory or path is an empty string.

I've checked many different combinations of OSes and shells using command;
cd ""

which eventually calls "chdir" system call, with argv == 2, and argv[1] pointing to an empty string.
The results is that only some ksh93  (not all versions) on Linux (not on AIX) returns an error. "/bin/sh" always success but on AIX it moves to $HOME and on linux cwd is unchanged
Why so many differences?

A: You are comparing apples and pears here.
The xopen specification you are quoting, refers to the C-function chdir.
The two shells I'm using (bash and zsh) have an internal command cd, and in both shells, a
cd ''

is interpreted as a no-op. This is explained in the man pages, for example for bash:

A null directory name in CDPATH is  the  same  as  the current  directory,  i.e., ``.''.

So this is the intended behaviour. Note that the standard you are quoting doesn't say anything about the shell's cd command.
I didn't check how the developers of bash and zsh actually implemented the cd command, but if they want to comply to their own specification, they must implement it (in C) similar to this:
if(argc == 0) {
    chdir(getenv("HOME"));
} else if(strlen(argv[1]) == 0) {
    chdir(".");
} else {
    chdir(argv[1]);
}

If it's not done in this way, the behaviour of the chdir command would depend on the underlying implementation of the system library (and, yes, on the conformance to the xopen standard), and this would certainly be a bug in the shell implementation (though a different one than you are referring to).
UPDATE: As CoolRaoul correctly noted in his comment, my quote of the bash manpage is not relevant here, as it refers only to an empty element in the CDPATH, not to an empty argument of the cd command. While it is reasonable to assume that the effect in both cases should be the same, this is not explicitly specified. The same is true for the zsh manpage. In both manpages, it is also not explicitly said that the cd command invokes the C function chdir (although this also can reasonably assumed), nor do they seem to refer to any compliance to the xopen specification. At least for bash and zsh, I think we can safely say that the behaviour of cd "" is simply unspecified.
BTW, I also tried it with the ksh which comes with Cygwin (and which identifies itself as MIRBSD KSH R50), and it behaves in the same way as bash and zsh.

A: Check section 4, Shell & Utilities of the IEEE Std 1003.1™ or Open Group Base Specification.
This contains a separate page for cd, which says:

The cd utility shall then perform actions equivalent to the chdir()
  function called with curpath as the path argument. If these actions
  fail for any reason, the cd utility shall display an appropriate
  error message and the remainder of this step shall not be executed.

This would suggest that the ksh93 that fails on cd "" is actually working according to spec.  This is what I see on Ubuntu 14.04, ksh Version AJM 93u+ 2012-08-01.

A: As suggested previously, you can trace through the cd open group page to find the behavior (my notes are the bullet-points):

*

*If no directory operand is given and the HOME environment variable is empty or undefined, the default behavior is implementation-defined and no further steps shall be taken.

*

*This is not true, as there is a directory operand, it's just a zero-length string

*If no directory operand is given and the HOME environment variable is set to a non-empty value, the cd utility shall behave as if the directory named in the HOME environment variable was specified as the directory operand.

*

*See above

*If the directory operand begins with a <slash> character, set curpath to the operand and proceed to step 7.

*

*Again false, go to the next step

*If the first component of the directory operand is dot or dot-dot, proceed to step 6.

*

*false again

*Starting with the first pathname in the <colon>-separated pathnames of CDPATH (see the ENVIRONMENT VARIABLES section) if the pathname is non-null, test if the concatenation of that pathname, a <slash> character if that pathname did not end with a <slash> character, and the directory operand names a directory. If the pathname is null, test if the concatenation of dot, a <slash> character, and the operand names a directory. In either case, if the resulting string names an existing directory, set curpath to that string and proceed to step 7. Otherwise, repeat this step with the next pathname in CDPATH until all pathnames have been tested.

*

*Here's where we hit the meat.  By the specification, if CDPATH is set and a pathname in there points to a directory, it will find the first existing pathname.  So if CDPATH is /foo:/bar:/baz and /foo does not exist, cd will first try /foo/ and fail this step.  It will then try /bar/.  If /bar exists as a directory, it will set curpath to /bar/ and proceed.  If CDPATH is null, it will test ./ to see if it points to a directory (and it will, typically, because this is your pwd).

*Set curpath to the directory operand.

*

*In other words, if CDPATH is set but none of its components exist, it will just use the directory operand, which is an empty string.

*If the -P option is in effect, proceed to step 10. If curpath does not begin with a <slash> character, set curpath to the string formed by the concatenation of the value of PWD, a <slash> character if the value of PWD did not end with a <slash> character, and curpath.

*

*If we hit step 6, this will set curpath to the PWD, as it will be $(pwd)/.

*In essence, by this step, if CDPATH is set and has an existing directory as a component, the first existing component will be what curpath is now, otherwise curpath will be PWD (or possibly PWD/./ to the same effect)

*The curpath value shall then be converted to canonical form as follows, considering each component from beginning to end, in sequence:

*

*Dot components and any <slash> characters that separate them from the next component shall be deleted.

*For each dot-dot component, if there is a preceding component and it is neither root nor dot-dot, then:

*

*If the preceding component does not refer (in the context of pathname resolution with symbolic links followed) to a directory, then the cd utility shall display an appropriate error message and no further steps shall be taken.

*The preceding component, all <slash> characters separating the preceding component from dot-dot, dot-dot, and all  characters separating dot-dot from the following component (if any) shall be deleted.

*An implementation may further simplify curpath by removing any trailing <slash> characters that are not also leading  characters, replacing multiple non-leading consecutive  characters with a single <slash>, and replacing three or more leading <slash> characters with a single <slash>. If, as a result of this canonicalization, the curpath variable is null, no further steps shall be taken.

*

*Simple path canonicalization.  Interestingly, they account in the last step for if the path is left null by explicitly showing it as a noop, though I'm not sure how this could possibly happen, as all relative paths have PWD prepended to them before this step.

*If curpath is longer than {PATH_MAX} bytes (including the terminating null) and the directory operand was not longer than {PATH_MAX} bytes (including the terminating null), then curpath shall be converted from an absolute pathname to an equivalent relative pathname if possible. This conversion shall always be considered possible if the value of PWD, with a trailing <slash> added if it does not already have one, is an initial substring of curpath. Whether or not it is considered possible under other circumstances is unspecified. Implementations may also apply this conversion if curpath is not longer than {PATH_MAX} bytes or the directory operand was longer than {PATH_MAX} bytes.

*

*Doesn't seem to do much other than make the path relative again if it's too long.

*The cd utility shall then perform actions equivalent to the chdir() function called with curpath as the path argument. If these actions fail for any reason, the cd utility shall display an appropriate error message and the remainder of this step shall not be executed. If the -P option is not in effect, the PWD environment variable shall be set to the value that curpath had on entry to step 9 (i.e., before conversion to a relative pathname). If the -P option is in effect, the PWD environment variable shall be set to the string that would be output by pwd -P. If there is insufficient permission on the new directory, or on any parent of that directory, to determine the current working directory, the value of the PWD environment variable is unspecified.

*

*And here is where the chdir actually takes place.

In conclusion
So in essence, a command of cd '' by the standard should cd to the first existing component of CDPATH, if it is set, or to the current directory otherwise.  If cd -P '' is used, it will also remove symlinks from the path.  In this way, chdir should only be called with an empty string if CDPATH is non-null, but none of its components exist, and cd -P '' is called, as that will pass through step 5, set the curpath to an empty string in step 6, then jump from step 7 to step 10.  I don't see any other way that chdir would be called with an empty string, unless a bad implementation takes step 9 too literally and sets curpath to an empty string following the last sentence.  ksh93 on Linux and /bin/sh on AIX are nonconformant by these rules.  In this way, I'd be careful about using a cd to a path that might evaluate zero-length, as a CDPATH being set can weirdly affect what you're trying to do (though CDPATH has unexpected and confusing behavior anyway, and should not be used in most cases).


text:
Q: How to use breakpoints in Eclipse I am using the Eclipse IDE. I don't know how effectively put breakpoints in Eclipse and go forward and backward into it. Can anyone help me?
Can anyone suggest a site suitable for me?

A: Here is a video about Debugging with eclipse.
For more details read this page.
Instead of Debugging as Java program, use Debug as Android Application
May help new comers.

A: To put breakpoints in your code, double click in the left margin on the line you want execution to stop on. You may alternatively put your cursor in this line and then press Shift+Ctrl+B.
To control execution use the Step Into, Step Over and Step Return buttons. They have the shortcuts F5, F6 and F7 respectively.
To allow execution to continue normally or until it hits the next breakpoint, hit the Resume button or F8.

A: Put breakpoints - double click on the margin.
Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.

A: Googling gives many sites... Debugging with the Eclipse platform for one.

A: Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-
http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/


text:
Q: Cannot concatenate dcd files in VMD using catdcd tool I have a set of dcd files that I want to concatenante to have one (long) dcd file. I put in a VMD Tkconsole (VMD version : 1.9.2) the following code :
catdcd -o output.dcd -i indexFile.ind input1.dcd input2.dcd input3.dcd

and I had the following error :
wrong # args: should be "catdcdList dcdFileNames outFile indexFile stride"

so I wrote :
catdcdList -d input1.dcd input2.dcd input3.dcd -o output.dcd -i indexFile.ind -s 1

Even though the catdcdList command is reckognized (colored in green), I still have exactly the same error message. I tried out littles changes to my request but I keep getting the above error message. The second example from the official catdcd webpage does not work neither.

A: I have been having the same issue with catdcd on my ubuntu 15.10 laptop.
In order to get it to work, I added the catdcd directory to my PATH.
How to do this (note, my instructions add catdcd permanently to PATH):
1) Go to /home/user directory. Using ls -a command you should see a file called .bashrc (don't forget the "."; it's important and means that the file is a hidden file).
2) Open .bashrc using gedit (or a similar text editor). If you want, you can make a backup of .bashrc (cp .bashrc ./.bashrc_bkup for example).
3) At the end of .bashrc, append this:
export PATH="/usr/local/lib/vmd/plugins/LINUXAMD64/bin/catdcd5.1:$PATH"
This directory is the default that is installed when you configure VMD 1.9.2. Note that you may have a different version of catdcd installed (such as catdcd4.0, which comes from the VMD website). In any case, you'll need to find the directory that corresponds to the catdcd file on your computer.
4) Close and open the terminal again. Type $PATH command to make sure this directory is now present.
5) You should be able to type "catdcd" in the terminal (without opening vmd) and it should now recognize the command. You should also be able to use catdcd in the tkconsole, but I find it easier to use in the terminal.


text:
Q: How to fix 'File not found' error in debugging with VScode debugger gcc While I was debugging a c code, my Vscode debugger for gcc showed a error like this:
'Unable to open 'test.c': Unable to read file(Error:File not found(C:\mycode\C:\mycode\test.c))'.
So why my file path exists a repetition? And how to fix it?
I had only installed these plugins:
C/C++
C++ Intellisense

A: Change your tasks.json from "args":[ "${file} ] to ${relativeFile},and delete  "cwd" or change it to ${workspaceFolder}.


text:
Q: Are non-invertible elements of a monoid closed under multiplication? Let $M$ be a monoid, and let $x$ and $y$ be non-invertible elements of $M$. Must the product $x*y$ also be non-invertible? I am especially interested in the case where neither $x$ nor $y$ have neither a right nor a left inverse.

A: No. Take $M$ to be the monoid of functions $f : \mathbb{N} \to \mathbb{N}$ under composition, take $y$ to be the function $y(k) = k + 1$, and take $x$ to be the function $x(k) = \text{min}(0, k-1)$. Then $y$ is not surjective and $x$ is not injective but their composition is the identity.
If $xy$ is invertible then $x$ necessarily has a right inverse and $y$ necessarily has a left inverse, so if we assume that either of those inverses doesn't exist then by taking the contrapositive, $xy$ is non-invertible.
However, this is true if $M$ is finite, and this follows from the fact that left inverses and right inverses are inverses in this case.