text:
Q: Java Swing - Place border around JTable row when row has Boolean and String types (Nimbus Look and Feel) I apologize if this has been asked before, but I can't seem to find an answer here.
I have a JTable. I need to place a red border around certain rows that satisfy a certain condition (no value in the Class Type column). When I had only Strings in the JTable, the following code worked. I have since added a Boolean (JCheckBoxes) column in the JTable, causing my code to not put a border around the whole row anymore. How can I fix the code to put a border around the whole row again?
This does appear to be a Look and Feel issue. Using the System LAF (on Windows 10) makes it correctly put a border around the whole row, while using the Nimbus LAF makes it appear as below. I wanted to use Nimbus though, so any advice on fixing this part of Nimbus would be appreciated.
I am using the default renderers provided by Java using NetBeans, as shown in one of the images below. All 4 columns have the Renderer set to "none".
Custom Creation Code in NetBeans for the JTable:
new javax.swing.JTable()
{
    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
    {
        Component c = super.prepareRenderer(renderer, row, column);
        JComponent jc = (JComponent) c;

        if (rowContainsNonexistentClassType(tableFullClassList.convertRowIndexToModel(row)))
        {
            int top = (row > 0 && isRowSelected(row - 1)) ? 1 : 2;
            int left = column == 0 ? 2 : 0;
            int bottom = (row < getRowCount() - 1 && isRowSelected(row + 1)) ? 1 : 2;
            int right = column == getColumnCount() - 1 ? 2 : 0;

            jc.setBorder(BorderFactory.createMatteBorder(top, left, bottom, right, Color.RED));
        }
        else
            jc.setBorder(null);

        return c;
    }
}

What it looked like when the JTable only had Strings:

What it looks like with the JTable having Strings and Booleans:

The JTable column settings in NetBeans:


text:
Q: getting ids of all documents indexed in elastic search using scroll Similar questions were asked before and a furnished the primitive code below based on similar answers. My requirement is to 'loop'/scroll over all currently indexed documents in elastic search to obtain a list of their unique ids. The code below works fine for the first 1000 documents but then gets stuck in the do while loop without retrieving new ids. It may not scroll further? Could someone please be so kind and point out the error/issue? Thanks!
var searchResult = client.Search<Document>(
    s => s
    .AllTypes()
    .From(0)
    .Size(1000)
    .MatchAll()
    .Scroll("10s")
);

IBulkResponse indexResult = null;
do
{
    var result = searchResult;
    searchResult = client.Scroll<Document>("10s", result.ScrollId);
    if (searchResult.Documents.Any())
    {
    foreach (var doc in searchResult.Documents)
    {
        var id = doc.some_id.Trim();
        if (id_list.Contains(id) == false)
        {
        id_list.Add(id);
        Console.WriteLine(id_list.Count);
        }
    }
    }

    page++;
} while (searchResult.IsValid && indexResult != null && indexResult.IsValid && searchResult.Documents.Any());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any idea about WPF ScrollViewer to make it smooth scroolling like Android? I have trying a simple ScrollViewer in xaml like below:
<ScrollViewer Height="{Binding RelativeSource={RelativeSource FindAncestor,
     AncestorType={x:Type StackPanel}}, Path=Height}" ScrollViewer.VerticalScrollBarVisibility="Visible" CanContentScroll="True">
         <DockPanel>
             <StackPanel Name="StackPanel1" OverridesDefaultStyle="False" Width="230" Height="803"
                 VerticalAlignment="Top" HorizontalAlignment="Left" Margin="23,1,0,0">
             ....Something here
             ....Something here
             ....Something here
             </StackPanel>
         </DockPanel>
</ScrollViewer>

But my question is..is it possible for us to create any smooth scrolling likes any android or iphone using WPF?
Any ideas?

A: You would need to handle the MouseDown, MouseUp, MouseMove events yourself or the appropriate touch events yourself I would imagine.
BTW, why are you using a relativeSource to get the height of the parent. Can't you just set the scroll viewer to fill the parent?


text:
Q: Notification from google Play Store Today i received an email from Google Play Team. How can I find which library or SDK is violating the conditions of the Google Play? Here is the content of mail:

This is a notification that your application, is currently in
  violation of our developer terms. REASON FOR WARNING: Violation of the
  Personal and Confidential Information provision of the Developer
  Distribution Agreement:
