text:
Q: Use ImageResizer with view precompilation in ASP.NET MVC I'm using the ImageResizer library in my ASP.NET MVC website. I tried to turn on view precompilation to speed up first page load time and the image resizer stopped working. I get the following 404 message when trying to access a resized image:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

In the debug output (shown below) from ImageResizer it says "(Warning): Precompilation is enabled. Image providers may not work as expected."
Is there any way to get them working together?
The troubleshooting guide says a file not found error could be because "You (a) aren't specifying a command string, (b) have Precompilation enabled, and (c) are using an image provider. This is caused by a long-standing bug in the .NET framework." What is a command string? If I specify a command string will it work? If so, how do I do that?
Debug Output:
Image resizer diagnostic sheet      3/2/2017 3:31:20 PM

2 Issues detected:

(Warning):  To potentially see additional errors here, perform an image resize request.

(Warning):  Precompilation is enabled. Image providers may not work as expected.

You are using plugins from the Performance Edition: DiskCache (Performance Edition), AzureReader2Plugin (Performance Edition)

Registered plugins:

ImageResizer.Plugins.Basic.DefaultEncoder
ImageResizer.Plugins.Basic.NoCache
ImageResizer.Plugins.Basic.ClientCache
ImageResizer.Plugins.Basic.Diagnostic
ImageResizer.Plugins.Basic.SizeLimiting
ImageResizer.Plugins.MvcRoutingShim.MvcRoutingShimPlugin
ImageResizer.Plugins.DiskCache.DiskCache
ImageResizer.Plugins.AzureReader2.AzureReader2Plugin

Configuration:

<resizer>
<clientcache minutes="1440" />
<sizelimits imageWidth="0" imageHeight="0" totalWidth="3200" totalHeight="5000" totalBehavior="throwexception" />
<diagnostics enableFor="allhosts" />
<plugins>
<add name="MvcRoutingShim" />
<add name="DiskCache" />
<add name="AzureReader2" connectionString="[redacted]" endpoint="[redacted]" lazyExistenceChceck="True" prefix="~/assets/" />
</plugins>
</resizer>

Accepted querystring keys:

quality, format, thumbnail, maxwidth, maxheight, width, height, w, h, scale, stretch, crop, cropxunits, cropyunits, page, bgcolor, rotate, flip, sourceFlip, sFlip, sRotate, borderWidth, borderColor, paddingWidth, paddingColor, ignoreicc, frame, useresizingpipeline, cache, process, margin, anchor, dpi, mode, zoom,

Accepted file extensions:

bmp, gif, exif, png, tif, tiff, tff, jpg, jpeg, jpe, jif, jfif, jfi,

Environment information:

Running Microsoft-IIS/8.0 on Microsoft Windows NT 6.2.9200.0 and CLR 4.0.30319.42000
Trust level: Unrestricted
OS bitness: x86 !! Warning, running as 32-bit on a 64-bit OS(AMD64). This will limit ram usage !!
Executing assembly: D:\Windows\SysWOW64\inetsrv\w3wp.exe
IntegratedPipeline: True

...
...

A: Pre-compilation breaks all VirtualPathProviders. We've done various mitigations, but you cut off the ImageResizer version number, so I can't really help much there.
If you switch to the Async HttpModule you may have more luck.
Replace type="ImageResizer.InterceptModule"/> with type="ImageResizer.AsyncInterceptModule"/> in Web.config.


text:
Q: TBB parallel_for with less number of threads I have written a multi-view face detection code using opencv face detector. I am running five detectors (trained for different pose angles) over an image and taking their weights to detect faces in an image. I have made the code parallel using TBB parallel_for but it improved the performance by just 1.7-times. I would like to ask if there is any better way to run five detectors in parallel?
I am running my code on a cluster with 16-cores. I think number of threads (that in my case are 5) are too less to utilize the complete power.
Any suggestions?
Thanks,

A: Some possible problems to look into:

*

*One of the detectors takes longer than the other detectors to run.  For example, if one detector takes 4 units of time, and the other four detectors each take 1 unit of time, the most possible speedup is 2x.  Parallelizing the slow detector itself might help in this kind of situation.

*The detectors run so fast that the parallel_for does not have time to spread the work.  If the detectors each take at least 0.1 sec, this should not be a problem.

*Memory bandwidth can be a limiting resource, particularly if working sets do not fit in outer-level cache.

A profiler such as Intel(R) VTune(TM) Amplifier can sometimes help to track down these problems.  Both commercial and non-commercial licenses exist for Amplifier.  [Disclaimer: I work for Intel.]

redpajama_set_name: RedPajamaStackExchange


text:
Q: run chrome's SpeechSynthesis on nodejs Google did great job with chrome's SpeechSynthesis, It's much better then Microsoft's tts (and frankly any other free solution I found).
I wonder, is there any way to use Chrome's SpeechSynthesis over node.js?


text:
Q: Are "relay" delegate protocols bad practice in Objective-C? Let's say I have three custom objects in Objective-C: ClassA: UIViewController <ClassBDelegate> , ClassB: NSObject <ClassCDelegate>, ClassC: NSObject. ClassA is a subclass of UIViewController that will display an activity indicator until a certain network event happens in ClassC. ClassB has a ClassC, among other classes, and is responsible for relaying events from ClassC to ClassA. ClassA has a ClassB, and ClassB has a ClassC, there is no direct connection from ClassA to ClassC.
Now lets say once the particular network event happens in ClassC, that ClassC will fire off  - (void)someAction;. ClassB conforms to the ClassC delegate protocol, and its - (void)classC:(ClassC *)classC didPerformSomeAction; method is called. In turn, ClassB fires off -(void)thisOtherAction;, and since ClassA conforms to the ClassB delegate protocol, its -(void)classB:(ClassB *)classB didPerformThisOtherAction; gets called, which effectively retrieves the network event from ClassC.
My question is, is this bad practice, and if so, is there an easier way to bridge the gap between ClassA and ClassC? I am hesitant to use a NSNotification because I think delegate protocols are more elegant. However, this seems sort of like a relay race to me. I would appreciate any information about popular conventions in a scenario such as this.

A: Don't consider delegate more elegant than notifications, consider only that they apply to different situation:
Delegates - to be used when one item is interested in the result of or provides a service to one other item to which is has a relationship
Notifications - to be used when (potentially) multiple different items are interested in the occurrence of one (or more) events which are posted by other items to which they may or may not have a relationship
This isn't 100% hard and fast. You can create a delegate that can call back to many observers. You can also pass a block between classes to have some other object take responsibility for the delegate callback. But, your situation seems more appropriate to be handled by a notification.

A: It seems that you are describing either mediator pattern or adapter pattern. It is also possible that you have a middle man code smell. It really depends on what you want to achieve.


text:
Q: Can I completely convert an Ubuntu desktop installation to a server one? (not just the packages) I am aware that the server and desktop editions only differ by the packages installed, and I can install server packages (LAMP etc.) into a desktop edition and get the same thing.
However, I want to be able to completely change my desktop installation into a server edition. e.g: when I type uname -a or lsb_release -a it is supposed to say Ubuntu server or something. I currently have an 11.10 desktop installation with LAMP stack installed and the info displayed by apache is "Apache blah blah, on (Ubuntu) server.
Where does apache get this information that I am using an Ubuntu desktop installation and not a server one? Is there a config file(s) to edit?

A: The most clean solution would not be to replace some packages and install a new (LTS) kernel, but to reinstall your box with an Ubuntu server version. As far as I know, there is no other clean way.
Is there a specific reason why do you want to switch?


text:
Q: Not adding calendars and watchman I have to add the library to the project first came to fix it was to erase the cache error, but now says it did not register
Thank you for guiding me.
Here is index.js
import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('talar', () => App);

I've solved this problem now, but the calendar and watchman library does not add what the problem is
http://uupload.ir/files/r7uu_1.jpg

A: Try this:
AppRegistry.registerComponent('test', () => App);

I hope this help

A: Did you init your projet with react-native init newProject for example?
Because if so, you have to match with this name when you do the registerComponent. So it would be
AppRegistry.registerComponent('newProject', () => App);

instead.
EDIT:
According to your screenshot, you should put AppRegistry.registerComponent('talar', () => App);

A: Seems like the project name which u have initiated doesn't appear in the AppRegistry

AppRegistry.registerComponent('newApp', () => App);

If Your project name is same as the name in the registerComponent than check in which project directory your running your app.
Or if that still not working for u than see the node of your project by running

sudo apt lsof -i :(portnumber)8081

. Than kill the Process id(PID)
by running command

kill -9  (PID)

This is because your process might run multiple instances Restart Your project.This might work for you!


text:
Q: How to make a custom progressbar in Android? What would be the best way to make somthing looking like this:

The text on it needs to be customizable, not only numbers, some strings too, depending on context.
From what I see it:

*

*Create a custom View and within onDraw perform all the calculations and text alignment.

*Style or extend a horizontal ProgressBar.

What do you think ?

A: Extend ProgressBar ... override onDraw()
The primary reason for this is that all of the primary methods are already there and the first rule of object-orientated programming is code-reuse means don't reinvent the wheel.


text:
Q: $this->request->param() and $this->request->post() in kohana 3.2 what is the difference between $this->request->param() and $this->request->post() in kohana 3.2?
Somebody explain me briefly.
Thanks

A: Suppose you have URL like this: http://example.com/store/books/computer/martin_fowler
with routing defined as follows:
Route::set('books', '<controller>/<action>(/<product>(/<category>(/<author>)))')
        ->defaults(array(
            'controller' => 'store',
            'action' => '',
        ));

$this->request->param() this will return:
array (
  'product' => 'books',
  'category' => 'computer',
  'author' => 'martin_fowler',
)

$this->request->post() will return $_POST data.
Both methods will return NULL if the key is not found:
$this->request->param('xxx') // NULL
$this->request->param('author') // martin_fowler
$this->request->post('id') // Some id value in $_POST or NULL if id doesn't exist in $_POST

A: In Kohana
$data = $this->request->post();
// get $_POST data

returns post data like submit form.
$this->request->param()

returns posted as well as get data which is send from $_POST and $_GET.

A: The Param gets request parameters assigned to the request after the routing process whereas post get the raw data POSTed.


text:
Q: form onSubmit event doesn't trigger in react This my form component, providing that this a single form of an item-form list the problem is that the form onSubmit is not triggering when submitting the form. The problem happens with all forms of the list. Also, other events like onClick work fine
// State vars
const [inputValue, setInputValue] = useState(value.body);

return (
    <form
        onSubmit={(e) => {
            e.preventDefault();
            // doesn't work!
        }}
        className="flex items-center space-x-3"
    >
        <Controls.TextInput
            inputRef={formInputRef}
            inputChange={(e) => {
                handleUpdate(value.id, e.target.value);
                setInputValue(e.target.value);
            }}
            value={inputValue}
            label={label}
        />

        <button type="submit" className="sr-only"></button>

        <div className="flex">
            {/* button for focus state */}
            <IconButton onClick={handleStartStopListening} color="primary" size="small">
                {listeningIcon}
            </IconButton>

            <IconButton onClick={handleDeleteItem} size="small">
                <TrashIcon className="h-6 cursor-pointer text-red-600 " />
            </IconButton>
        </div>
    </form>
);

}


text:
Q: Why do some angular directives need double curlies and others not? Here are some example AngularJS fragments:
<image ng-href="{{mainCtrl.href}}" xlink:href="" width="383" height="108" />

<div ng-show="mainCtrl.show">

<svg xmlns="http://www.w3.org/2000/svg" baseProfile="full" version="1.1" ng-attr-width="{{mainCtrl.svg.width}}" height="400">

<svg xmlns="http://www.w3.org/2000/svg" baseProfile="full" version="1.1" ng-style="mainCtrl.style">

For some of the AngualrJS attribute directives I need to use double curlies to reference the model data in the controller, while for others I must not use double curlies.
When I encounter a new AngularJS directive how do I know what I should use to point it to the data on the controller? Is there some rationale as to which directives require double curlies and which require their absence?

A: The double curly braces tell angular to interpolate the expression, i.e. create a string. So you wouldn't use them for a directive (or attribute) that doesn't expect a literal string (like ngClick). A literal string means "use the value as is" as opposed to "interpret the value" (=expression).
Whenever you can use curly braces the Angular documentation classifies the parameter as template. By can I mean in addition to or instead of a literal string! So you could write ng-href="http://google.com" or ng-href="{{search}}" with search being 'http://google.com' or ng-href="http://{{search}}" with search being 'google.com'. The result is always the same.
Directives like ng-attr-width and ng-href are just substitutes for their "real" counterparts, width and href. They simply set the value of that attributes in the DOM. For the sake of simplicity they expect a literal string and support templates.


text:
Q: Understanding javascript loop iteration with method inside? Before you all baulk at nesting a method within a loop, this is an example where I truly see no other way. Though, I will entertain other suggestions.
Anyways, I'm using the Dropbox.js SDK for their API. I am looking in a directory for files given based on extension given the following list and path:
FILE_EXTENSIONS = [".py",".js",".cpp",".html",".h"];
PATH = "/Developer";

My code is as follows:
var counts = [];

look_for_files(PATH, FILE_EXTENSIONS);

function look_for_files(directory_path, file_extensions){
    for (var i = 0; i < file_extensions.length; i++){
        current_file = file_extensions[i];

        client.search(PATH, current_file, function(error, count){
            if(error){
                return showError(error);
            }
            console.log(current_file); // Problem is here.
            console.log(count.length);
            counts.push(count.length);
        });
    }
};

Now, when I log the (count.length) I get the following output:
.h
88
.h
607
.h
665
.h
180
.h
410

The numbers are changing, but the current_file is not, even though it's being passed into the method. I have no idea why. This is one of my first experiences programming in javascript (I come from an OOP background), but I am lost. Could someone please help explain?
Thanks

A: Since you are making an asynchronous request, there is a time delay. So, by the time your callback method executes, the for loop has already executed through out, and at this point when you are logging the current_file ( console.log(current_file); ), the index is pointing to the last element in the array.
If you want to log the name of all the files it is processing, move that log statement outside the callback method like this -
function look_for_files(directory_path, file_extensions){
    for (var i = 0; i < file_extensions.length; i++){
        current_file = file_extensions[i];
        console.log(current_file); // This wont be a problem any more

        client.search(PATH, current_file, function(error, count){
            if(error){
                return showError(error);
            }

            console.log(count.length);
            counts.push(count.length);
        });
    }
    };

Now, this should be the result:
// This is when inside the loop
.py
.js
.cpp
.html
.h

// this is the callback
88
607
665
180
410


text:
Q: add correct Bundle order for Intent in Zebra Datawedge app I've developed an android app with a Zebra RS5100 finger scanner. So far the scanner was paired with the device and then I opened the "Datawedge" manually to enable codabar with minimumlength 4 and maximum length 20.
According to the docs
https://techdocs.zebra.com/datawedge/6-9/guide/api/setconfig/
it is possible to set 'decoder_codabar', 'decoder_codabar_length1' and 'decoder_codabar_length2' in a Bundle + Intent.
What is the correct list of bundles with their settings to pass to SendBroadcast ? The following code enables a profile in the datawedge and sets scanner input enabled. But deeper than that there are no examples.
Should I create a new Bundle and add that to the bParams Bundle or add settings to the bParams Bundle itself?
public static Intent Init()
{
    Bundle bMain = new Bundle();

    bMain.PutString("PROFILE_NAME", "SorterApp");
    bMain.PutString("PROFILE_ENABLED", "true");
    bMain.PutString("CONFIG_MODE", "UPDATE");

    Bundle bConfig = new Bundle();
    bConfig.PutString("PLUGIN_NAME", "BARCODE");
    bConfig.PutString("RESET_CONFIG", "false");

    Bundle bParams = new Bundle();
    bParams.PutString("scanner_input_enabled", "true");

    bConfig.PutBundle("PARAM_LIST", bParams);

    bMain.PutBundle("PLUGIN_CONFIG", bConfig);

    // decoder_codabar ??????
    // decoder_i2of5 ????????
    // decoder_codabar_length1 ?????

    Intent dataWedgeIntent = new Intent();
    dataWedgeIntent.SetAction("com.symbol.datawedge.api.ACTION");
    dataWedgeIntent.PutExtra("com.symbol.datawedge.api.SET_CONFIG", bMain);

    return dataWedgeIntent;
}

A: finally figured it out, maybe someone finds a use for it someday.
Just adding
    barCodeProps.PutString("decoder_codabar_enabled", "true");
    barCodeProps.PutString("decoder_codabar_length1", "3");

is not enough.
It only works after adding scanner_selection auto to the bundle.
barCodeProps.PutString("scanner_selection", "auto");

Here is the full function
    public static Intent Init()
    {
        Bundle profileConfig = new Bundle();

        profileConfig.PutString("PROFILE_NAME", "RopsSorterApp");
        profileConfig.PutString("PROFILE_ENABLED", "true");
        profileConfig.PutString("CONFIG_MODE", "OVERWRITE");

        Bundle barCodeConfig = new Bundle();
        barCodeConfig.PutString("PLUGIN_NAME", "BARCODE");
        barCodeConfig.PutString("RESET_CONFIG", "true");

        Bundle barCodeProps = new Bundle();
        barCodeProps.PutString("scanner_selection", "auto");
        barCodeProps.PutString("scanner_input_enabled", "true");

        barCodeProps.PutString("decoder_codabar_enabled", "true");
        barCodeProps.PutString("decoder_codabar_length1", "3");

        barCodeProps.PutString("decoder_i2of5", "true");
        barCodeProps.PutString("decoder_i2of5_length1", "3");

        barCodeConfig.PutBundle("PARAM_LIST", barCodeProps);
        profileConfig.PutBundle("PLUGIN_CONFIG", barCodeConfig);

        Intent dataWedgeIntent = new Intent();
        dataWedgeIntent.SetAction("com.symbol.datawedge.api.ACTION");
        dataWedgeIntent.PutExtra("com.symbol.datawedge.api.SET_CONFIG", profileConfig);

        return dataWedgeIntent;
    }

Then broadcast the intent to the datawedge app.
SendBroadcast(AutoConfig.Init());

Beware that using OVERWRITE reset all other settings
bMain.PutString("CONFIG_MODE", "OVERWRITE");

If you dont want that use UPDATE
bMain.PutString("CONFIG_MODE", "UPDATE");


text:
Q: Uncaught SyntaxError: Unexpected end of input at file I have that error when I run my phonegap Application. I reviewed my code for how many times but I can't see where my error is. After I used JSON.parse(response) that error shown but when I removed that,it executes properly. Can someone help me? Thank you
Here's my code:
function onReconnect(position) {

    Lat = position.coords.latitude;
    Long = position.coords.longitude;
    d = new Date();
    date = d.getUTCDate();
    hour = d.getUTCHours() + 8;
    minutes = d.getUTCMinutes();
    secs = d.getUTCSeconds();
    year = d.getUTCFullYear();
    mon = d.getUTCMonth() + 1;
    day = d.getUTCDay();
    time = year + "-" + mon + "-" + date + " " + hour + ":" + minutes + ":" + secs;

    var sendData3 = {
        "name": stringValue2
    };

    $.post('http://192.168.254.110/webs/main/ajax/TimeTypeCheck.php', sendData3, function (data) {
        $("#info").html(data);
        var TCReturnMessage = data;
        var TCmess = TCReturnMessage.toString().trim();

        var sendData2 = {
            "name": VLmess,
            "Lat": Lat,
            "Long": Long,
            "time": time,
            "Timetype": TCmess
        };
        $.post('http://192.168.254.110/webs/main/ajax/Reconnect.php', sendData2, function (data) {
            $("#info").html(data);
            document.location.href = "TimeOnStatus.html";
        });
    });

}