(Dangerous Products): Apps that collect information (such as the
  user's location or behavior) without the user's knowledge (spyware) …
  are prohibited on Google Play. (Personal and Confidential
  Information): We don't allow unauthorized publishing or disclosure of
  people's private and confidential information, such as credit card
  numbers, government identification numbers, driver's and other license
  numbers, non-public contacts, or any other information that is not
  publicly accessible. We have determined that one or more Ad SDKs or
  libraries used in the above app facilitates the transmission of the
  list of installed apps on the user's device to a server without
  conspicuous disclosure to the user that this is happening. This
  violates the above policy provision. Please evaluate any third party
  libraries for compliance and/or consult your Ad SDK provider(s) for
  further information if necessary.
Your application will be removed if you do not bring it into
  compliance by removing the ads sdk or library from your app, or
  updating to a compliant version of the SDK(s) or library(ies) within
  30 days of the issuance of this notification. If you have additional
  applications in your catalog, please also review them for compliance.
  Note that any remaining applications found to be in violation will be
  removed from the Google Play Store.
Please also consult the Policy and Best Practices and the Developer
  Distribution Agreement as you bring your applications into compliance.
You can also review this Google Play Help Center article for more
  information on this warning.
All violations are tracked. Serious or repeated violations of any
  nature will result in the termination of your developer account, and
  investigation and possible termination of related Google accounts.
The Google Play Team

A: WOW!
exactly the same mail I received from Google play 2 days back! Word by word same.
Great, So the issue 100% is the permission settings for the Flurry and TapStream SDKs. I just contacted Flurry/Tapstream for this, awaiting a reply from them.
By the way I checked Tap Stream here
You can clearly see they have asked for adding an intent under the application tag
 <receiver android:name="com.tapstream.sdk.ReferrerReceiver" android:exported="true" >
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>

This is used to get the list of apps installed just to record analytics to count the App installs and see how many users are still using the App.
but regarding the Location collecetion [Dangerous content] I still have to figure out.
One possible measure I have thought of doing is adding an EULA before letting user use the app, on the first run. It makes sure that my back is covered. Additionally, you can also add permission for FINE_LOCATION under manifest. Since it is for sure that one/both of the SDKs are using user location.
Good question!
Will update as soon as I receive any updates.
UPDATE
Finally, I received Mail from Tapstream, they are saying that they have made changes according to the Google's Policy change on November 15 2014 hence, asked me to change the SDK version to the lastest one.
Quoted here

Hi there,
Tapstream has updated its Android SDK to comply with a recent Google Play store policy change.
Due to this policy change, a minor component of Tapstream's device identification process can no longer be collected by the Android SDK. This change will not impact your tracking.
To avoid any app approval issues on the Play store, you should deploy this new SDK as soon as possible.
You can find the updated Android SDK here: tapstream.com/developer/android/sdk
The updated SDK is a drop-in replacement; no other changes are required. If you need any assistance, or would like further information, just reply to this email.

I hope that might serve as a solution apparently.


text:
Q: Joining multiple tables using PHP relating to a member id I'm really hoping that you can clear things up for me regarding JOIN using php as I'm really struggling to come to terms with how it works.
Basically I have 2 tables, one for premium members and another for fans of these members.  So I want to get certain information from the "premium" table where a member ($memberid) is a fan.
Premium = id, name, avatar, town, etc, etc
Fans = fan($memberid), fanee(Premium ID)

So I have this code at the moment:
<?php
$get_connections_sql = "SELECT id, name, avatar, town FROM premium LEFT JOIN fans ON fans.fanee=premium.id WHERE fans.fan=$memberid LIMIT 18";
$get_connections_res = mysqli_query($con, $get_connections_sql);
if(mysqli_affected_rows($con)>0){
    while ($connections = mysqli_fetch_assoc($get_connections_res)){
        $connectionid = $connections['id'];
        $connectionname = $connections['name'];
        $connectiontown = $connections['town'];
        $connectionavatar = $connections['avatar'];

    $connections .= "

    ";
    }
}else{

    $connections = "

There are no connections to be shown

    ";

}
?>

This is returning the else condition so there must be something wrong with my JOIN row - Can anyone please point me in the right direction.

A: You've said that the column 'id' is ambiguous, this is because you have two tables referenced in your query both with 'id' columns and MySQL does not know which to choose.  You can be specific by adding the table name like this:
SELECT premium.id, ...

Additionally, you'll want mysqli_num_rows() instead of mysqli_affected_rows().  Since your query does not affect any rows (like update, delete, insert), instead it's returning a set of rows.
mysql_num_rows() takes the result of a query as its parameter (in your case $get_connections_res) rather than the connection.  To make sure that the result is valid first check the value of $get_connections_res before the if... if it's falsey then there's an error in the query. Use mysqli_error() to report the error.


text:
Q: Python export MySQL SELECT to XML I am trying to work out how to export the result of a MySQL SELECT query to an XML file. The query looks like this:
SELECT id, extension_id, flow, filename, filesize, unread, cr_date, callerid,
  length, callid, info, party
FROM extension_recording

I can see that there are two ways of going about this - either running mysqldump --xml or using Python's XML modules. Not sure which is the best way to go about this, interested to hear some opinions on which might work better?
Thanks


text:
Q: Hibernate validator. Number field I want to validate a jsp field. There should be a positive number (1, 100, 1000, etc). But I get an error when I put there a String value:
No validator could be found for type: java.lang.Long.

Here is a code from the model:
@NotNull @Pattern(regexp = "[0-9]+", message = "wrong Sort number")
private Long depOrder;

How could I get my "wrong Order number" message instead of that ugly error.
Thanks.

A: for my eyes it looks strange to check a Long with a regexp for numbers.
May No validator could be found for type: java.lang.Short
will help


text:
Q: SSIS Performance tuning Suppose my system has 8GB RAM and I have installed SQL Server 2012 on it along with the DataTools. Sql server engine uses 6GB memory. Will the SSIS uses remaning memory apart from 6GB or it uses 6GB?
Also is there a way to count the number of buffers used and the records accomodated in each buffer and the size of the buffer?
If am not wrong buffer refers to the RAM memory?

A: SSIS will use as much memory as it needs. If there is not enough physical DRAM on the box, it will take it from the page file (which generally results in a big slowdown)
The memory for running SSIS does not come out of the SQL Server memory space, it comes out of the memory that is left on the box after SQL Server has taken what it wants. In your case, this would be 2GB. Remember that out of those 2GB, you will also need space for the OS and another other applications running on the box.
In other words, think of SSIS just like any other application - not as part of SQL Server (even though it installs with it).


text:
Q: PHP Radio Button Inside echo     echo    "<form class='custom'>";
foreach ($prices->item as $item){
      $ongkir = $item->value;
      $transfer = $total_jne * 1000;
      $transfer_rp = $transfer + $ongkir;
      $jne = $item->service;
      $checked = ($jne == $_POST['ongkir'])? ' checked="checked"' : '';
      echo  "

      <input class='custom' name='ongkir' $checked type='radio' id='ongkir'> $jne	";
      echo  "Rp. $ongkir	";
      echo  "Rp. $transfer_rp
";}
      echo  "

</form>" ;
    }

Hi Everybody, how do i post "checked" with value='$transfer_rp' to another php file with button? :(

A: The radio input will come as "true" or "false", not as the value of its name property, so try
$checked = ($jne == 'ongkir' && isset($_POST['ongkir']) && $_POST['ongkir'] == "true" )? ' checked="checked"' : '';
Or alternatively since this is ugly
$checked = '';
if( $jne == 'ongkir' && isset($_POST['ongkir']) && $_POST['ongkir'] == "true" ){
    $checked = 'checked="checked"';
}


text:
Q: setInterval after setTimeout var playtop = setInterval(goright, 5000);

function goright(){
...
}

The above works.
Now, I need to interrupt the above by clicking on a button, do something on page, and ten seconds after click - activate the setInterval again.
$("#btngoright").click(function(){
    clearInterval(playtop);
    ...
    setTimeout(playtop, 10000);
});

But, once interrupted, setInterval is not activated again.

A: It's not working because playtop is the id that was returned when initially setting the interval.
The setTimeout method expects a function, not an id, therefore you should pass a reference to the goright function again:
setTimeout(goright, 10000);

If you want to activate the interval again after 10 seconds, you can set an interval and pass a reference to the goright function in an anonymous function:
$("#btngoright").click(function(){
    clearInterval(playtop);

    setTimeout(function () {
      setInterval(goright, 5000);
    }, 10000);
});

A: Nearly. It should be:
$("#btngoright").click(function(){
    clearInterval(playtop);

    setTimeout(function () {
      playtop = setInterval(goright, 5000);
    }, 10000);
});

This way you are putting control back into the playtop variable meaning that the interrupt function will work more than once.


text:
Q: Multiplying CGPoints using SKTUtils I'm developing a Sprite Kit game using Swift, loosely following the Ray Wenderlich tutorials found here and here, and incorporating the SKTUtils module to allow easy addition/multiplication/division etc. of CGPoints.
The issue I'm finding is that all the online documentation refers to the older, Objective-C version of the module, while the code on Github has been rewritten to use Swift, and there's no accompanying usage guidelines.
The tutorial (written using Objective-C) states that the following code should work:
- (void)update:(NSTimeInterval)delta {
  CGPoint gravity = CGPointMake(0.0, -450.0);
  CGPoint gravityStep = CGPointMultiplyScalar(gravity, delta);
  self.velocity = CGPointAdd(self.velocity, gravityStep);
  CGPoint velocityStep = CGPointMultiplyScalar(self.velocity, delta);
  self.position = CGPointAdd(self.position, velocityStep);
}

Which, loosely translated to Swift, equates to:
func update(delta:NSTimeInterval) {
    let gravity:CGPoint = CGPointMake(0.0, -450.0);
    var gravityStep:CGPoint = CGPointMultiplyScalar(gravity * delta)
    self.velocity = self.velocity + gravityStep;
    let velocityStep:CGPoint = CGPointMultiplyScalar(self.velocity, delta)
    self.position = self.position + velocityStep;
}

However, the CGPointMultiplyScalar function has been changed to simply *. There's no accompanying documentation that I can find on how to implement thins, and my approaches aren't working:
func update(delta:NSTimeInterval) {
    ...
    var gravityStep:CGPoint = CGPoint(gravity * delta); // nope
    var gravityStep:CGPoint = gravity * delta; // nope
    ...
}

Does anyone out there have experience with this and can tell me where I'm going wrong?

A: The CGPoint extension looks like:
public func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
    return CGPoint(x: point.x * scalar, y: point.y * scalar)
}

The scalar parameter needs a CGFloat, but you try to multiply it with an NSTimeInterval, and since there are no implicit conversions, you have to do
var gravityStep:CGPoint = gravity * CGFloat(delta)

to make it work.


text:
Q: What is meant by 'Exported function' in c++? Recently I started to work with c++. I heard about exported functions but not sure what it means.
so my questions are about:

*

*What is exported function?

*Is there any difference between normal function and exported function? if yes, what is it?

*How is it related with dll?

A:

*

*what is exported function ?

When you program with modules (pieces of code) you need to call in some module a function which was defined in some other module. Exporting is relative to that process. In C/C++ if you want to declare a function to use it without defining it in a source file, you should use the keyword "extern". In the file where that function is defined you have nothing special to make, by defaults things at global scope are automatically exported.

*Is there any difference between normal function and exported function?    if yes , what it is ?

Nothing special, except that the later are visible at link time.

*how it is related with dll ?

See, http://msdn.microsoft.com/en-us/library/a90k134d.aspx for DLL and function export for DLL. In such a case you must declare which function should be exported.


text:
Q: Chome Extension - Programatically Trigger Pop Up i am currently creating a chrome extension, i was able to create the popup.html and it works just fine, i was able to add a little authentication mechanism to it as well and it works just as expected. however there is something i am trying to achieve which at the moment seems impossible, but first let me explain the functionality of the extension

*

*When i visit a particular link / site my content-script runs, it appends a button anywhere it see's the div class '.Post', i then add an event listener to the button that sends information such as the post title, URL and author of the post etc. now to where i need help.

Is it possible that when one click on the button it opens the Popup.html and sends these information to the popup.html.
Here is my code thus far.
content-script.js
$('.Post').append('<button id="the_id" class="add_archive_btn"> Add Archive </button>');
$('body').append('')
$('body').append('')

Script.js
$(document).ready(function(){
    whatToShow();
});

var userExtensionKey = 'blabla';

function whatToShow(){
    var data = localStorage.getItem(userExtensionKey);
    if(data !== null){
        $('.login_form').hide();
        $('.logged_in_layout').show();
    } else {
        $('.login_form').show();
        $('.logged_in_layout').hide();
    }

}

$('#revoked_access').on('click', function (event) {
    event.preventDefault();
    localStorage.removeItem(userExtensionKey);
    $('.logged_in_layout').hide();
    $('.login_form').show();
});

$('#click_action').on('submit', function (event) {
    event.preventDefault();
    $.ajax({
        url: "http://127.0.0.1:8000/api/login"
        , type: 'POST'
        , data: {
            email: $('#lead_email').val(),
            password: $('#lead_password').val()
        }
        , dataType: 'json', // added data type
        success: function (res) {
            parseLogin(res)
        }
        , error: function (error) {
            printErrorMsg(error.responseJSON.error)
        }
    });
});

function printErrorMsg(msg) {
    console.log(msg);
    if (msg !== undefined) {
        var objt = Object.keys(msg);
        if (jQuery.inArray('email', objt) == "-1") {
            $('#email_input_filed').html('');
        } else {
            $('#email_input_filed').html('
' + msg['email'][0] + '
');
        }

        if (jQuery.inArray('password', objt) == "-1") {
            $('#password_input_filed').html('');
        } else {
            $('#password_input_filed').html('
' + msg['password'][0] + '
');
        }

        if (jQuery.inArray('loginfailed', objt) == "-1") {
            $('#login_failed').html('');
        } else {
            $('#login_failed').html('
' + msg['loginfailed'][0] + '
');
        }
    }
}

function parseLogin(){
    // save login username
    localStorage.setItem(userExtensionKey, $('#lead_email').val());
    $('#lead_email').val('');
    $('#lead_password').val('')
    $('.login_form').hide();
    $('.logged_in_layout').show();
    console.log('saved user details succesfully');
}

Manifest.json
{
  "name": "Hello Extensions",
  "permissions": [
    "http://127.0.0.1:8000/",
    "activeTab",
      "tabs",
      "storage"
  ],
  "description" : "Base Level Extension",
  "version": "1.0",
  "browser_action": {
    "default_popup": "hello.html",
    "default_icon": "hello_extensions.png"
  },
  "manifest_version": 2,
  "commands": {
    "_execute_browser_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+F",
        "mac": "MacCtrl+Shift+F"
      },
      "description": "Opens hello.html"
    }
  },
  "background": {
    "scripts": ["/js/background_script.js"],
    "persistent": false
  },
  "content_scripts" : [
     {
      "matches": ["<all_url>"],
      "js": ["/js/jquery.min.js", "/js/content-script.js"],
      "permissions": [
          "activeTab",
          "tabs",
          "storage"
        ]
     }
  ]
}

Please ignore the background.js script it is currently blank and has nothing inside, any help would be much appreciated. thank you.


text:
Q: If statement with a string I wanted to make some kind of a clock where it changes the hour depending of the time of the day(am or pm). I use the following code:
#include <stdio.h>

int main() {
    int hour, minute;
    char time[3];
    scanf("%02d:%02d %[^\n]s", &hour, &minute, &time);
    getchar();
    if (time == "am" && hour >= 12) {
        hour - 12;
    } else {
        hour = hour;
    }
    if (time == "pm" && hour < 12) {
        hour + 12;
    } else {
        hour = hour;
    }
    printf("%02d:%02d %s\n", hour, minute, time);

    return 0;
}

If I input 13:00 and the time is am, it should change the hour to 01:00, but it still outputs 13:00 even though its not pm. I think the problem is in the if statement, but I don't know what it is exactly. How do I fix this?

A: There are multiple problems:

*

*The format %[^\n]s is incorrect. There is no s, you should specify the maximum number of characters as 2 and use %2s or %2[^\n], and the destination array should be passed as time or &time[0], but not &time.

*You should store the number of successful conversions and test that at least 2 numbers have been read and whether the am/pm indicator was present.

*if (time == "am" ... is incorrect: you cannot compare strings this way. Use the strcmp() function that returns a negative value if the first argument comes before the second in lexicographical order, 0 if they are the same string, and a positive value otherwhise:
  if (!strcmp(time, "am") ...

!strcmp(time, "am") is the same as strcmp(time, "am") == 0
Here is a modified version:
#include <stdio.h>
#include <string.h>

int main() {
    int hour, minute;
    char time[3];
    int n = scanf("%02d:%02d %2s", &hour, &minute, time);

    if (n < 2) {
        printf("invalid format\n");
    } else {
        if (n == 3) {
            if (!strcmp(time, "am")) {
                if (hour >= 12) {
                    hour -= 12;
                }
            } else
            if (!strcmp(time, "pm")) {
                if (hour < 12) {
                    hour += 12;
                }
            } else {
                printf("invalid indicator: %s\n", time);
            }
        }
        printf("%02d:%02d\n", hour, minute);
    }
    return 0;
}

A: I think the problem here is that you are checking an if time is == "am".
First thing I would do is use a string but never mind you used an array of chars. Second thing how do you check if an array is == with a string.
You must do a for loop to check if the time is equal to "am" or "pm".
Or you can do:
if(time[0]=='a' && time[1]=='m'){
      ....
}

Here you've used 2 if-statements but you don't need 2. Because if the time[...] is not equal to "am" then logically it is "pm", but if you don't trust the user then you must do while loop until the user inputs "am" or "pm".
Hope this helps.


text:
Q: How get the title from php? I know english a little bit, I'm using this service first time.
Ans so I have this code:
    if($curl = curl_init()){
            curl_setopt($curl,CURLOPT_URL, "http://diesel.elcat.kg/index.php?showtopic=134877653");
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
            $out = curl_exec($curl);
            curl_close($curl);

            $tmp = substr($out,strpos($out,'<title>'),56);
            var_dump($tmp);
        }

This code gets the html code:
"string '<title>Как дальше двигаться php? - Diesel Forum</title>
' (length=56)"

I need other code, only title without strings and length.

A: I say you use echo and just do something like <?php echo $title; ?> and then specify title elsewhere where it's needed, like <?php $title = "<title>"; ?>

A: var_dump displays full informations about the variable, use echo instead
    if($curl = curl_init()){
        curl_setopt($curl,CURLOPT_URL, "http://diesel.elcat.kg/index.php?showtopic=134877653");
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
        $out = curl_exec($curl);
        curl_close($curl);

        $tmp = substr($out,strpos($out,'<title>'),56);
        echo($tmp);
    }


text:
Q: Terraform Azure VM Extension failed with too long command for Powershell script execution I am getting below error while executing the Azure VM extension in Terraform for run Powershell script. Could you please help me to solve this error?
Command execution finished, but failed because it returned a non-zero exit code of: '1'. The command had an error output of: 'The command line is too long. '
Here is the protected settings details which is I used
"commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.secvmtf.rendered)}')) | Out-File -filepath hybrid.ps1\" && powershell -ExecutionPolicy Unrestricted -File hybrid.ps1"

A: According to this document the script parameter data can't exceed the size of 256Kb, otherwise it will not be executed.

The script must be base64 encoded. The script can optionally be
gzip'ed. The script setting can be used in public or protected
settings. The maximum size of the script parameter's data is 256 KB.
If the script exceeds this size it will not be executed.

https://github.com/Azure/custom-script-extension-linux/blob/master/README.md#14-script


text:
Q: Npm install not working, after updating node js Error message screenshots
1. Photo
2.Photo
3.Photo
Version of nodejs

A: Based on the screenshots, you are attempting to install the node-sass package.
It's deprecated and, as you can see, depends on a binary module that needs to be compiled separately on Windows using the Visual Studio toolchain.
You have two options:

*

*follow the instructions in the readme to also install the node-gyp prerequisites

*switch your project to use the sass module (recommended).


text:
Q: Typescript how to mix dynamic([key: type]: type) and static typing for an interface Main issue
Not really sure if this is possible, but since i abhor Typescript and it is making my coding hard I figured I'd ask just to make sure.
interface ISomeInterface {
  handler: () => {}
  [key: string]: string
}

Problem obviously is, the handler is a () => {} and not a string, so typescript throws an error. Is it possible to somehow make this work?
Addendum:
While on the topic, this interface is suppose to be consumed by a React.Context and since a requirement of a default value by React.createContext(/* requires default here */), I need to give it a object that matches that interface. When I attempt to pass an object litteral as such:
React.createContext({handler: () => {throw new Error('using default context')}})

Typescript is making a ruckus by saying {handler: () => never} cannot be assigned to {handler: () => {}} any way to make this interface plausible? I tried to make interface implement () => any, still didn't work, it wants explicit never.
Edit #1:
So i've made some changes, namely:
interface IFormContext {
  $handleChange: (key?, val?) => void
  $registerField: (key?) => void
  [key: string]: { value: string } | ((key?, val?) => void)
}

But now when I am trying to access the field like this: const {[key]: { value }} = props which is basically de-structuring with a dynamic key, i get the following error:

Property 'value' does not exist on type '{ value: string; } | ((key?: any, val?: any) => void)'.ts(2339)

A: Unfortunately your named properties must match the index signature.
In this case, since at least one property is a function,  you can use:
[key: string]: string  | Function;
or
[key: string]: any;
Both should work.
For your addendum, () => {} means a function with no arguments that returns a empty object, while the function () => {throw new Error('using default context')} is returning nothing, thus the error.
There is a little bit of confusion with the braces used in types and in the actual function implementation.
A function with the type () => {} is actually something like () => {return {}} or () => ({}).
For a function that returns nothing you can use never or void, but if your handler may return something, you can use something like handler: () => void | boolean, replacing boolean by the type it may return.


text:
Q: constant app memory increase ( IOAccelResource ) I am trying to wrap my mind around an issue (eluded to in this question). The context is: turn-based game, developed with cocos2d version 2.0, obj-c, no ARC, currently prepping an AppStore update to account for some iOS 7 issues (mine, not iOS7).
My own instrumentation, as well as Instruments, show no leaks, no abandoned memory, nothing... flat. This also used to be the case under iOS 4,5,6.1. However, in my test rundown prior to submission, when profiling on device, i see a 1Mb increase per 2 minutes, with the game sitting idle, ie no user interactions whatsoever (see pic below).

The only thing i can see is this IOAccelResource category running amuck between generation capture.

*

*Would you have any suggestions as to what could that be ?

*I cant find much about an IOAccelResource ... can anyone of you point me in the right reading direction ? If this is indeed cocos2d related, i would not mind digging in there, but i dont know where to start looking.

*Also, i would like to run with 'as close to release' a build as possible, and still be able to measure the memory footprint over time. Could you suggest me a method for measuring process size ?
tia.

A: As far as I can tell , this is a bogus (probable instruments bug). When using a 'release' version of the same code base ... ie no debug ... and monitoring the process size (ie no debug process attached to the running process), the memory creep is not there.

A: Educated guess: IOAccelResource could be used by UIAccelerometer. It certainly sounds like an accelerometer I/O kind of thing.
Since UIAccelerometer is deprecated in iOS 7 but still used by cocos2d perhaps there's an issue there Apple didn't catch or care about. Just for testing try to remove any UIAccelerometer reference from cocos2d to see if this goes away. Release builds should not affect Instruments memory monitoring, and an archive build is simply a release build from the code perspective.

A: You could try monitoring allocations using heapshot analysis through Instruments.  That should give you an indication as to where the additional memory is being allocated.  Maybe you've already tried this?

A: The Enable Zombie Objects option on Edit Scheme > Run > Diagnostics can cause this behaviour. Be sure to disable it if you have it enabled.

A: Ricardo has half the answer : zombies objects is part of this. You need both Zombies enabled AND an attached process to get the creep.
In summary :

*

*no zombies, no memory creep.

*with zombies, no debug process attached, no memory creep.

*with zombies, debug process attached, memory creep.


text:
Q: Inject javascript command on webbrowser c# I want to inject this commands on webbrowser.. How I can do it?
oFormObject = document.forms['formid'];
oFormObject.elements["name"].value = 'Some Value';
document.getElementById('formid').submit();

A: You need to read up on ClientScriptManager.RegisterClientScriptBlock.
StringBuilder csText = new StringBuilder();
      csText.Append("<script type=\"text/javascript\"> function DoClick() {");
      csText.Append("Form1.Message.value='Text from client script.'} </");
      csText.Append("script>");
      cs.RegisterClientScriptBlock(csType, csName, csText.ToString());


text:
Q: Encouraging Citations in Answers I've noticed that on several sites there is a variation in the importance of citation within an answer. I find adding citations to answers to be silly due to what I mentioned in this comment here on the English Language and Usage Stack Exchange site.
Should citations be of high or low value on Stack Exchange sites? Should it differ as it does?
The biggest issue I noticed about it was that if a user "moves" from a site that does not encourage, and in fact discourages the use of citations (as they are not considered important or sometimes useful on those sites) (like Stack Overflow), to a site that highly encourages citations, it becomes confusing to the answeree, and (for me at the least) ruined the experience.
Also, by "citation," I do not mean reference to gain further knowledge, I mean reference to support your answer, like it is an argument.

A: You asked:

Should citations be of high or low value on stack exchange sites?
  Should it differ as it does?

I think the answer is that it will depend on the site and its community.
In some sites the community has decided that it wants to engender high academic standards while in others demanding such high standards can be seen as a way to disenchant current and potential users.
I recommend that on any site which you think has unacceptably low/high standards related to citation requirements, you should use that site's Meta to discuss your case.  The standard required by each community you consider posting in should be quickly determinable from their help/on-topic page and a perusal of their recent Q&As.
Some communities may evolve from low to high requirements for citations, while others may do the reverse.  Each site evolves towards the state that meets that community's requirements and direction.
On one site that I moderate (Genealogy & Family History) we currently seem happy for questions to be asked with few citations but when we think more are needed then we simply ask for them using comments.  Using copious citations within our questions can be very valuable for genealogy professionals but doing so at the outset can also make for dry reading and fewer questions from the enthusiastic amateurs (like me) that I think we equally want to attract to keep our community vibrant.

A: I see absolutely nothing wrong with supporting answers.
If you are a non-native speaker and you write an answer on EL&U or ELL, it's best you backup your solution with a reference. The reference confirms your answer.
If you a native speaker, a reference will strengthen further  your answer, and provide the querent the evidence that you know what you're talking about.  Unless you are a fluent speaker and have a sound knowledge of grammar, you cannot test an English language answer in a matter of minutes.
That is why factually correct answers on EL&U and ELL will always be upvoted by experts and enthusiasts, but if the answer is also supported it will probably earn upvotes across the board.
Is there something wrong with that?

A: I actually take issue with that comment. You write

Well, I don't see value in providing references on a forum site (that seems really silly). My answer stays as is (in terms of reference). I see it silly for 2 reasons, A. it's a forum site. Forum site's are ridiculously known for misleading people, so it is absolutely worthless to add reference.

A few specific responses to that:

*

*Stack Exchange is not a forum. We're a network of Q+A sites. Each site's tour states

This site is all about getting answers. It's not a discussion forum. There's no chit-chat.

We do get quite touchy about this.

*Even if we were forums - which we aren't - we don't have a reputation for "misleading people". Stack Overflow, for instance, is extremely popular among programmers and developers worldwide. I come from non-programming Stack Exchange sites, and when I began programming, I was shocked to see just how well-respected SO is. If Stack Exchange was consistently misleading, would this be the case?

*I'm never a fan of the idea that if a ship's sinking, you should give up. Your last sentence seems to suggest that adding citations won't do anything; it would be like bailing out the Titanic with a soup bowl. It's not. It works, on a surprisingly large number of sites - because Stack Exchange isn't a sinking ship. We're not awash in a sea of trash like you might find in, say, Yahoo! Answers. This brings me to Point #4 . . .

*. . . most of the rest of Stack Exchange is not like Stack Overflow. Again, this is my bias from smaller sites speaking, but other topics may require references that a programming question won't. For instance, you can often test code from an answer just by running it. On the other hand, on English Language and Usage (to take the site your comment's on), you can't really test out a word or phrase in the same way. You need to know definitively what it means. But in answer to your question, yes, the necessity (or lack thereof) of citations differs, for reasons such as the one I gave above.

Take my answer in context: I come from sites where citations are either required or strongly encouraged. If I claim, in an answer on Mythology, that Homer described X in the Iliad, I should back that up with a reference to the exact passage. On Astronomy, when presenting results of measurements of the solar wind, I should link to where I got the figures from. So citing sources is, to me, a personal requirement in most cases. I generally don't answer without doing so.
Just take that into account when considering my points. I also hope this didn't come out too harshly; citing sources has always been one of my pet peeves, so to speak.


text:
Q: Where should the file user.clj go? I am trying to setup proto-repl atom-editor package and apparently it needs a file user.clj to exist somewhere - which I guess is some leiningen's init file.
Where should I create this file?

A: Clojure will load the file user.clj from your class path if it is found. In a default leinengen project src/ will be on the class path, so if you create src/user.clj the contents of that file will be loaded in the context of the user namespace.
user is the default namespace for the clojure repl, but some leiningen projects override this. In order to access definitions in user.clj you will need to either pull user into scope (using require or use) or make sure that user is your starting namespace.

A: See the Proto REPL demo project https://github.com/jasongilman/proto-repl-demo/blob/master/dev/user.clj for an example of how to setup user.clj You should also add a dependency on clojure.tools.namespace in the project.clj https://github.com/jasongilman/proto-repl-demo/blob/master/project.clj
I just pushed some changes to Proto REPL last night to improve this area but you'll still benefit from having one setup.

A: According to the proto-repl page, it might use some functions from user namespace when reloading code in REPL (reset function) but it shouldn't be required.
You might want to take a look at the proto-repl demo project to see the more advanced setup.


text:
Q: Using android:layout_weight in Layout Tricks I have referred to this site for Layout Tricks.
Over there one attribute is declared as android:layout_weight="1".
So my confusion is regarding android:layout_weight:

*

*where is the exact use of android:layout_weight ?

*Where should we use android:layout_weight ?

A: From what I understand of layout_weight, the closest comparison I could find is when you pass some % in HTML for the width or height of your div. In our context, the weigth seems to refer to the % of width or heigth your widget should get for itself compared to its neighbours in a given ViewGroup. You can find another exemple with more explanation here.
If you look the way they use it, it sticks exactly to the definition. They give a height of 0dip to keep the whole space free, and then uses equal weigths for the 2 widgets to make same th same height.

A: layout_weight is quite simply a priority to apply to a view class, the higher, the larger the control or group will be in proportion to it's mates inside that group. The default is 0, so a weight of 1 makes it twice as large as other default controls. No mystery.


text:
Q: Display Image entity in XML through webservice(SOAP) using C#? There is an web application, where in it has few entities including image entity.That image is already stored in DB, now i have to access it through webservice and display in XML. Tried converting that image entity to byte[] and as well as String base64. But did not work out. Please help me to resolve this issue. Thanks in advance.

A: Are you facing issue transmitting the image back?
I converted the image to base64 and returned as a string. It is working fine. What issue did you face there.
But this approach requires update on the maxReceivedMessageSize parameters in WCF service as well as the client.

Side effects : There are some issues with increasing
  maxReceivedMessageSize. More memory foot print, might open up DDOS
  attacks.

Service Contract
    public class ImageService : IImageService
    {
        public string GetImageData(string path)
        {
            if (File.Exists(path))
            {
                return ConvertFile(path);
            }
            else
                return string.Empty;
        }

        private string ConvertFile(string path)
        {
            using (Image image = Image.FromFile(path))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    image.Save(m, image.RawFormat);
                    byte[] imageBytes = m.ToArray();

                    // Convert byte[] to Base64 String
                    string base64String = Convert.ToBase64String(imageBytes);
                    return base64String;
                }
            }
        }
    }

Service Configuration
<system.serviceModel>
    <bindings>
      <basicHttpsBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000"
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
            <readerQuotas maxDepth="32"
                 maxArrayLength="200000000"
                 maxStringContentLength="200000000"/>
        </binding>
      </basicHttpsBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

Client Code
    static void Main(string[] args)
    {
        ImageService.ImageServiceClient client = new ImageService.ImageServiceClient();
        string data = client.GetData(@"C:\Users\v-sridve\Pictures\Travel_Error_New.PNG");
    }

Client Configuration
<system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" maxReceivedMessageSize="1000000" maxBufferSize="1000000" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:7541/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IService1" contract="ImageService.IService1"
                name="BasicHttpBinding_IService1"  />
        </client>
    </system.serviceModel>


text: Q: Can I use Stack Overflow usernames in an academic paper? I am writing a paper about Stack Overflow users, and I would like to mention some interesting findings about some users of the SO community. Is it OK to do so? Do I have to ask them personally or should I use an alias or their userID?


text:
Q: PE Executable gets corrupted when adding a new section to it I am trying to add a new section to a portable executable, where I need to write some data, in this case an entire file.
The second file is able to parse itself and read the data from the section I created inside of it, but for some reason, it gets corrupted when I modify it using the code below.
The Imgur links are below: I'm sorry for the bad formatting :(
This messagebox should appear.

But I get this error message instead: "This app cannot run on your pc."

The new section gets added properly inside the PE:

The data inside the new section:

I can't really tell what is wrong here.
#include <iostream>
#include <Windows.h>
#include <ShlObj.h>
#include <Shlwapi.h>

#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "Shlwapi.lib")

DWORD align(DWORD size, DWORD align, DWORD addr) {
    if (!(size % align))
        return addr + size;
    return addr + (size / align + 1) * align;
}

int main(int argc, char* argv[])
{
    if (argc < 3)
    {
        std::cout << "Argomenti insufficienti.\n";
        return 0;
    }

    char PathToSave[MAX_PATH];

    if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_COMMON_DOCUMENTS, NULL, 0, PathToSave)))
    {
        PathAppendA(PathToSave, "Bind.exe");
    }

    HANDLE fOutput = CreateFileA(PathToSave, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, NULL, NULL);         // Unused

    HANDLE FirstFile = CreateFileA(argv[5], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);            // File to read data from
    if (FirstFile == INVALID_HANDLE_VALUE)
    {
        std::cout << "Impossibile aprire il file passato come primo argomento.\n";
        return 0;
    }

    HANDLE SecFile = CreateFileA(argv[5], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);               // File to write the read data in
    if (SecFile == INVALID_HANDLE_VALUE)
    {
        std::cout << "Impossibile aprire il file passato come secondo argomento.\n";
        return 0;
    }

    DWORD FirstFS = GetFileSize(FirstFile, 0);              // First file dimension
    DWORD SecondFS = GetFileSize(SecFile, 0);               // Second file dimension

    BYTE* FirstFB = (BYTE*)VirtualAlloc(NULL, FirstFS, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);           // Allocates memory for the first file
    BYTE* SecondFB = (BYTE*)VirtualAlloc(NULL, SecondFS, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);         // Allocates memory for the second file

    DWORD BytesRead = 0;
    DWORD BytesWritten = 0;

    if (bool Read = ReadFile(FirstFile, FirstFB, FirstFS, &BytesRead, NULL) == FALSE)                   // Reads the first file
    {
        std::cout << "Impossibile leggere primo file.\n";
        return 0;
    }
    else
    {
        std::cout << "Letti " << BytesRead << " dal primo file.\n";
        BytesRead = 0;
    }

    if (bool Read = ReadFile(SecFile, SecondFB, SecondFS, &BytesRead, NULL) == FALSE)                       // Reads the second file
    {
        std::cout << "Impossibile leggere secondo file.\n";
        return 0;
    }
    else
    {
        std::cout << "Letti " << BytesRead << " bytes dal secondo file.\n";
        BytesRead = 0;
    }

    /*
    *
    * The code is problematic beyond this point!
    *
    * SecondFB = Pointer to the second file's data buffer that needs to be modified by adding the new section.
    * FirstFB = Pointer to the first file's data buffer that will be written inside the ".sdata" section.
    * Both of them have been loaded in memory using VirtualAlloc.
    *
    * Ask me anything for further info and many, many thanks :D

    */

    // Here I add a new section to the second file.

    PIMAGE_DOS_HEADER sIDH = (IMAGE_DOS_HEADER*)SecondFB;
    PIMAGE_NT_HEADERS sINH = (IMAGE_NT_HEADERS*)(SecondFB + sIDH->e_lfanew);
    PIMAGE_FILE_HEADER sIFH = (PIMAGE_FILE_HEADER)(SecondFB + sIDH->e_lfanew + sizeof(DWORD));
    PIMAGE_OPTIONAL_HEADER sIOH = (PIMAGE_OPTIONAL_HEADER)(SecondFB + sIDH->e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
    PIMAGE_SECTION_HEADER sISH = (PIMAGE_SECTION_HEADER)(SecondFB + sIDH->e_lfanew + sizeof(IMAGE_NT_HEADERS));

    // Here I name the new section inside the file
    ZeroMemory(sISH, sizeof(IMAGE_SECTION_HEADER));
    CopyMemory(sISH[sIFH->NumberOfSections].Name, ".scode", 8);

    /*
        0xE00000E0 = IMAGE_SCN_MEM_WRITE |
                     IMAGE_SCN_CNT_CODE  |
                     IMAGE_SCN_CNT_UNINITIALIZED_DATA  |
                     IMAGE_SCN_MEM_EXECUTE |
                     IMAGE_SCN_CNT_INITIALIZED_DATA |
                     IMAGE_SCN_MEM_READ

    */

    // Here all the required information gets filled in
    sISH[sIFH->NumberOfSections].VirtualAddress = align(sISH[sIFH->NumberOfSections - 1].Misc.VirtualSize, sIOH->SectionAlignment, sISH[sIFH->NumberOfSections - 1].VirtualAddress);
    sISH[sIFH->NumberOfSections].SizeOfRawData = align(FirstFS, sIOH->SectionAlignment, 0);
    sISH[sIFH->NumberOfSections].Misc.VirtualSize = align(FirstFS, sIOH->SectionAlignment, 0);
    sISH[sIFH->NumberOfSections].PointerToRawData = align(sISH[sIFH->NumberOfSections - 1].SizeOfRawData, sIOH->FileAlignment, sISH[sIFH->NumberOfSections - 1].PointerToRawData);
    sISH[sIFH->NumberOfSections].Characteristics = 0xE00000E0;

    // Here the changes are written to the second file
    SetFilePointer(SecFile, sISH[sIFH->NumberOfSections].PointerToRawData + sISH[sIFH->NumberOfSections].SizeOfRawData, NULL, FILE_BEGIN);
    SetEndOfFile(SecFile);

    sIOH->SizeOfImage = sISH[sIFH->NumberOfSections].VirtualAddress + sISH[sIFH->NumberOfSections].Misc.VirtualSize;
    sIFH->NumberOfSections += 1;
    SetFilePointer(SecFile, 0, NULL, FILE_BEGIN);

    BytesWritten = 0;

    bool W = WriteFile(SecFile, SecondFB, SecondFS, &BytesWritten, NULL);

    if (W == FALSE)
    {
        std::cout << "Impossibile aggiungere sezione alla stub.\n";
        return 0;
    }
    else
    {
        std::cout << "Scritti " << BytesWritten << " bytes nella stub. (Aggiunta nuova sezione.)\n";
        BytesWritten = 0;
    }

    // Here I write the data inside the new section
    SetFilePointer(SecFile, sISH[sIFH->NumberOfSections - 1].PointerToRawData, 0, FILE_BEGIN);
    if (bool Write = WriteFile(SecFile, FirstFB, FirstFS, &BytesWritten, NULL) == FALSE)
    {
        std::cout << "Impossibile aggiungere sezione alla stub.\n";
    }
    else
    {
        std::cout << "Scritti " << BytesWritten << " bytes nella stub.\n";
        BytesWritten = 0;
    }

// Here I close all the handles

    VirtualFree(FirstFB, FirstFS, MEM_RELEASE);
    CloseHandle(FirstFile);

    VirtualFree(SecondFB, SecondFS, MEM_RELEASE);
    CloseHandle(SecFile);

    std::cout << "Binding completato.\n";

    return 0;
}