function onError(error) {
    alert('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

function onSuccess(position) {

    $("#Login").click(function (evt) {

        var currentPage = window.location.href;
        //store it
        window.sessionStorage.setItem("page", currentPage);
        //check if the previous page is the one you wanted.

        stringValue2 = window.localStorage.getItem("data");
        //stringValue2 = stringValue2.trim();
        username = $("#username").val();
        password = $("#password").val();
        d = new Date();
        date = d.getUTCDate();
        hour = d.getUTCHours() + 8;
        minutes = d.getUTCMinutes();
        secs = d.getUTCSeconds();
        year = d.getUTCFullYear();
        mon = d.getUTCMonth() + 1;
        day = d.getUTCDay();
        time = year + "-" + mon + "-" + date + " " + hour + ":" + minutes + ":" + secs;
        sendData = {
            "username": username,
            "password": password,
            "time": time
        };

        $.post('http://192.168.254.110/webs/main/ajax/validateLogin.php', sendData, function (data) {
            $("#info").html(data);
            var VLReturnMessage = data;
            VLmess = VLReturnMessage.toString().trim();

            if (VLmess != "" && VLmess != "Invalid Login!") {
                localStorage.setItem("message", VLReturnMessage);
                window.localStorage.setItem("username", username);
                window.localStorage.setItem("data", data);
                sendData1 = {
                    "name": VLmess
                };

                $.post('http://192.168.254.110/webs/main/ajax/StatusCheck.php', sendData1, function (response) {
                    $("#info").html(response);

                    var SCReturnMessage = JSON.parse(response);
                    if (SCReturnMessage.status == "yes") {
                        navigator.geolocation.getCurrentPosition(onReconnect, onError);

                    } else {
                        alert("hey!");
                        var sendData4 = {
                            "name": VLmess,
                            "time": time
                        };
                        $.post('http://192.168.254.110/webs/main/ajax/AccountStatus.php', sendData4, function (data) {
                            $("#info").html(data);
                        });
                        document.location.href = "trackme.html";

                    }

                });

            } else {}

        });

    });

}

function onError() {
    alert("Error");
}


text:
Q: How to retrieve a value on prompt? I am learning JavaScript, I have to use a prompt and enter a value.

I have to retrieve this value on a field but I don't get this value. My code is incomplete.

My HTML

Exercise 8

   Hours : <input type="text" id='h' />

My JS
var hours = parseInt(prompt('Enter your hours please : '));

objet.addEventListener('load', main);

function main(){

    hours = document.getElementById('h').value = hours;
    alert(hours);
}

var hours = parseInt(prompt('Enter your hours please : '));

objet.addEventListener('load', main);

function main(){

 hours = document.getElementById('h').value = hours;
 alert(hours);
}

  <link rel="stylesheet" type="text/css" href="Main.css">

Exercise 8

   Hours : <input type="text" id='h' />

Thank you...

A: Just check the value entered by the user and insert into the input element.

var hours = parseInt(prompt('Enter your hours please : '));

if (hours != null) {
  document.getElementById("h").value = hours
  alert(hours)
}

Exercise 8

Hours : <input type="text" id='h' />

**UPDATE - Using a function. **
var hours = parseInt(prompt('Enter your hours please : '));

if (hours != null) {
  main();
}

function main(){
    document.getElementById('h').value = hours;
    alert(hours);
}


text:
Q: Data structure for buffering encoded audio in android I have TCP client which received audio (encoded) data through socket. I have to keep received data in some buffer and provide to decoder when requested by decoder chunk by chunk. Data is in byte[] and array size can vary. What should I use as buffer to keep the received byte[] chunks. I know about BlockingQueue but it doesn't provided adding and retrieving N size of byte[].
Does Java provide any data structure for this purpose, can we use ByteBuffer?

A: Does your client know how the byte array size varies?
A well known approach (it needs you manage this also at the server side) is to encapsulate the data inside a packet with the following fields: | TYPE | SIZE | DATA |
so, supposing the client has an open socket connection and instantiate a DataInputStream (dataInputStream = new DataInputStream(socket.getInputStream())), the client can read the data in a thread which run method is something like this:
@Override
public void run() {
    while(running) {

        int pckType = readPacketType();

        int pckSize = readPacketSize();

        byte[] data = readPacketContent(pckSize);

        // do something with data
        // you can use Semaphore instances in order to maintains a set of permits if needed
    }
}

where
private int readPacketType() {
    int result = -1;
    byte[] array = new byte[1];
    try {
        dataInputStream.read(array);
        result = (int)array[0];
    } catch (IOException ex) {
        return -1;
    }
    return result;
}

private int readPacketSize() {
    int result = -1;
    byte[] array = new byte[4];
    try {
        dataInputStream.read(array);
        result = ByteBuffer.wrap(array).getInt();
    } catch (IOException ex) {
        return -1;
    }
    return result;
}

private byte[] readPacketContent(int contentSize) {
    byte[] result = new byte[contentSize];
    try {
        dataInputStream.read(result);
    } catch (IOException ex) {}
    return result;
}

noting that I assigned, for example, 1 byte for the TYPE field and 4 byte for the SIZE field
EDIT:
You can use an implementation of the BlockingQueue interface like LinkedBlockingQueue. You can put byte[] of different size and retrieve them coherently (keeping the order and the size). Follows an easy check ;)
LinkedBlockingQueue<byte[]> lbq = new LinkedBlockingQueue<byte[]>();
String str1 = "blablabla";
String str2 = "blabla";
try {
    lbq.put(str1.getBytes());
    lbq.put(str2.getBytes());
    lbq.put(str1.getBytes());
} catch (InterruptedException e) {
    e.printStackTrace();
}
byte[] b = null;
int size = lbq.size();
for(int i=0; i<size; i++) {
    try {
        b = lbq.take();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(b.length);
}


text:
Q: PHP Array insert into MySQL table as individual rows I am trying to insert multiple rows in a MySQL table from PHP arrays. I managed with with help of other members to get set of values in a pair of brackets but when i try to insert this i get "Error: Column count doesn't match value count at row 1" I donot know where am i going wrong. my codes are as below: (The number of values i get vary according to user input)
    $docno1=array();
    $serialno = array();
    $acc_name = array();
    $debit = array();
    $credit = array();

    for ($i=1;$i<=$rowcount;$i++)
    {
    //echo 'Accountname'.$i.' :'.($_GET['accname'.$i]).'
';
    $docno1 [] = ($_GET['docno']);
    array_unshift($docno1,"");
    unset($docno1[0]);

    $serialno [] = $i;
    array_unshift($serialno,"");
    unset($serialno[0]);

    $acc_name[] = ($_GET['accname'.$i]);
    array_unshift($acc_name,"");
    unset($acc_name[0]);

    $debit[] = ($_GET['DrAmount'.$i]);
    array_unshift($debit,"");
    unset($debit[0]);

    $credit[] = ($_GET['CrAmount'.$i]);
    array_unshift($credit,"");
    unset($credit[0]);

    }

    $sum_dr = array_sum ($debit);
    $sum_cr = array_sum ($credit);

    echo ' values of $multi
';
    $multi = array(
    ($docno1),
    ($serialno), //Array for a row of fields
    ($acc_name),
    ($debit),
    ($credit),
    ($docno1)

    );

    print_r($multi);

    $new = array();
    foreach($multi as $key=>$value) {
    $new[] = "'".implode("','", $value)."'";

    }
    echo '
Values of $new
';
    print_r($new);

    $query = "(".implode("), (",$new).")";
    echo $query.'
';

    mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());

    echo "Inserted successfully";
    die;

The results i get are :
      values of $multi
      Array
      (
      [0] => Array
      (
      [1] => 3434
      [2] => 3434
      )

      [1] => Array
      (
      [1] => 1
      [2] => 2
      )

      [2] => Array
      (
      [1] => Lemon
      [2] => Kidney Beans
      )

      [3] => Array
      (
      [1] => 20
      [2] => 10
      )

      [4] => Array
      (
      [1] => 0
      [2] => 0
      )

      [5] => Array
      (
      [1] => 3434
      [2] => 3434
      )

      )

      Values of $new
      Array
      (
      [0] => '3434','3434'
      [1] => '1','2'
      [2] => 'Lemon','Kidney Beans'
      [3] => '20','10'
      [4] => '0','0'
      [5] => '3434','3434'
      )
      ('3434','3434'), ('1','2'), ('Lemon','Kidney Beans'), ('20','10'), ('0','0'), ('3434','3434')
      Error: Column count doesn't match value count at row 1

A:  mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());

You are trying to insert something into 6 fields, so that $query string must have 6 values in it, or you get this error.
You have a lot of $query's that are 2 values. And that's not 6

A: If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the specific inserts -- for which you didn't specify a value.

A: It looks to me as if you are mapping your array the wrong way round. You're trying to add two records with six fields each, but what you're actually putting into the SQL statement are six records with two fields each.
This is why MySQL is complaining -- because you've told it you want to update six fields, but in each of the records you've given it, you've only specified two fields.
You need to build your array differently.
I assume that $docno1, $serialno, $acc_name, $debit and $credit will always all have the same number of array elements (it appears from your code that you are assuming this, so I'll follow you in your assumption).
In that case, you need to build your array something like this:
$multi = array();
foreach($docno1 as $key=>value) {
    $multi[] = array(
        $docno1[$key],
        $serialno[$key], //Array for a row of fields
        $acc_name[$key],
        $debit[$key],
        $credit[$key],
        $docno1[$key])
}

Replace the block in your code where you set $multi with this, and your program should work.
Look at what print_r($multi) looks like now, and you'll see the difference.
(note, there are more efficient ways of writing your whole program than this, but I've focused on giving you a drop-in replacement for this specific bit, to help show you where you were going wrong, rather than simply rewriting the whole program for you)
Hope this helps.


text:
Q: Hyperref option clash error because unknown package requires/loads it too I am currently hunting for errors in my template and these two I cannot solve after reading the log and researching:
! LaTeX Error: Option clash for package hyperref.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.7

The package hyperref has already been loaded with options:
  []

I already ruled out

*

*Bibliography-styles requiring it

*Package not loaded last

*Putting global hyperref options in Documentclass options (even more errors)

My current knowledge is that some package/configuration file loads/requires hyperref. Therefore I looked at the log-file. But as a beginner I cannot decipher (a) which package causes the problem and (b) how I can solve/bypass it.
Minimal example:
\documentclass[a4paper, 12pt, oneside]{book}

\usepackage{bookmark}
\usepackage[
    ocgcolorlinks=false, %sample
]{hyperref}

\hypersetup{
    urlcolor=red, %sample
}

\makeatletter
    \if@twoside
        \hypersetup{pdfpagelayout=TwoPageLeft, linkcolor=red}
        \fi
\makeatother

\begin{document}

This is a test.

\end{document}

A: Loading bookmark after hyperref solves the error.
See Bookmark-Documentation on page 7.


text:
Q: check if jstl variable is empty by set and out hey i wann check if jstl variable is empty by set and out.
created a variable using set:
<c:set var="prevValue" value="" />

i did the following to check if the jstl variable is empty by using the out method:
<c:when test="<c:out value='${empty prevValue}' />" />
empty
</c:when>
<c:otherwise>
not empty
</c:otherwise>

but i am receiving not empty. why is this so?? i did set prevValue to empty string so techinically this is correct right?

A: The code puts a string literal in the test attribute of the c:when tag, which expects a boolean.  Simplify the test expression to only check that prevValue is empty, the code should not include the <c:out ... segment in the test.  Use:
<c:when test="${empty prevValue}" />

Also if you want to continue using <c:when> the conditions must be wrapped in <c:choose>
A full example:
<c:choose>
    <c:when test="${empty prevValue}" />
        empty
    </c:when>
    <c:otherwise>
        not empty
    </c:otherwise>
</c:choose>

A: Already you have one valid answer,
But why not simply ?
<c:if test="${not empty prevValue}">

//not empty

</c:if>


text:
Q: Extract specific string from URL I want to extract some string from this url
https://s3-ap-southeast-1.amazonaws.com/mtpdm/2019-06-14/12-14/1001_1203_20190614120605_5dd404.jpg
I want to extract the 2019-06-14, how do I do that using java?

A: Use Regular Expression to achieve this to get the Date 2019-06-14,
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractDateFromURL {

     public static void main(String []args) {
        String URL = "https://s3-ap-southeast-1.amazonaws.com/mtpdm/2019-06-14/12-14/1001_1203_20190614120605_5dd404.jpg";

        Pattern pattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{1,2})");
        Matcher matcher = pattern.matcher(URL);

        if (matcher.find()) {
            System.out.println(matcher.group(1)); // Do what you need to do with the result
        }
     }
}

Output

2019-06-14

And to get the 12-14 you can use the following Regular Expression,
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractDateFromURL {

     public static void main(String []args){
        String URL = "https://s3-ap-southeast-1.amazonaws.com/mtpdm/2019-06-14/12-14/1001_1203_20190614120605_5dd404.jpg";

        Pattern pattern = Pattern.compile("/(\\d{1,2}-\\d{1,2}-\\d{4}|\\d{1,2}-\\d{1,2})");
        Matcher matcher = pattern.matcher(URL);

        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
     }
}

Output

12-14


text:
Q: Modifying the Introduction on the Web API help page I've enhanced an older SOAP style web service with REST endpoints.  Most everything is working correctly, but I haven't been able to figure out how to change the Introduction on for the auto generated help files.  What I have right now is showing the introduction as "Provide a general description of your APIs here."
I've followed this Similar question, but doesn't explain where to change Introduction and have everything else documented, but still don't know where to change the introduction.
I should be using version 2 of Web-API.

A: In Visual Studio's Solution Explorer window go to: YourProject -> Areas folder -> HelpPage -> Views -> Help -> index.cshtml and you will see the text you want to modify.
Alternatively you could just do a find all (Ctrl+Shift+F) for the text you are looking for Provide a general description of your APIs here.
Once you've modified it, save the index.cshtml and refresh the page in your browser. Should be good to go.


text:
Q: Excel to PostgreSQL using Python I'm new to Python and I'm trying to export excel directly into postgreSQL without CSV files.
I don't know if it's possible.
I keep running into the error 'column "daily_date" is of type date but expression is of type numeric'.
import psycopg2
import xlrd

book = xlrd.open_workbook("pytest.xlsx")
sheet = book.sheet_by_name("Source")

database = psycopg2.connect (database = "RunP", user="postgres", password="", host="localhost", port="5432")

cursor = database.cursor()

query = """INSERT INTO orders (Daily_Date, Days, First, Second, Leader) VALUES (%s, %s, %s, %s, %s)"""

for r in range(1, sheet.nrows):
    Daily_Date = sheet.cell(r,0).value
    Days = sheet.cell(r,1).value
    First = sheet.cell(r,2).value
    Second = sheet.cell(r,3).value
    Leader = sheet.cell(r,4).value

    values = (Daily_Date, Days, First, Second, Leader)

    cursor.execute(query, values)

cursor.close()

database.commit()

database.close()

print ""
print ""
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print "I just imported Excel into postgreSQL"

A: Excel stores datetimes as numbers. You can use xlrd.xldate.xldate_as_datetime to convert:
    Daily_Date = xlrd.xldate.xldate_as_datetime(sheet.cell(r,0).value,book.datemode)


text:
Q: HttpURLConnection error I want to get the HTML from a website, for that I'm using this code.
When I try to add this code from the documentation I get this error:
            //Get HTML
            URL url = new URL("http://www.android.com/");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                readStream(in);
                finally {
                    urlConnection.disconnect();
                }
            }

What went wrong? Did I forget to import some stuff?

A: You didn't forget to import anything.
There's a couple things wrong with the code.
1) You're missing the catch block to go along with try and your finally statement is incorrectly inside the if. It should look like the follow:
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} catch (Exception e) { // best practice is to be more specific with the Exception type
    urlConnection.disconnect();
    Log.w("Login", "Error downloading HTML from " + url);
} finally {
    if(urlConnection != null) {
                urlConnection.disconnect();
    }
}

2) In that example you are following in the documentation, they are leaving it up to you to decide what to do with the stream once it it retrieved from the urlConnection.
So create your own void readStream(InputStream in) method in your activity which can then consume the InputStream. Write it to disk, display it on screen, its up to you.

A: You are missing the catch clause. Put this before your finally clause as such:
} catch (Exception e) { //it's bad practice to catch Exception, specify it more if you can, i just don't know what errors InputStream throws
    Log.e("ClassTag", e.getMessage(), e);
} finally { /* ... */ }

A: The finally block does not go inside the try block, change it to:
 try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
 }
 finally {
    urlConnection.disconnect();
}

Also make sure that you have imported java.net.URL.


text:
Q: Fatal error with Symfony 2.5.0 I have installed symfony2 through composer :
composer create-project symfony/framework-standard-edition usr/share/nginx/www/symfony/

Everything ges smooth until I try to visit the main page I have this error :
Interface 'Symfony\Component\Config\Resource\ResourceInterface' not found

Also the doc don't talk about 2.5.0 , latest doc was about 2.3.0 and the Symfony 3 directory ? I just say no


text:
Q: Why does an arrow make a duplicate component in a PlantUML diagram? I'm very new to PlantUML, so this is likely something basic.
Sometimes when I add a arrow from one rectangle to another, the original component is not linked.  Instead, a new component is created and linked.  What am I doing wrong?
In my example, I have this fairly simple diagram:
@startuml
database "DB" {
  frame Rules {
    rectangle "Item 1"
    rectangle "Item 2"
  }
}

rectangle "App Server" {
  rectangle "My UI"
}

rectangle "System" {
  rectangle "Foo"
}

[My UI] --> [Item 1] : create and edit
[System] --> [Item 1] : extract
@enduml

And this is generated:

Note that the arrow from System to Item 1 is for a new component and not the existing "System" element.
What am I doing wrong?

A: I asked the same question in the PlantUML forum, and was told that this is due to the brackets around the name System in the arrows.  I guess they can only be used if the name contains a space.
So replacing
[System] --> [Item 1] : extract

with
System --> [Item 1] : extract

fixes the issue, and creates this diagram:


text:
Q: Not able to return error to calling function inside Typescript Hi i am trying to get the error return code to my calling function inside ionic, but I am not able to return the error from the function called.
Here is my main page where the function is called:
let result:any = await this.authService.SignUp(
        this.registerForm.value["name"],
        this.registerForm.value["phone"],
        this.registerForm.value["email"],
        this.registerForm.value["password"],
        this.attorneyId
      );
      if (result && result.code) {
        console.log('Register Page Error', result.code); //NOT GETTING RESULT HERE
        this.alertService.showErrorMessage(result.code);

      }

here is my function which is called from above:
async SignUp(
    fullName: string,
    phone: number,
    email: string,
    password: string,
    attid: number
  ) {
    console.log("Inside Auth SignUp");
    this.afDatabase.list("/attorneyList", ref =>
        ref.orderByChild("attid").equalTo(attid)
      ).valueChanges().subscribe(async data => {
        console.log("Inside Data")
        if (data[0]) {
          return await this.afAuth
            .createUserWithEmailAndPassword(email, password)
            .then(async result => {
              console.log("Signup Result", result)
              result.user["fullName"] = fullName;
              result.user["phone"] = phone;
              result.user["attid"] = attid;
              await this.SetUserData(result.user);
              this.navCtrl.navigateRoot(["/tabs"]);
            })
            .catch(error => {
              console.log("Signup Error", error); //GETTING ERROR HERE
              return error; //THIS IS NOT RETURNING THE ERROR BACK TO THE ABOVE CALLING FUNCTION
            });
        }
      });

  }

Any idea what am I doing wrong here??? Please help.

A: The return inside your subscribe call on the firestore query does not actually return that data from the function. you could, however, convert your query into a promise by calling .valueChanges().pipe(first()).toPromise() and await the result of that query. then the code, that is currently inside your subscribe call should work as expected.
async SignUp(
    fullName: string,
    phone: number,
    email: string,
    password: string,
    attid: number
  ) {
    console.log("Inside Auth SignUp");
    const data = await this.afDatabase.list("/attorneyList", ref =>
        ref.orderByChild("attid").equalTo(attid)
      ).valueChanges().pipe(first()).toPromise();
        console.log("Inside Data")
        if (data[0]) {
          return await this.afAuth
            .createUserWithEmailAndPassword(email, password)
            .then(async result => {
              console.log("Signup Result", result)
              result.user["fullName"] = fullName;
              result.user["phone"] = phone;
              result.user["attid"] = attid;
              await this.SetUserData(result.user);
              this.navCtrl.navigateRoot(["/tabs"]);
            })
            .catch(error => {
              console.log("Signup Error", error); //GETTING ERROR HERE
              return error; //THIS IS NOT RETURNING THE ERROR BACK TO THE ABOVE CALLING FUNCTION
            });
        }
  }