A: The problem is in ZeroMemory(sISH, sizeof(IMAGE_SECTION_HEADER));
You removed the memory of the first section, which caused problems with the section structure of the exe. This is why the exe cannot run.
Solution:
=> ZeroMemory(&sISH[sIFH->NumberOfSections], sizeof(IMAGE_SECTION_HEADER)); //Clear the memory behind the last section
Don't forget to add FILE_SHARE_WRITE for the first CreateFileA, otherwise it will cause the second CreateFileA to fail to write.
=>  HANDLE FirstFile = CreateFileA(argv[5], GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);            // File to read data from


text:
Q: How Do I Create a Separate Window for my output WITHOUT the usual Windows Title Bar and Scrolling bar I want to display some output in a separate Window but WITHOUT all the usual Windows accoutrements. I don't want a title bar, I don't want a menu of options, I don't want a scroll bars - I just want a simple "frame" with my graphic output sitting within it.
I have been successful in creating a separate window using code like:
nb = CreateDocument[
       Dynamic[pictureWindow], WindowFrame -> "Palette",
       WindowTitle -> None, WindowSize -> {200, 100}];

. . . but this gives me all the (to me, in this instance) extraneous stuff.
How could I generate a new window and control its displayed elements?

A: For the "output" window:
nbout = CreateDocument[{}, WindowFrame -> "ThinFrame",
   WindowElements -> {},
   WindowToolbars -> {}, WindowSize -> Medium,
   WindowMargins -> {{Automatic, 0}, {Automatic, 0}},
   Deployed -> True, ShowCellBracket -> False];