That code should demonstrate my solution


text:
Q: Using git: committed changes in one branch affect 'master' I have an issue with git which I feel may relate to permissions.  The situation is as follows: I have two branches, 'master' and 'theming'.  The file in question is called 'settings.php', and it has the permissions r--rw-rw-, and the owner listed is my own username.  I am using Ubuntu 10.4LTS.
I produce the issue in the following manner:

*

*Checkout the theming branch

*Make change to settings.php

*Add and commit the change to 'theming'

*Checkout 'master' branch by using: $ git checkout master

After the preceding steps, I get the error 'unable to unlink settings.php', and I note that the file has also been changed in master.  This also happens if I do it the other way around, ie. I change it in master, commit the change, and checkout theming.  It then does not let me change back to the previous branch, as there are changes to be committed.
The only way I know of to avoid running into this issue is using $ sudo checkout [branchname].  This temporarily avoids the issue, but if I ever use checkout without sudo, I run into the same thing again and I have to worry about undoing all of the changes in my current branch.
Does anyone know how to solve this?  I've looked around and I find issues relating to unlinking, but none like mine.

A: You shouldn't be checking it out as root in the first place.  Try changing the repository permissions back to you:
# chown -R yourname ~/path/to/your/gitrepo

If you need to use a shared repository, check out the 'git init' manual for the --shared flag.  Or there are lots of google hits for group settings that let you properly share a repo, but it is git version dependent so I won't recount it all here.  The setting you're probably looking for, if so, is this one:
[core]
sharedrepository = 0660

(and then chgrp -R the directory and chmod g+s on the directory as well)

A: Why is the file in question read-only for owner? Git is not allowed to rewrite the contents or replace it when you switch branches.

A: This is Daniel M with a new name.  First off, the file permissions were actually rw-rw-r--.  Second, the comment by igorw was perfectly helpful.  I did not have write permissions on the parent directory.  As soon as I added this, my problem disappeared.


text:
Q: Need to send an email to customers in a journey with specified intervals of time in marketing cloud Need to send an email to customers in a journey with specified intervals of time in marketing cloud.
Here if a journey is activated and emails are triggered and it has a wait time of 15 days for the second email between these gaps we had updated my data extension then the second email should be triggered according to the updated data extension
I was wondering whether this is possible?

A: Not in the current release (208). Lookout for the 209 - 210 releases as they might introduce something that would help.

A: This can be done if decision split is configured on Contact Data rather than Journey Data. Every time a decision split is configured, after waiting at the wait activity, the value of the required attribute for that contact is picked up from the updated Data Extension.


text:
Q: Are there any downsides to using "using" for all non-primitive objects? I'm sure there are answers out there ... but googling on "C# using" is a bit more complicated than you may expect.
At any rate ... just really started learning about this handy technique the other day and it seems like I would be foolish to not use it for any non-primitive objects I have in my code.
Is that a fairly accurate statement or are there some downsides (outside of the slightly more cluttered code) to using "using" for almost everything?

A: It's not clear what you mean - if you mean using statements such as:
using (SomeType x = new SomeType())
{
}

Then that's only applicable to IDisposable implementations.
If you mean using directives like this:
using System.IO;

then yes, I usually have a directive for every namespace containing a type I wish to use within a particular source file.

A: As others have mentioned, you can only use a using statement on types that implement IDisposable. For types that do implement IDisposable, the only real downside I have seen is due to the fact that using calls the type's Dispose() method implicitly, so if an exception is thrown in that call, it is sometimes difficult to catch.
Otherwise, I would recommend using for types that implement IDisposable instead of utilizing try-catch-finally as it makes code more compact and clean.
Edit: found a good msdn article explaining this and other pitfalls.


text:
Q: Is there a way to flush html to the wire in Sinatra I have a Sinatra app with a long running process (a web scraper). I'd like the app flush the results of the crawler's progress as the crawler is running instead of at the end.
I've considered forking the request and doing something fancy with ajax but this is a really basic one-pager app that really just needs to output a log to a browser as it's happening. Any suggestions?

A: Update (2012-03-21)
As of Sinatra 1.3.0, you can use the new streaming API:
get '/' do
  stream do |out|
    out << "foo\n"
    sleep 10
    out << "bar\n"
  end
end

Old Answer
Unfortunately you don't have a stream you can simply flush to (that would not work with Rack middleware). The result returned from a route block can simply respond to each. The Rack handler will then call each with a block and in that block flush the given part of the body to the client.
All rack responses have to always respond to each and always hand strings to the given block. Sinatra takes care of this for you, if you just return a string.
A simple streaming example would be:
require 'sinatra'

get '/' do
  result = ["this", " takes", " some", " time"]
  class << result
    def each
      super do |str|
        yield str
        sleep 0.3
      end
    end
  end
  result
end

Now you could simply place all your crawling in the each method:
require 'sinatra'

class Crawler
  def initialize(url)
    @url = url
  end

  def each
    yield "opening url\n"
    result = open @url
    yield "seaching for foo\n"
    if result.include? "foo"
      yield "found it\n"
    else
      yield "not there, sorry\n"
    end
  end
end

get '/' do
  Crawler.new 'http://mysite'
end


text:
Q: google drive api, export google slide as power point (ppt or pptx) - node.js I want to use the google apis to download a google slide as a power point presentation (ppt or pptx) to our node.js server. I have setup google drive api, and I have created a slide in my drive folder. I'm trying to use drive.files.export to download the slide, but since a slide isn't really a thing on windows or mac, I am trying to convert it to power point by setting the mimeType to application/vnd.ms-powerpoint:
  const { drive } = await Google.getInstance();
  const fileId = 'SomeLongTemplateId';
  const fileName = 'test slide processing';
  console.log('exporting ppt');
  const ppt = await drive.files.export(  // report.js:343
    { fileId, mimeType: 'application/vnd.ms-powerpoint' },
    { responseType: 'arraybuffer' }
  );
  return Buffer.from(ppt.data);

However, this throws and error and doesn't seem to work:
error: {
    message: ArrayBuffer {
      [Uint8Contents]: <7b 0a 20 22 65 72 72 6f 72 22 3a 20 7b 0a 20 20 22 65 72 72 6f 72 73 22 3a 20 5b 0a 20 20 20 7b 0a 20 20 20 20 22 64 6f 6d 61 69 6e 22 3a 20 22 67 6c 6f 62 61 6c 22 2c 0a 20 20 20 20 22 72 65 61 73 6f 6e 22 3a 20 22 62 61 64 52 65 71 75 65 73 74 22 2c 0a 20 20 20 20
22 6d 65 73 73 61 67 65 22 3a 20 ... 195 more bytes>,
      byteLength: 295
    },
    stack: 'Error: [object ArrayBuffer]\n' +
      '    at Gaxios._request (C:\\Users\\rasmu\\Documents\\triggerz\\triggerz\\node_modules\\gaxios\\build\\src\\gaxios.js:129:23)\n' +
      '    at processTicksAndRejections (internal/process/task_queues.js:95:5)\n' +
      '    at async JWT.requestAsync (C:\\Users\\rasmu\\Documents\\triggerz\\triggerz\\node_modules\\google-auth-library\\build\\src\\auth\\oauth2client.js:345:18)\n' +
      '    at async processionSlide (C:\\Users\\rasmu\\Documents\\triggerz\\triggerz\\entity-access\\src\\act\\report.js:343:15)'
  },

Unfortunately, it doesn't really say what the problem is, but it definitely doesn't work. I have also tried exporting as pptx using the mimeType application/vnd.openxmlformats-officedocument.presentationml.presentation but this gave a similar error.
I am used to export pdf's using this technique, and it works like a charm, the only difference is that I export a doc (google docs) and use the mimeType application/pdf
In the web UI of google drive, I can right-click on the slide and choose "download" this, downloads a pptx file that I can open with both MS power point and Libre office. - so it would surprise me a lot is the google node.js api library can't export in the same manner.
Any ideas how I can export a slide as a presentation that works on windows/mac ?

A: You can try replacing you responseType to stream as recommended in this reference: google api nodejs client [Help] Google Drive export example not working
const ppt = await drive.files.export(  // report.js:343
    { fileId, mimeType: 'application/vnd.ms-powerpoint' },
    { responseType: 'stream' }
  )

One workaround that I could suggest if the solution above still fails is to use Drive.Files.Get, Get the file resource you your Google Slide file using its file id. Then get the exportLinks of your preferred mimeType.
Sample (API explorer):

Response:
{
 "name": "Untitled presentation",
 "exportLinks": {
  "application/vnd.oasis.opendocument.presentation": "https://docs.google.com/feeds/download/presentations/Export?id=13vwP4xQ_nVAHCPCuXI3GQKhMJrQ5goTfX7mh6qP5fKM&exportFormat=odp&resourcekey=0-nwpcI7sa0wRmreOT5Z6RJg",
  "application/pdf": "https://docs.google.com/feeds/download/presentations/Export?id=13vwP4xQ_nVAHCPCuXI3GQKhMJrQ5goTfX7mh6qP5fKM&exportFormat=pdf&resourcekey=0-nwpcI7sa0wRmreOT5Z6RJg",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": "https://docs.google.com/feeds/download/presentations/Export?id=13vwP4xQ_nVAHCPCuXI3GQKhMJrQ5goTfX7mh6qP5fKM&exportFormat=pptx&resourcekey=0-nwpcI7sa0wRmreOT5Z6RJg",
  "text/plain": "https://docs.google.com/feeds/download/presentations/Export?id=13vwP4xQ_nVAHCPCuXI3GQKhMJrQ5goTfX7mh6qP5fKM&exportFormat=txt&resourcekey=0-nwpcI7sa0wRmreOT5Z6RJg"
 }
}

*

*Access the export link using application/vnd.openxmlformats-officedocument.presentationml.presentation as key. Download the file using the link.

A: Issue and workaround:
Unfortunately, it seems that in the current stage, when I saw the exportFormats with "About: get" of Drive API, the mimeType of application/vnd.google-apps.presentation (Google Slides) can be exported to the following mimeTypes.
"application/vnd.google-apps.presentation": [
  "application/vnd.oasis.opendocument.presentation",
  "application/pdf",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "text/plain"
],

By this, it seems that when the export method is used, Google Slides cannot be exported as application/vnd.ms-powerpoint. By this, when I tested this, the error occurs. But from above exportFormats, it is found that when the mimeType of application/vnd.openxmlformats-officedocument.presentationml.presentation is used, the Google Slides can be exported as PPTX.
But from your question, you say as follows.

Unfortunately, it doesn't really say what the problem is, but it definitely doesn't work. I have also tried exporting as pptx using the mimeType application/vnd.openxmlformats-officedocument.presentationml.presentation but this gave a similar error.

When I tested your script using the mimeType of application/vnd.openxmlformats-officedocument.presentationml.presentation, no error occurs. So please modify your script as follows and test it again.
Modified script:
const fileId = 'SomeLongTemplateId';
const fileName = "test slide processing";
console.log("exporting ppt");
const ppt = await drive.files.export(
  {
    fileId: fileId,
    mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  },
  { responseType: "arraybuffer" }
);
fs.writeFile("sample.pptx", Buffer.from(ppt.data), (err) => {
  if (err) console.log(err);
});

// return Buffer.from(ppt.data);

*

*When I tested this modified script, I could confirm that the file of sample.pptx can be created and the file can be opened as PPTX file.

Reference:

*

*About: get


text:
Q: Manual triggering of ajaxLoader in Tabulator 3.5 I am using the tabulator version 3.5 of http://tabulator.info/. I fill the table with an ajax request. During the loading time the "loading icon" is shown. Before the ajax request for tabulator is executed I am running some check operations. During these checks I want to show the loading icon of tabulator already. Thus, is there a way of triggering on/off the loading icon manually via javascript?