and this will put "output" into this notebook
$Post = Function[expr, SelectionMove[nbout, Previous, Cell];
   NotebookWrite[nbout,
    Cell[BoxData@ToBoxes@expr, "Output",
     CellLabel -> "Out[" <> ToString@$Line <> "]:=",
     ShowCellLabel -> True]]];

Alternatively, you could use Dynamic instead, with
nbout = CreateDocument[{TextCell["Output", "Section"],
    Dynamic[outputCell]}, WindowFrame -> "ThinFrame",
   WindowElements -> {},
   WindowToolbars -> {}, WindowSize -> Medium,
   WindowMargins -> {{Automatic, 0}, {Automatic, 0}},
   Deployed -> True, ShowCellBracket -> False];

and
$Post = ((outputCell = #); Null) &

but the first method could easily be modified to keep a running list of outputs (just change SelectionMove[nbout, Previous, Cell] to SelectionMove[nbout, Next, Cell], and I like having the cell labels.
One could use NotebookClose[nbout] to close the window.


text:
Q: ¿Cómo hacer un nuevo release en GitHub y trabajar en diferentes versiones? Tengo un proyecto en GitHub al cual quiero hacerle cambios pero mantenerlos tambien en su version anterior(es un proyecto de react ahora cambiare algunas cosas para que sea con Redux quiero mantenerlo tambien sin Redux)..  buscando un poco en GitHub veo que se hace a través de releases.
Ya la creé; pero no se como cambiar entre releases, es decir, si quiero modificar mi version 1.0 sin redux o si luego quiero moverme y cambiar mi version 2.0 con redux...
¿Tendre que hacer un nuevo repositorio?

A: Te sugiero que utilices tags:

Como muchos VCSs, Git tiene la habilidad de etiquetar (tag) puntos específicos en la historia como importantes.

Para crear un nuevo tag sobre el commit actual debes usar el siguiente comando:
git tag v1.0.0

Y para publicarlo en, por ejemplo, GitHub debes usar el siguiente comando:
git push origin master --tags

Puedes conocer más sobre las etiquetas en la documentación oficial.

A: puedes intentar creando ramas para trabajar en diferentes versiones
sigue los siguientes pasos
Crea y te cambia a la rama creada

git checkout -b nombrerama

si requieres regresar a la rama master o cambiarte a otra

git checkout master

para fusionar ejemplo a la rama master, primero te posicionas a la rama master y realizas el merge a la rama a ser fusionada

git checkout master
git merge nombrerama

una ves fusionada puedes eliminar la rama si así lo requieres

git branch -d nombrerama

A: Puedes crearte ramas, asi puedes trabajar con comandos.
git branch "release1"
git branch             // lista todas las ramas que tienes
          master
          release1
git checkout release1  // para cambiar a la rama release
git merge master       // para unir los cambios del master en tu rama release1
git push origin release1


text:
Q: Entropy of inverse map for endomorphism case on surfaces Hi,
I know that in the diffeomorphism case the measure entropy of the T:M^{2}-->M^{2} (M smooth Rimannian surface) will be the same as the measure entropy of T^{-1}. But i need to know about the C^{2} endomorphism case. it seems that it can not be true, i want to know, what can be the relation between the entropy of T and its inverse? can we add some conditions which help us that the equality occurs again, maybe?
Thanks,
Pooh

A: I don't see any problems with defining entropy of $T^{-1}$ as it can always be done in a "natural" way by passing to the natural extension (not sure the author meant this, though). However, more important is that the author is apparently not aware of the fact that coincidence of entropies of the inverse and original maps has nothing to do with diffeomorphisms, surfaces etc. and is an absolutely general property.


text:
Q: Python declaring a list of variables without initializing them I need to declare an array of variables to be used later, but without initializing any of the variables inside, is it possible?.
I need this to make a function use easier as i have to perform some mathematical operations on the vector varlist, which is the input of another function.
Can anybody help?
varlist=[]
for i in range(0,10):
 varlistchar="varlist"+str(i+1)
 vl=globals()[varlistchar] #=0.
 varlist.append(vl)

the commented part makes the code functional but doesn't solve my issue.

A: I think it's better to use the index of the list as variable : variable[index]
Or if you want to use named variables... use a Dictionary{key : value} instead of list.

A: remove globals() from the code. globals() is used for calling a global variable inside a function.
varlist=[]
for i in range(0,10):
    varlistchar="varlist"+str(i+1)
    vl = varlistchar
    varlist.append(vl)

print(varlist)

OUTPUT
['varlist1', 'varlist2', 'varlist3', 'varlist4', 'varlist5', 'varlist6', 'varlist7', 'varlist8', 'varlist9', 'varlist10']


text:
Q: Amber Smalltalk Collaboration and Version Control How does version control and collaboration work with Amber?
When I created a new package I saw that three files were created:

*

*js/MyPackage.deploy.js

*js/MyPackage.js

*st/MyPackage.st

Do I need to put all of them under version control?
Can I merge changes into only the .st file and have the Amber server pick them up?

A: First a short explanation of the three files:

*

*st/MyPackage.st: the Smalltalk source also known as fileout

*js/MyPackage.js: the equivalent to the Smalltalk source compiled to JS (including metadata such as Smalltalk sourcecode)

*js/MyPackage.deploy.js: equals the other .js file but does not contain metadata not needed in deployment

To run an Amber application one of the .js files is needed.
Which one depends on the deploy mode but for development the one without .deploy in the name is used.
The .js files in turn can be generated from the .st files using the Amber commandline compiler (e.g. through Grunt.js) or by doing a file-in in the IDE and commiting the relevant package.
In general, we keep all three files under version control but for now the most crucial ones are the .st files since those are usually easier to merge than generated JS code.
However, keeping and merging only the .st files is not sufficient since those are not loadable by Amber.
Nico for example uses a local git hook to recompile the .st files upon pulling the latest changes.
See this message from the Amber mailinglist.


text:
Q: How can I add classpath location by using mojo appassembler plugin while creating batch file I am using appassembler plugin from mojo for creating a runnable batch/shell script for my application. I have to add a particular directory to my classpath, so what changes should I do in my pom.xml configuration for mojo's plugin.
Currently classpath is generated with all required library path in my batch file as below
set CLASSPATH=%BASEDIR%\abc.jar;%REPO%\*.properties

All I need to do is add a separate variable like MY_PATH and add it to the classpath as below
set MY_PATH=%BASEDIR%\resources
set CLASSPATH=%BASEDIR%\abc.jar;%REPO%\*.properties;%MY_PATH%

To add to further there is a tag <configurationDirectory> but that I have already provided for a different directory, now if I have to add further more directory then what would be solution?
How can i achieve it? Below is the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <artifactId>jgcode-framework-parent</artifactId>
    <groupId>com.jaggs</groupId>
    <version>1.0.2</version>
</parent>
<groupId>com.jaggs.server</groupId>
<artifactId>jaggs-code-server</artifactId>
<version>1.0.1-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.4</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.jaggs.password</groupId>
        <artifactId>mypassword</artifactId>
        <version>1.0</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc14</artifactId>
        <version>10.2.0.3</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>appassembler-maven-plugin</artifactId>
            <configuration>
                <repositoryLayout>flat</repositoryLayout>
                <installArtifacts>false</installArtifacts>
                <assembleDirectory>${project.build.directory}/appassembler</assembleDirectory>
                <includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
                <platforms>
                    <platform>windows</platform>
                    <platform>unix</platform>
                </platforms>
                <defaultJvmSettings>
                    <initialMemorySize>256M</initialMemorySize>
                    <maxMemorySize>256M</maxMemorySize>
                </defaultJvmSettings>
                <programs>
                    <program>
                        <name>ManualDataEntry</name>
                        <mainClass>com.jaggs.bean.ManualDataEntry</mainClass>
                    </program>
                </programs>
                <configurationDirectory>\..\..\jaggs\sec\configuration\</configurationDirectory>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>assemble</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <descriptors>
                    <descriptor>src/main/assembly/assemble.xml</descriptor>
                </descriptors>
                <archive>
                    <manifest>
                        <mainClass>com.jaggs.bean.ManualDataEntry</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>/jaggs/sec/configuration/</Class-Path>
                    </manifestEntries>
                </archive>
                <delimiters>
                    <delimiter>${*}</delimiter>
                </delimiters>
            </configuration>
            <executions>
                <execution>
                    <id>my-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>assembly</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <escapeString>\</escapeString>
            </configuration>
        </plugin>
    </plugins>
</build>


text:
Q: Multiple isolated DC-DC converters in series - ground reference question I have a question concerning multiple isolated DC-DC converters in series and ground references.
I need to measure 48 volts from the input of the first DC-DC converter via a voltage divider, and also 24 volts on the output. However my MCU is powered by an LDO (from 12 volts) which uses GND2 as reference, which is totally isolated from GND1 and GND.
Which ground reference is needed on the both voltage dividers?

A: You already have correct answer by @Aaron in the comments. This is just my two cents on the implementation.
The ADC on the source side is probably most cumbersome solution possible. You would need additional power sources for ADC chips and digital isolators. The one questionable benefit of this approach is somewhat higher measurement precision.
Isolation amp is somewhat better, but it is not easy to find isolated amplifiers for so high supply voltages on both sides, not to mention single supply rail capability.
IMHO your best option is to use simple optoisolator circuits. They are much easier to adapt to variety of the source voltages, and by changing their gain you can have two identical ranges on the outputs suitable for Arduino ADC.
The only drawback of this solution is that for better overall precision you need to ensure you are working in the linear range of the particular optoisolator chip, which may result in some non-linearity at the extreme ends of the scale.


text:
Q: Linker error - undefined reference -gcc After running,
 Cygwin-PC ~/code_practice/Computing/list
  $ gcc -c arrayImpl.c -o arrayImpl.o

Code directory structure, in windows(cygwin)
Cygwin-PC ~/code_practice/Computing/stack
$ ls
main.c  stack.h  stackImpl.c

Cygwin-PC ~/code_practice/Computing/list
$ ls
arrayImpl.c  arrayImpl.o  linkedListImpl.c  list.h  main.c

Stack abstraction depends on List abstraction, for data representation & usage.
List abstraction is as shown below,
/************ list.h ************/

/***************** Usage-start ************/
typedef enum{false, true}bool;
typedef enum {CREATE_NEW_LIST, DOUBLE_THE_LIST, HALF_THE_LIST}Op;

#if defined(ARRAY)

  /* To ensure Encapsulation(i.e., maintain invariants of array) */
  typedef struct List List;

#elif defined(LINKED_LIST)

  /* To ensure Encapsulation(i.e., maintain invariants of linked list) */
  /* User will not get access to node*/
  typedef struct List List;

#else
  #error "Wrong list implementation macro name !!!"
#endif

void insertItem(List *, void *newItem);
void *deleteItem(List *, int listIndex);
void *deleteLastItem(List *);

List* createList(List *, Op opType);

/***************** Usage-end ***************/

/***************** arrayImple.c **************/

#if defined(ARRAY)

#include"list.h"

/************ Representation - start ************/
typedef struct List{
  void **array;

  /* Following members for Housekeeping - Array enhancement*/
  int lastItemPosition;
  int size;
}List;

#define INITIAL_LIST_SIZE 50
/********************* Representation - end ************/

/************* Usage - start ***************/
List *createList(List *list, Op opType){

       ....
}

void insertItem(List *arrayList, void *newItem){
            ...
}

void *deleteItem(List *arrayList, int listIndex){
     ....
}

void * deleteLastItem(List *arrayList){
     ...
}
/******************** Usage - end *******************/

#endif

Stack abstraction, is shown below,
/********* stack.h *********/

#include"../list/list.h"

typedef struct Stack Stack;

Stack *createStack();
void push(Stack *, void *item);
void*pop(Stack *);

/*********** stackImpl.c *******/

#include"../list/list.h"

typedef struct Stack{
  List *stack;
}Stack;

Stack* createStack(){

  Stack *s = malloc(sizeof(Stack));
  s->stack = createList((void *)0, CREATE_NEW_LIST);

  return s;
}

void push(Stack *s, void *item){
  insertItem(s->stack, item);
}

void *pop(Stack *s){
  void *item = deleteLastItem(s->stack);
  return item;
}

Below compilation says, with given below message, which does not involve linker,
Cygwin-PC ~/code_practice/Computing/stack
   $ gcc -c -DARRAY main.c stackImpl.c ../list/arrayImpl.o
gcc: warning: ../list/arrayImpl.o: linker input file unused because linking
      not done

Below compilation fails, with given below error,
Cygwin-PC ~/code_practice/Computing/stack
   $ gcc -DARRAY main.c stackImpl.c ../list/arrayImpl.o
/tmp/ccapgYQI.o:stackImpl.c:(.text+0x25): undefined reference to
   `createList'
/tmp/ccapgYQI.o:stackImpl.c:(.text+0x4b): undefined reference to
   `insertItem'
/tmp/ccapgYQI.o:stackImpl.c:(.text+0x61): undefined reference to
   `deleteLastItem'
collect2: error: ld returned 1 exit status

Question,
From above compilation command, Why GNU linker(ld) does not accept ../list/arrayImpl.o file to find the definitions of createList(), insertItem() & deleteLastItem()
Below compilation works,
  Cygwin-PC ~/code_practice/Computing/stack
    $  gcc -DARRAY main.c stackImpl.c ../list/arrayImpl.c

A: gcc -c arrayImpl.c -o arrayImpl.o
That is missing -DARRAY. Without that the code in arrayImpl.c is conditionally removed:
/***************** arrayImple.c **************/

#if defined(ARRAY)

A: this
Cygwin-PC ~/code_practice/Computing/stack
   $ gcc -DARRAY main.c stackImpl.c ../list/arrayImpl.o
/tmp/ccapgYQI.o:stackImpl.c:(.text+0x25): undefined reference to
   `createList'
/tmp/ccapgYQI.o:stackImpl.c:(.text+0x4b): undefined reference to

failed becuase you missed off arrayImpl.c
kaylum has the right answer, when you compiled arrayImpl.c you forgot -DARRAY


text:
Q: how do you make a variable created in ajax, global to the rest of the function I am trying to get some data through the database in jquery. I doing this through ajax, the ajax code returns the value fine. I then set a variable with the data comment.
The comment variable is then used to insert html into an element. However, it would appear that this variable is not set, because it is not being passed through the ajax function. How do I achieve that?
$(document).on('click', '.customer_progress_edit', function(){
   timeline_id = $(this).attr('data-timeline');
    $.ajax({
       type : 'POST',
       url      : '//'+base_url+'/ajax2/timeline-comment.php',
       data : 'timeline_id='+timeline_id,
       success  : function(data) {
           comment = data;
       }
   });
   $('#customer_pop_edit_comment').val(comment);
});

Yes, I am aware I could simply have the html() function within the ajax function, but I have simplified the code to give an easier idea of what I am trying to achieve, there is more to it than just this.

A: try this
var get_data = $.ajax({
type : 'POST',
url  : '//'+base_url+'/ajax2/timeline-comment.php',
data : 'timeline_id='+timeline_id
});
get_data.done(function(html){
    comment = html;
});


text:
Q: How do I use Mockito mock an afterPropertiesSet method that implements an InitializingBean Now I have some other library beans that implement initializingBeans and add some time-consuming methods, but I don't want to actually execute them, I need the Spring environment, but this bean I can mock it to reduce the overall test time, what should I do
This is the pseudo code of the bean of Mock:
public final class TimeoutBean implements InitializingBean, ApplicationContextAware, ApplicationListener {

    @Override
    public void afterPropertiesSet() throws Exception {
        initProc();
    }

    /**
     * init
     */
    public void initProc() {
     //... Something time-consuming and irrelevant to this test
    }
}

And my mock unit test code:
@SpringBootTest(classes = Application.class)
@DelegateTo(SpringJUnit4ClassRunner.class)
public class MockTest {

    @MockBean
    private TimeoutBean timeoutBean;
    @Resource
    private MyRepository myRepository;

    @SneakyThrows
    @Test
    public void test() {
        doNothing().when(timeoutBean).initProc();
        myRepository.getById(1L);
    }

}

In this way, the Mock initProc method is invalid. I can probably understand because @MockBean calls after InitializingBean#afterPropertiesSet. When the afterPropertiesSet is executed, TimeoutBean is not an Mock object, but I don't know how to solve it.

A: Your class TimeoutBean is final and mockito cannot mock final classes. So first you will have to fix that. After that I think it should work. For mocked classes you don't have to tell mockito to doNothing() becease that is the default behaviour for mocks.
I don't understand what you mean with: the Mock initProc method is invalid?


text:
Q: how to map google-ads-api generated keyword ideas with its request keyword? I have multiple keywords for which I am looking for some related keyword ideas along with their metrics. For that, I am using google-ads-api's GenerateKeywordIdeasRequest. It takes a list of keywords, but right now I am passing a single keyword at a time. After that I convert the output into a dataframe and pick the top 3 keywords ideas based on their monthly search volume.
for example: if passed "bottle", it would return

and from there I would extract the top 3 keyword searches suggested for "bottle".
But with this approach, it takes a lot of time to generate ideas for all input keywords. So I tried passing all input keywords at once, which reduce the processing time dramatically but the issue is, I am not able to get the top 3 suggested keyword for each input keyword separately as all suggested keywords ideas for each input are now mixed. And It is hard to tell which is suggested for which passed input.
Here is the code I am using
import pandas as pd
from google.ads.googleads.client import GoogleAdsClient

class GoogleAD:
    def __init__(self):
      pass

    def get_keywords_search_volume(client, customer_id, location_ids, language_id, keyword_texts, page_url= None):
        """function to get keyword search volume from google ads API """
        keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")
        keyword_competition_level_enum = (client.enums.KeywordPlanCompetitionLevelEnum)
        keyword_plan_network = (client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH_AND_PARTNERS)
        location_rns = GoogleAD.map_locations_ids_to_resource_names(client, location_ids)
        language_rn = client.get_service("GoogleAdsService").language_constant_path(language_id)

        # Either keywords or a page_url are required to generate keyword ideas
        # so this raises an error if neither are provided.
        if not (keyword_texts or page_url):
            raise ValueError(
                "At least one of keywords or page URL is required, "
                "but neither was specified."
            )

        # Only one of the fields "url_seed", "keyword_seed", or
        # "keyword_and_url_seed" can be set on the request, depending on whether
        # keywords, a page_url or both were passed to this function.
        request = client.get_type("GenerateKeywordIdeasRequest")
        request.customer_id = customer_id
        request.language = language_rn
        request.geo_target_constants = location_rns
        request.include_adult_keywords = False
        request.keyword_plan_network = keyword_plan_network

        # To generate keyword ideas with only a page_url and no keywords we need
        # to initialize a UrlSeed object with the page_url as the "url" field.
        if not keyword_texts and page_url:
            request.url_seed.url = page_url

        # To generate keyword ideas with only a list of keywords and no page_url
        # we need to initialize a KeywordSeed object and set the "keywords" field
        # to be a list of StringValue objects.
        if keyword_texts and not page_url:
            request.keyword_seed.keywords.extend(keyword_texts)

        # To generate keyword ideas using both a list of keywords and a page_url we
        # need to initialize a KeywordAndUrlSeed object, setting both the "url" and
        # "keywords" fields.
        if keyword_texts and page_url:
            request.keyword_and_url_seed.url = page_url
            request.keyword_and_url_seed.keywords.extend(keyword_texts)

        keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(request=request)

        for idea in keyword_ideas:
            competition_value = idea.keyword_idea_metrics.competition.name
        return keyword_ideas

    def map_locations_ids_to_resource_names(client, location_ids):
            """Converts a list of location IDs to resource names.
            Args:
                client: an initialized GoogleAdsClient instance.
                location_ids: a list of location ID strings.
            Returns:
                a list of resource name strings using the given location IDs.
            """
            build_resource_name = client.get_service(
                "GeoTargetConstantService"
            ).geo_target_constant_path
            return [build_resource_name(location_id) for location_id in location_ids]

    def get_keyword_df(key_word):
        """function to generate dataframe with keyword search volume"""
        try:
            client = GoogleAdsClient.load_from_storage('desc.yaml')
            list_keywords = GoogleAD.get_keywords_search_volume(client, "686xxxxx647", ["2840"], "1000", key_word, None)
            keyword_df = pd.DataFrame()
            for idea in list_keywords:
                keyword_dict = {}
                competition_value = idea.keyword_idea_metrics.competition.name
                idea_text = idea.text
                monthly_search_volume = idea.keyword_idea_metrics.avg_monthly_searches
                keyword_dict['idea_text'] = idea_text
                keyword_dict['monthly_search_volume'] = int(monthly_search_volume)
                keyword_dict['competition_value'] = competition_value
                keyword_dict['key_word'] = key_word
                keyword_dict['key_word_modified'] = key_word.replace('%',' percent')
                keyword_series = pd.Series(keyword_dict)
                keyword_df = keyword_df.append(keyword_series, ignore_index = True)
        except Exception as e:
            print(e)
            # print(e.args[2])
            keyword_df = pd.DataFrame()
        return keyword_df

suggestion_df = GoogleAD.get_keyword_df(['bottle'])

Let me know if there's any more information I can provide.


text:
Q: How to convert from numpy array to file byte object? I read an image file as
with open('abc.jpg', 'rb') as f:
    a = f.read()

On the other hand, I use cv2 to read the same file
b = cv2.imread('abc.jpg', -1)

How to convert b to a directly?
Thanks.

A: Answer to your question:
success, a_numpy = cv2.imencode('.jpg', b)
a = a_numpy.tostring()

Things you should know:
First, type(a) is a binary string, and type(b) is a numpy array. It's easy to convert between those types, since you can make np.array(binary_string) to go from string to numpy, and np_array.tostring() to go from numpy to binary string.
However, a and b represent different things. In the string a, you're reading the JPEG encoded version of the image, and in b you have the decoded image. You can check that len(b.tostring()) is massively larger than len(a). You need to know which one you want to use. Also, keep in mind that each time you encode a JPEG, you will loose some quality.
How to save an image to disk:
Your question looks like you want an encoded binary string. The only use I can imagine for that is dumping it to the disk (or sending it over http?).
To save the image on your disk, you can use
cv2.imwrite('my_file.jpg', b)


text:
Q: Test route and stub a function call within it? Is it possible to stub a function within an Express route using Mocha and Sinon?
Here's the implementation, in ./apps/stuff/controller.js
import db from '../lib/database';

const getStuff = async (req, res) => {
  const results = await db.query(req.id); // I want to stub this
  return res.status(200).json({
    thingy: results.thingy,
    stuff: [
      results.foo,
      results.bar,
    ],
  });
};

export default {
  getStuff,
};

And the Express route for it, in ./routes.js
import stuff from './apps/stuff/controller';
import express from 'express';

const app = express();

app.route('/stuff')
  .get(stuff.getStuff);

So in the test case, I want to stub the call to db.query() and instead return a custom result during the GET /stuff request the test runs.
// ./test/stuff/controller.js
import db from '../../apps/lib/database';

import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../../index';

const { expect } = chai;

chai.use(chaiHttp);

describe('getStuff', () => {
  it('gets you stuff', async () => {
    // I have tried this, but it results in TypeError: Cannot stub non-existent own property query
    // I presume it is creating a new "empty" object instead of stubbing the actual implementation
    sandbox.stub(db, 'query').resolves({ thingy: 'bar', stuff: [ 123, 'wadsofasd' ] });

    chai.request(server)
      .get('/stuff?id=123')
      .then(res => {
        expect(res).to.have.status(200);
        expect(res.body).to.deep.equal({
          thingy: 'bar',
          stuff: [
            123,
            'wadsofasd',
          ]
        });
      });
  });
});

What is the correct way to stub/mock the db.query call in the above scenario? I've been searching online for hours, but haven't come across a single working version of a similar case.

A: Alternative beside using proxyquire is to Avoid using import default
Your db module looks like using export default (it is not exported as symbol) and make sinon couldn't stub it properly.
The solution is using named export
database.js
export function query() {
 // implementation
}

=== OR ===

function query() { .. }

module.exports = {
  query
}

stuff/controller.js
import * as db from '../lib/database'; // alternative => import { query } from '...'

const getStuff = async (req, res) => {
  const results = await db.query(req.id); // I want to stub this
  // ...
};

test/stuff/controller.js
import * as db from '../../apps/lib/database';

// ...

sandbox.stub(db, 'query').resolves({ thingy: 'bar', stuff: [ 123, 'wadsofasd' ] });

Ref:

*

*https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad

*https://basarat.gitbooks.io/typescript/docs/tips/defaultIsBad.html (typescript but the reason still makes sense)

A: Are you tried proxyquire?
Proxyquire is a javascript library to cheat the node.js require so you can pass it a another function (your stub) when then detects require('example/route/of/your/import').
https://github.com/thlorenz/proxyquire
So you can write
    const proxyquire = require('proxyquire');

    proxyquire('./apps/stuff/controller', {
        getStuff: sandbox.stub()
    }


text:
Q: cd: permission denied: binutils-2.21.1 I'm following Tools Used in 6.828 to configure.
$ sudo tar xjf binutils-2.21.1.tar.bz2

generate folder binutils-2.21.1
$ cd binutils-2.21.1
cd: permission denied: binutils-2.21.1
$ sudo cd binutils-2.21.1
sudo: cd: command not found

Permissions of this folder's Properties show me I have Read & Write access.
How could I go into this folder (and build it)?
$ ls -l
drwxrwx--- 18  500  500     4096 Aug 24  2011 binutils-2.21.1
-rw-r--r--  1 root root 18997755 Aug 26  2011 binutils-2.21.1.tar.bz2
drwxr-xr-x 21  500  500     4096 Apr 26 20:40 gcc-4.6.1
-rw-r--r--  1 root root 30117877 Jun 27  2011 gcc-core-4.6.1.tar.bz2
drwxr-xr-x 15 1001 root     4096 Apr 26 21:55 gmp-5.0.2
-rw-r--r--  1 root root  2024576 Apr 26 21:39 gmp-5.0.2.tar.bz2
drwxr-xr-x  6 rahn rahn     4096 Apr 26 22:00 mpc-0.9
-rw-r--r--  1 root root   565953 Jan 19 05:11 mpc-0.9.tar.gz
drwxr-xr-x  9 rahn rahn     4096 Apr 26 21:57 mpfr-3.1.4
-rw-r--r--  1 root root  1279284 Mar  6 21:43 mpfr-3.1.4.tar.bz2

Debian 8.4, zsh

A: cd is builtin command:
$ type cd
cd is a shell builtin

You can't run it via sudo
You can use the following command:
sudo -i


text:
Q: npm install throwing errors The code throws the same error when npm install or npm install --save is called.
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /Users/andyc/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/Users/andyc/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/andyc/.npm/_logs/2021-11-04T02_19_18_554Z-debug.log

any idea why this is happening?

A: It seems you don't have package.json. So, you need to follow these steps, for every new project
Step: 1
npm init --yes

Step: 2
npm i --save 'packagename'

Step: 3 - When you delete and re-install packages by deleting node_modules, run this:
npm i/install


text:
Q: Convert 2D Array to a 3D Space I am trying to develop a 3D cube with values from a flat 2D Plane. I am having a lot of difficulty trying to pseudo code it out so I was hoping to get some input from you guys.
I will try my best to express myself through pictures as I am able to visualize what I am trying to achieve.
I have a 2D output based on the black line in this figure:

I have an array with data of amplitude as each index's value i.e (0; 1) -> the 0 is the x coordinate (sample) and 1 as the y coordinate (amplitude) or as another example (~1900; ~0.25).
How do I take this 1 dimensional sequence and extrude it into a 3D picture like below:

Is there perhaps a library that does such? Or am I going about it the wrong way? The data is from a matched filter output of a sonar signal and I wish to visualize the concentration of the intensity versus where it is located in a sample on a 3D plane. The data has peaks that have inclining and declining gradient slopes before a peak.
I cannot seem to wrap my mind around such a task. Is there a library or a term used to associate what I wish to accomplish?
EDIT: I found this https://www.tutorialspoint.com/matplotlib/matplotlib_3d_surface_plot.htm
But it requires all x, y and z points. Whereas I only have x and y. Additionally I need to be able to access every coordinate (x, y, z) to be able to do range and angle estimation from sample (0, 1) (Transmitted sound where power is highest). I would only like to basically see the top of this though on another 2D axis...
EDIT 2: Following up on a comment below, I would like to convert Figure 1 above into the below image using a library if there exists.

Thanks so much in advanced!


text:
Q: Exec () Creating two different process for FFMPEG I run this command in exec () and it creates two FFMPEG processes one at the same time as the other but with different PID. Is this behavior normal? When I run the code directly in the shell this does not happen.
$ffmpeg = "/home/user/bin/ffmpeg -hide_banner -loglevel verbose -n -i https://sitelink/list.m3u8 -map 0:4 -map 0:5 -acodec copy -bsf:a aac_adtstoasc -vcodec copy video.mp4 1> log.txt  2>&1";

    exec($ffmpeg, $output, $var);

Example of the two processes created
user+ 24414 24413  0 13:42 pts/2    00:00:00 sh -c /home/user/bin/ffmpeg -hide_banner -loglevel verbose -n -i https://sitelink/list.m3u8 -map 0:4 -map 0:5 -acodec copy -bsf:a aac_adtstoasc -vcodec copy video.mp4 1> log.txt  2>&1
user+ 24415 24414  1 13:42 pts/2    00:00:00 /home/user/bin/ffmpeg -hide_banner -loglevel verbose -n -i https://sitelink/list.m3u8 -map 0:4 -map 0:5 -acodec copy -bsf:a aac_adtstoasc -vcodec copy video.mp4

A: Yes, it's normal. exec() executes the command as a shell command, so it has to create a sh process. The shell then forks a child process to run the program.
Some shells will reuse their own process for the last command before exiting, but apparently the shell on your system doesn't do this. The overhead of that extra process is generally negligible, so it's not a big deal.


text:
Q: Save .csv comma overload I'm running a script in VBA to save a table as .csv. Here is the code:
Sub CopyToCSV()
    Dim MyPath As String
    Dim MyFileName As String

    'The path and file names:
    MyPath = Sheets("ControlTAB").Range("B3")
    MyFileName = Sheets("ControlTAB").Range("B5") & Format(Date, "ddmmyy")
    'Makes sure the path name ends with "\":
    If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
    'Makes sure the filename ends with ".csv"
    If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
    'Copies the sheet to a new workbook:
    Sheets("Structure").Copy
    'The new workbook becomes Activeworkbook:
    With ActiveWorkbook
        'Saves the new workbook to given folder / filename:
        .SaveAs Filename:= _
          MyPath & MyFileName, _
          FileFormat:=xlCSV, _
          CreateBackup:=False
        'Closes the file
        .Close False
    End With
End Sub

However, the output gives me:

Global,SET,clLevel,"E,ADMIN",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

How can I tell Excel to dump the unnecessary commas before it writes to the .csv so that when another program opens the .csv it does not get confused by all the commas?
In some cases I find that the code works fine. However when I have run some other scripts on a table it gives me this.
Is there a not NULL value in Excel that is not set on these cells which causes this distorted output?

A: This problem was solved  by only writing the lines which has data in it to the CSV file. First detect the data scope and write only those cells to the csv. Here is the fix:
Sub CopyToCSV()
  ' DEFINE ALL VARIABLES
  ' SETUP FILE NAMES AND PATH

  ' FIND THE SCOPE OR RANGE OF THE DATA
  LastRow = Worksheets("StructureMocXWikiCOMP").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    LastCol = Worksheets("StructureMocXWikiCOMP").Cells.Find(What:="*", After:=Worksheets("StructureMocXWikiCOMP").Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column

  OutputFileNum = FreeFile
  Open MyPath & MyFileName For Output Lock Write As #OutputFileNum
  ' SELECT DATA
  SheetValues = Worksheets("COMP").Range(Worksheets("COMP").Cells(1, 1), Worksheets("COMP").Cells(LastRow, LastCol)).Value
  ReDim LineValues(1 To LastCol)
  For RowNum = 1 To LastRow
    For ColNum = 1 To LastCol
        myString = Trim(SheetValues(RowNum, ColNum))
        If InStr(myString, ",") > 0 Then
            LineValues(ColNum) = SheetValues(RowNum, ColNum)
        End If
    Next
    Line = Join(LineValues, ",")
    Print #OutputFileNum, Line
  Next
  Close OutputFileNum
End Sub