A: In 3.5 the only way to do it would be to trigger the ajax request yourself using the setData function to trigger the load, allowing you to do what every you want before you call it.
In version 4.0 onwards you can use the ajaxRequestFunc property to override the default ajax loading function and return a promise, so you could put your logic in there and resolve the promise when you are ready:
var table = new Tabulator("#example-table", {
    ajaxRequestFunc:function(url, config, params){
        return new Promise(function(resolve, reject){
            //do your pre loading logic here

            var promise = table.modules.ajax.defaultLoaderPromise.call(table.modules.ajax, url, config, params)
            .then(function(data){
                resolve(data);
            })
            .error(function(err){
                reject(err);
            })
        }
    },
});


text:
Q: How to get a batch file open a website in default browser? I am fairly new to programming and as a bit of a fun thing I am building a vb.net console app to allow people in the band that I'm in to have easy access to all the relevant websites, e.g. Facebook, Twitter, the band website, etc.
So I have given up on getting vb.net to open the website and instead have learned how to make it run a batch file, but I just need to know what I need to put in it to open a website in the users default browser.
I have already tried:
start "" http://www.bandimin.co.uk

The vb.net code to run the batch file is:
If Console.ReadLine() = "1" Then
    Console.WriteLine("opening please wait...")
    Dim batfile1 As String batfile1 = "C:\Users\henry\source\repos\band console\band console\TextFile1.bat"
    Process.Start(batfile1)

But that is not working.

A: Just use Process.Start()
Sub Main()
    Process.Start("http:\\www.microsoft.com")
    Console.ReadLine()
End Sub

I cannot get the link in your question to work. Try it in your browser to see if it works.

A: You can make an temporary url file and then running it:
@echo off
echo [InternetShortcut] >> temp.url
echo URL=%url% >> temp.url
start temp.url
del temp.url


text:
Q: How to perform proper error handling with asyncio and aiohttp? I am looking for guidance around best practices with asyncio and aiohttp in Python 3. I have a basic scraper but I am not sure how to:

*

*Properly implement error handling. More specific around my fetch function.

*Do I really need the last main function to wrap my async crawler around?

Here is my code so far, it is working but I would like feedback on the two item above.
urls = []
async def fetch(url, payload={}):
    async with ClientSession() as s:
        async with s.get(url, params=payload) as resp:
            content = await resp.read()
            return content

async def get_profile_urls(url, payload):
    content = await fetch(url, payload)
    soup = BeautifulSoup(content, 'html.parser')
    soup = soup.find_all(attrs={'class': 'classname'})
    if soup:
        urls.extend([s.find('a')['href'] for s in soup])

async def main():
    tasks = []
    payload = {
        'page': 0,
        'filter': 88}
    for i in range(max_page + 1):
        payload['page'] += 1
        tasks.append(get_profile_urls(search_ulr, payload))
    await asyncio.wait(tasks)

asyncio.run(main())


text:
Q: How to render clipped surfaces as if they were a solid I'm new to threejs and I have some 3d objects that are spatially close or have containment relationships. I use them to represent geological bodies. When I use clipping, they are hollow and I want the effect to be solid. I have tried the following two options.

*

*The scheme of webgl_clipping_stencil example (https://threejs.org/examples/#webgl_clipping_stencil)

The problem with this scheme is that only one color can be set for the profile. What I want is that each profile has its own color, which is the same as the color of the 3d object surface.

*How to render clipped surfaces as solid objects The scheme in this link.

The problem with this scheme is that if the 3d object are spatially adjacent or there are  containment relationship, the effect will not work. For example:
enter image description here
Is there any other solution to achieve this effect? Thank you very much!


text:
Q: Create clean text (without \n ) and add the language : HTTPError: HTTP Error 403: Forbidden Python I am currently working on som Natural Language Processing in Python. The goal here is to get some pdf into text then do some text cleaning.
As the title is trying to tell I'm trying to do some text cleaning, I use TextBlob and here below is my def:
Additional info previsous to this cell I Used PDFMiner: PDF to Text.

def get_language(row):
    b = TextBlob(row['clean_text'])
    return b.detect_language()

df_cvs['clean_text'] = df_cvs['text'].str.replace('\n', ' ')
df_cvs.loc[:, 'language'] = df_cvs.apply(lambda row: get_language(row), axis=1)

df_cvs.head(2)```

Now the error is the following:

Error details below: **HTTPError: HTTP Error 403: Forbidden**
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
<ipython-input-71-f02d06c663d3> in <module>
      6
      7 df_cvs['clean_text'] = df_cvs['text'].str.replace('\n', ' ')
----> 8 df_cvs.loc[:, 'language'] = df_cvs.apply(lambda row: get_language(row), axis=1)
      9
     10 df_cvs.head(2)

~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   7546             kwds=kwds,
   7547         )
-> 7548         return op.get_result()
   7549
   7550     def applymap(self, func) -> "DataFrame":

~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    178             return self.apply_raw()
    179
--> 180         return self.apply_standard()
    181
    182     def apply_empty_result(self):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    269
    270     def apply_standard(self):
--> 271         results, res_index = self.apply_series_generator()
    272
    273         # wrap results

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
    298                 for i, v in enumerate(series_gen):
    299                     # ignore SettingWithCopy here in case the user mutates
--> 300                     results[i] = self.f(v)
    301                     if isinstance(results[i], ABCSeries):
    302                         # If we have a view on v, we need to make a copy because

<ipython-input-71-f02d06c663d3> in <lambda>(row)
      6
      7 df_cvs['clean_text'] = df_cvs['text'].str.replace('\n', ' ')
----> 8 df_cvs.loc[:, 'language'] = df_cvs.apply(lambda row: get_language(row), axis=1)
      9
     10 df_cvs.head(2)

<ipython-input-71-f02d06c663d3> in get_language(row)
      3 def get_language(row):
      4     b = TextBlob(row['clean_text'])
----> 5     return b.detect_language()
      6
      7 df_cvs['clean_text'] = df_cvs['text'].str.replace('\n', ' ')

~\Anaconda3\lib\site-packages\textblob\blob.py in detect_language(self)
    566         :rtype: str
    567         """
--> 568         return self.translator.detect(self.raw)
    569
    570     def correct(self):

~\Anaconda3\lib\site-packages\textblob\translate.py in detect(self, source, host, type_)
     70         data = {"q": source}
     71         url = u'{url}&sl=auto&tk={tk}'.format(url=self.url, tk=_calculate_tk(source))
---> 72         response = self._request(url, host=host, type_=type_, data=data)
     73         result, language = json.loads(response)
     74         return language

~\Anaconda3\lib\site-packages\textblob\translate.py in _request(self, url, host, type_, data)
     90         if host or type_:
     91             req.set_proxy(host=host, type=type_)
---> 92         resp = request.urlopen(req)
     93         content = resp.read()
     94         return content.decode('utf-8')

~\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223
    224 def install_opener(opener):

~\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    529         for processor in self.process_response.get(protocol, []):
    530             meth = getattr(processor, meth_name)
--> 531             response = meth(req, response)
    532
    533         return response

~\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
    638         # request was successfully received, understood, and accepted.
    639         if not (200 <= code < 300):
--> 640             response = self.parent.error(
    641                 'http', request, response, code, msg, hdrs)
    642

~\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
    567         if http_err:
    568             args = (dict, 'default', 'http_error_default') + orig_args
--> 569             return self._call_chain(*args)
    570
    571 # XXX probably also want an abstract factory that knows when it makes

~\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
    500         for handler in handlers:
    501             func = getattr(handler, meth_name)
--> 502             result = func(*args)
    503             if result is not None:
    504                 return result

~\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
    647 class HTTPDefaultErrorHandler(BaseHandler):
    648     def http_error_default(self, req, fp, code, msg, hdrs):
--> 649         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    650
    651 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 403: Forbidden


text:
Q: Overlapping header on second page of pdf generated using HTML Target: To give margin of upto 8cm to a dynamically generated pdf, which has repeated header and footer on every page.
Current issue: Although I am able to give margin to the pdf and the content gets properly aligned on the first page, but from the second page onwards the content of the body starts to overlap with the header of the page,
Page 2 and beyond - ISSUE

How it SHOULD LOOK LIKE

What I tried:
Tried the solution in related questions like :-
Content overlapping with header on second page of PDF and Table headers overlapping on second page when printing/PDF and other ones too, but none of them seem to be working.
Code:-

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link
      href="https://fonts.googleapis.com/css2?family=Mulish:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl"
      crossorigin="anonymous"
    />
    <title>Document</title>

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Header

      Footer

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

                Main content

PS: The issue would be reproducible only if the margin exceeds the value of 1.5cm, also if any other third party tool or any other way is possible to achieve the target please feel free to share.
Thank you!

A: After searching through a lot of materials, finally, I can conclude that with increasing page margin the max value one can give to the page header i.e
 decreases.
For example,

*

*0cm page margin - max header height could be 250px

*1cm page margin - max header height could be 230px

and so on.

.page-header,
.page-header-space {
  height: 250px;
}

A point to add, the values given are not strict values and will change based on your use case, but by varying header size based on the margin value, one can achieve the target given in the question.

A: The main issue seems to be that you placed  your  "Main content" in one single row.
I managed to make it work doing something similar to this.
Also I moved the header and footer placeholders to thead and tfoot respectively.
Additionally, the "@page{margin: 5cm;}" seems to break it, to be honest I don't know why.
I had to modify the code quite a bit but I hope it helps you as a template for what you want to achieve.
This is the code I ended up with:

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link
    href="https://fonts.googleapis.com/css2?family=Mulish:wght@400;700&display=swap"
    rel="stylesheet"
    />
    <link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl"
    crossorigin="anonymous"
    />
    <title>Document</title>

Header

Header

Header

Header

Header

Header

Header

Header

Header

Header

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Main content

Footer


text:
Q: How do I make html files accessible from OpenShift server running python? I have an OpenShift DIY app running Python. However, I cannot reach static files like html. (or run php) If I try accessing: mydomain.rhcloud.com/hello.html, I get:
uWSGI Error Python application not found.
Could you please help how i can make html files accessible?
My directories like:
repo
   diy
      something.py << It server all requests to the domain, however if it doesn't
      hello.html / exists, than I get the above error

A: The Python cartridges that you get with OpenShift is simply an Apache web serve that uses mod_wsgi to server your content. This means that you content that Apache directs you to most be severed by a mod_wsgi server/components.
Typically with a Python Cartridge you will extend the cartridge with a Web Framework to better help you sever static content such as this. Some examples of typical frameworks that are use are:

*

*Django

*Flask, see an example

*CherryPy
However out of the box (unless you are willing to edit your gears python/etc/conf.d/openshift.conf file which can break your gear) you can not route to static traffic with out using a WSGI framework.


text:
Q: What does deletion of post cost? Do I lose reputation on deleting my post with score -3? I just lost my reputation by 10.

A: When a post gets deleted, you lose all the reputation you gained/lost on it*.
So if you have an answer with:

*

*2 upvotes

*5 downvotes

for a total of -3. You earned 2*10 - 5*2 = 10 for that post. Deleting it will make you lose that 10 rep.
*Some exceptions apply:

*

*If your post is "historic", you won't lose the rep.

*IIRC, if there are any flags on the post, you may not always regain any rep you lost on it. (I'm unsure of the exact situations...)


text:
Q: How can I use all the React events with Material-UI components? The Material-UI DataGrid exposes an onCellHover prop, but no event when hovering ends. Is there any way to use standard React events like onMouseLeave?
<DataGrid onMouseLeave={handleMouseLeave} />

This does not trigger.

A: To have React react (sorry lol) to onMouseLeave just wrap it in another element, like <div>, for example.
Here is what i've done with the standard MUI codesandbox demo.


text:
Q: what are the limitations to execute a binary which compiled actually on x86_64 machine into i686 machine? i tried to compile sample hello_world.c program in x86-64 machine, but i expect to execute hello_world binary into i686 machine. can somebody correct me if i was wrong, what are the subjective limitations to execute x86-64 binary into i686 Machine. from my understanding x86-64 binary will execute in 32-bit machine aswell.
prashad@ubuntu:~$ uname -a
Linux ubuntu 5.3.0-62-generic #56~18.04.1-Ubuntu SMP Wed Jun 24 16:17:03 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
prashad@ubuntu:~$

root@Docsis-Gateway:/tmp# uname -a
Linux Docsis-Gateway 4.9.199-yocto-standard #1 SMP PREEMPT Thu Aug 6 22:38:09 UTC 2020 i686 GNU/Linux

A: i686 packages are intended to be executed on Intel 32-bit x86 processors up to and including the
Pentium 4
and others, as well as
AMD K6
processors and other compatible 32-bit CPUs.
For more information see
AMD K6 series
and
Intel i686.
x86_64
is for processors compatible with the AMD64 64-bit platform and
Intel 64
based processors.
64-bit processors are fully backward compatible with 32-bit predecessors,
so an AMD64 or Intel 64 processor supports both 64-bit x86_64 and 32-bit i686.
But for performance you may prefer the 64-bit x86_64 distribution packages.
However, a 32-bit computer can only execute i686 packages and cannot execute
x86_64 packages.
Reference :
Microprocessor Types and Specifications.


text:
Q: calculation of the value Pi (π) using recursion in c++ hey guys i have a little bit confusion regarding my program ....Actually my program is about finding the value of pi using infinite series :-
(4*(1-1/3+1/5-1/7+1/9-1/11.......so on ))
and i successfully completed my task using recursion ...but i have to do this program by passing only one argument that is n ...and value of n is always an odd number ...by i completed my task using three arguments i.e (n,sum,sign)...is there is any possible way to complete the program with only one argument that is n...sorry for my bad english ....i hope u understand better with the help my code .....here it is :-
     #include <iostream>
     using namespace std;
     float Pie(int n,float sum,float sign){
        if (((n+1)/2)%2==0) //for even terms n sign is -1 and vice versa
            sign=-1.0;
        else
            sign=1.0;
        if (n==1)
            return sum+1;
        sum=sum+((sign*1.0/n));
        return Pie(n-2,sum,sign);
     }
     int main(){
        int n;
        cout<<"enter the value of n : ";//n is always an odd number
        cin>>n;
        float sum=0.0;
        float sign;
        cout<<"value of pi is "<<4*Pie(n,sum,sign);
     }

A: Create an overload of Pie that supplies the initial values:
float Pie(int n) { return Pie(n, 0, 0); }

A: You can make an overloaded version of Pie that takes a single number and call the recursive version.
Your recursive version is painfully complicated. It can be simplified to:
float Pie(int i, int n, float sign){
   if ( i > n )
   {
      return 0;
   }

   return sign*1.0/i + Pie(i+2, n, -sign);
}

and the non-recursive version can be:
float Pie(int n)
{
   return Pie(1, n, 1.0);
}

A: The required function as follows:
float Pie(int n) { return (n == 0) ? 0 : (n % 2 ? 1 : -1) * 1.0 / n + Pie(n - 2); }

Then your main function would be:
int main() {
   int n;
   cout << "enter the value of n : ";
   cin >> n;
   cout << "value of pi is " << 4 * Pie(n);
}


text:
Q: Memory Leak in Rails App... string nightmare So I've got this rails app with a horrible memory leak problem. I'm running it on Heroku, and for the last couple days while I've been trying to figure out what on earth is causing it, I've had to continually restart the app every 5 hours or so or the memory exceeds 512 and my app crashes.
I'm using Oink, and I'm not seeing anything fishy with my instantiated classes. The only thing is that with each page load, the memory used creeps up. It doesn't even matter which page I load, it's seemingly random.
New Relic hasn't been much help either, since it doesn't have to do with any one particular controller action.
The only thing I've been able to find was using ObjectSpace, which revealed an ENORMOUS number of string objects in memory, and the number just grows and grows. I used a little tool to log the value of the strings and they're all blank. Not nil... but whitespace. My production app regularly has over 200,000 string objects in use.
Does anyone have any idea what these could possibly be coming from? This is really stressing me out having to be at my computer every five hours to keep my site alive.
Thanks!

A: Okay, this is absolutely ridiculous, but after two weeks of anxiety and struggle, I found the solution to this leak. It literally all came down to this one line:
ActionMailer::Base.delivery_method = :smtp

in my application.rb config file.
It should have been:
config.action_mailer.delivery_method = :smtp

I have no idea how I got it wrong, but boy did it wreak havoc on my app.
Does anyone know why this would cause such a problem? I was losing about a megabyte of memory on every single query. Crazy.


text:
Q: nuxt.render not working in production mode for Nuxt SPA The following code runs in the standard Nuxt server/index.js just fine in development mode when starting up my SPA app.
// Init Nuxt.js
const nuxt = new Nuxt(config)

// Build only in dev mode
if (config.dev) {
  const builder = new Builder(nuxt)
  await builder.build()
}

// Give nuxt middleware to express
app.use(nuxt.render)

When deployed and in production mode, the build process is skipped (which is what I want) but nuxt.render() fails because it has not been initialized by builder.build().
I've tried everything I can think of and can't find a solution where it simply renders a pre-built app as it LOOKS like it is supposed to do.


text:
Q: Asp.net Razor, Syntax error - onclick event parameter <input type="button" value="Delete" onclick="deleteMember(@Model.ID, '@ViewBag.returnUrl')"/>

That code has 4 errors, 2 syntax error and 2 Unterminated string constant.
What should I do to fix these errors?

A: You could break it out in a an Html.Raw Call:
<input type="button"
       value="Delete"
       onclick="@(Html.Raw(String.Format("deleteMember({0}, '{1}')",
           Model.ID,
           Html.Encode(ViewBag.returnUrl)
       )))"
/>

Or assign it to a string first, then reference that variable in the attribute.
@{
  String onclick = String.Format("deleteMember({0}, '{1}')",
      Model.ID, Html.Encode(ViewBag.returnUrl));
}
<input type="button" value="delete" onclick="@onclick" />

Third option is to separate concerns; Keep markup and scripts separate. Neil beat me to it, but something like:
<input type="button" value="delete"
    data-task="delete" data-id="@Model.ID" data-returnurl="@ViewBag.returnUrl" />

<!-- .... -->

<script>
  var buttons = document.getElementsByTagName('INPUT');
  for (var b = 0; b < buttons.length; b++){
    if (buttons[b].type != 'button') continue;
    switch (buttons[b].getAttribute('data-task') || ''){
      case 'delete':
        // read data-id & data-returnurl. Do something with them, and
        // move on.
        break;

      // other actions
      case 'add':
      case 'update':
      default:
        break;
    }
  }
</script>

Though it's strange the first parenthesis messes with razor (even though it's declared in an attribute). I wouldn't expect this behavior myself.

A: It's more a bug in VS than anything else.
It think it would still render as you would expect.
I like Brad's solution.
Another recommended option is to pop your values into data-dash attributes and use something like jQuery to pass the data-dash values to your function.

A: Another way you could do it would be assigning the values to javascript variables and using them in the call of the method.
<script>
  var memberId = '@Model.ID';
  var returnUrl = '@ViewBag.returnUrl';
</script>

<input type="button" value="Delete" onclick="deleteMember(memberId, returnUrl)"/>

A: You can use this way too to pass the parameter in the function
@Html.DropDownListFor(M => M.SubscriptionType,
   new SelectList(Model.DefaultPlanName, "value", "displayText"),
   new { @onclick = "Testnew('"+Model.CreationTime+"' )",
    @class = "form-control selectpicker" })


text:
Q: How to correct file extension for thumbnail generation of movie with CarrierWave I want to upload files and convert thumbnails for it.
My code is:
require 'streamio-ffmpeg'
module CarrierWave
  module FFMPEG
    module ClassMethods
      def resample(bitrate)
        process :resample => bitrate
      end

      def gen_video_thumb(width, height)
        process :gen_video_thumb => [width, height]
      end
    end

    #def is_video?
    #  ::FFMPEG::Movie.new(File.open(store_path)).frame_rate != nil
    #end

    def gen_video_thumb(width, height)
      directory = File.dirname(current_path)
      tmpfile = File.join(directory, "tmpfile")

      FileUtils.move(current_path, tmpfile)
      file = ::FFMPEG::Movie.new(tmpfile)
      file.transcode(current_path, "-ss 00:00:01 -an -r 1 -vframes 1 -s #{width}x#{height}")

      FileUtils.rm(tmpfile)
    end

    def resample(bitrate)
      directory = File.dirname(current_path)
      tmpfile = File.join(directory, "tmpfile")

      File.move(current_path, tmpfile)

      file = ::FFMPEG::Movie.new(tmpfile)
      file.transcode(current_path, :audio_bitrate => bitrate)

      File.delete(tmpfile)
    end
  end
end

My Uploader have
  version :thumb do
    process :resize_to_fill => [100, 70], :if=> :image?
    process :gen_video_thumb => [100, 70], :if=> :video? do
      process :convert => 'png'
    end
  end

and functions are.
  protected

  def image?(new_file)
    ::FFMPEG::Movie.new(new_file.file.path).frame_rate == nil
  end

  def video?(new_file)
    ::FFMPEG::Movie.new(new_file.file.path).frame_rate != nil
  end

But the problem is that, video is uploaded, video thubmail is generated very good. But it do not have a png extension. If i upload a mp4 file, its thumbnail also have a mp4 extension. but that is an image can be viewed in browser.
How to correct the extension issue? Can any one point out the issue in the code?

A: I recently solved this by overriding the full_filename method for the :thumb version
version :thumb do
  # do your processing
  process :whatever

  # redefine the name for this version
  def full_filename(for_file=file)
    super.chomp('mp4') + 'png'
  end
end

I called super to get the default :thumb filename, then changed the extension from mp4 to png, but you could do anything.
For more info, the carrierwave wiki has a good article on How to: Customize your version file names. Check out the other wiki pages for lots of ideas.


text:
Q: Reusing iMac Fusion Drive as external drive The logic board of my iMac 27" Retina broke and I find it impossible to get a new one in the country where I'm living in.
I wonder if it's possible to access the data in the Fusion hard drive,
 connecting both SSD+HDD as external drives in another Mac OSX system.
Some people say it's impossible, some very few others say it can be done. I wonder if you can give me some advice before I go and buy this super expensive SATA-to-USB Apple adapter.
Best regards!

A: you can put the old fusion drive in a usb enclosure then you should be able to boot to it by pressing the Option key when the boot chime rings. you can also use the drive in the enclosure to setup a new Mac. Using Migration Assistant you can import your entire old file system just as if you were using a Time Machine backup. The question of what to do with the drive AFTER you successfully accomplished moving your old file/apps/etc to the new Mac. All of a sudden you've got a 1.12TB or bigger drive on your hands. On Disk Utility it will show up as Fusion Drive and having the Core system with 2 partitions. I'm not sure if you can actually format the Fustion Drive as one unit and use the entire thing for whatever you wanted, like storing all your media files to be streamed from anywhere in the house.

A: Target Disk Mode is probably what you're looking for.
https://support.apple.com/en-us/HT201462


text:
Q: Assign value from filename and content of file to a template using Powershell In my directory path\, I have many text files with name something like this
area1.txt
area2.txt
area3.txt

Each file contains lots of one liner string that looks like this
user1
user2
user3

How do I write a Powershell script to pass all of the filename and content of file to a template so it will look like this for every iteration or combining all result in single file.
area "filename"
user "user1"
realname "user1"

Managed to write a script but it does not produce the desired outcome. Somehow it only produce last value of filename in loop and empty string after user and realname template.
foreach($file in Get-ChildItem path\ -Filter *.txt){
$result = @"
area $($file.BaseName)
area {0}
realname {0}
"@
}

foreach($file in Get-ChildItem path\ -Filter *.txt){
    foreach ($line in $file |Get-Content){
        $result -f $_
    }
  }

Need your help to point out the error in my script and help me to fix it. I really appreciate it if anyone can help.

A: You only need a single set of (nested) loops for this, then reference $line and $file appropriately inside the inner loop:
foreach($file in Get-ChildItem path\ -Filter *.txt){
    foreach ($line in $file |Get-Content){
        @"
area {1}
user {0}
realname {0}
"@ -f $line,$file.BaseName
    }
}


text:
Q: How can I remove a specific amount of items from an array but at random locations without loosing the array order? I'm trying to replace a percentage of letters in an array containing single letter strings.
I'm trying to do it with a while loop but it doesn't seem to work
here's what I've tried:
  let validAnswer = false;
  let neededHintLetters = Math.round(blankLetters.length * 40/100);
  while(!validAnswer) {
    let numHintLetters = 0;
    $.each(blankLetters, function(i) {
      let index = Math.floor(Math.random() * blankLetters.length);

      if (index !== i) {
        blankLetters[i] = '?'
      }
      else { //don't replace the letter
        numHintLetters++;
      }
    });
    if (numHintLetters === neededHintLetters) {
      break;
    }
  }

A: Ok I changed the way I thought about it lol I don't know why I was trying with these kinds of loops... possibly because it was super late yesterday
Here is what worked for me:
const NUM_HINT_LETTERS = Math.ceil(blankLetters.length * 50/100); //ceil.50% of the words should stay visible as hints
  let hintPlacement = []; //array that matches the letters
  $.each(blankLetters, function(i) {
    let hint;
    if (i < NUM_HINT_LETTERS - 1) {
      hint = true; //the first NUM_HINT_LETTERS of elements are true and wont be changed to a blank space
    }
    else {
      hint = false;
    }
    hintPlacement.push(hint);
  });
  shuffle(hintPlacement); //give the hints random positions

  $.each(blankLetters, function(i) {
    if (!hintPlacement[i]) {
      blankLetters[i] = '?'
    }
  });


text:
Q: Optimize my date formatter code I am creating a UIPickerView that lets users pick a specific date and time format. I was reading that it's better to create a date formatter only once as a global function rather than to create it every time a date needs to be formatted. What I am struggling with is how to only create one date formatter for all four of the formats I want. Below is the code I have right now that works but it requires me to create four different date formatters. I am trying to find a way to only create one date formatter for all four formats.
let customDateFormatter: NSDateFormatter = {
  let formatter = NSDateFormatter()
  formatter.dateFormat = "EEE, MMM dd, yyyy, h:mm a zzz"
  return formatter
}()

let mediumShortDateFormatter: DateFormatter = {
  let formatter = DateFormatter()
  formatter.dateStyle = .medium
  formatter.timeStyle = .short
  return formatter
}()

let dateOnlyDateFormatter: DateFormatter = {
  let formatter = DateFormatter()
  formatter.dateStyle = .medium
  formatter.timeStyle = .none
  return formatter
}()

let timeOnlyDateFormatter: DateFormatter = {
  let formatter = DateFormatter()
  formatter.dateStyle = .none
  formatter.timeStyle = .short
  return formatter
}()


text:
Q: Algolia unknown parameter I'm using algolia to search in a rails app using the algoliasearch-rails gem.
In my product model, I have this:
algoliasearch index_name: "Product" do
  attributes :id, :name, :description, :active?
  ...
end

I'm trying to filter results by a filter called "active?".  I'm getting an error back from Algolia when I try to run the search with the parameter included.
{"hits"=>[], "hitsPerPage"=>0, "page"=>0, "facets"=>{}, "error"=>#<Algolia::AlgoliaProtocolError: 400: Cannot POST to https://algolia.net/1/indexes/Product_development/query: {"message":"Unknown parameter: active%3F","status":400}

I can't figure out how to properly reference the parameter. It is working to retrieve the "active?" attribute correctly when I don't filter by active?.  I could change the parameter name, but would rather not.
How do I reference an Algolia search attribute that has a question mark in the name for filtering?

A: You can't use an attribute with a question mark like that.
As Slava.K mentioned in a comment, if your active? method is an Active Record attribute, using active instead will work just fine.
However, if active? is a method unrelated with Active Record, I suggest adding a custom attribute like so:
class Product < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch do
    attributes :id, :name, :description
    attribute :active do
      active?
    end
  end

  def active?
    ...
  end
end

More details on custom attributes here: https://github.com/algolia/algoliasearch-rails#custom-attribute-definition