text:
Q: How can I model this power inductor more accurately? I'm running some spice simulations in which I use power inductors. I found one on Aliexpress that seems suitable, but noticed that peak currents in the simulation exceed the rated saturation current by quite a lot.
So, I'm wondering: How can I model this inductor (and more specifically its saturation) as accurately as possible based on assumptions and the limited available specs?
I'd like to model the 330uH/25A variant.
The simulation is currently using just a standard inductor, with an inductance of 330uH and Rser of 14mΩ.
Here's the product page.
Here's a picture and all the electrical information that's given:

(The Chinese text in red says: 'silicon ferromagnetic powder core')

A: Do you know that you need to model the nonlinearity?
Usual progression of model capabilities is something like: inductor (gets the basic dynamics right); inductor with resistance (modeling loss over a modest frequency range); a more complicated RL network to model losses (wire and core losses, accurate over a wider frequency range), RLC networks to model winding self-capacitance or transmission line effects; and nonlinear models including saturation or anything else.
Also, mind that magnetic materials have notoriously complicated behavior, so, while there are quite a lot of effects that are known, that could be modeled (e.g. reduced (initial) permeability at low signal level; hysteresis; Barkhausen noise; etc.), the value that those features bring is less and less, and their omission justified more and more easily.  Or that they can be substituted by average models (like core loss as a resistance, rather than modeling flux and hysteresis).
In particular, we might not be concerned with saturation, from a power supply design standpoint, because we merely need to check that performance is adequate at either extreme (zero or full bias).  Or for signal filtering purposes, we might simply avoid saturation by a sufficient margin, and that ensures adequately low distortion.
So, manufacturers usually supply basic RL or RLC models, if they do at all.  Coilcraft has some of the better resources, but only these (linear RLC) kinds of models.
I have constructed models myself, including nonlinear behavior, for a few components.  Here are two links to my website for a ferrite bead model, fitted to characteristic curves (Laird provides DC bias curves for most of their ferrite beads):
https://seventransistorlabs.com/Modeling/SPICE/MI1206L391R_NL.ckt
Comparison (fine lines: modeled; fuzzy: datasheet):
https://seventransistorlabs.com/Modeling/Images/MI1206L391R_Overlay.jpg
You could use this function as a starting point, though as I recall, getting the fit right was a bit of a pain.  It's probably not the right curve for a gapped ferrite core, but the soft saturation of a powder core might be close enough.  You will need the L(I) curve for it, of course.
This probably isn't too useful if you aren't a SPICE expert already.  Suffice it to say, then, such models are uncommon.
Some other design questions to consider.  If this is a switching converter for example:
Economical:

*

*This is quite a large inductor. Do you really need that much inductance?

*If it's as high power, or voltage, as the inductance might suggest, will it have low enough core losses to even survive?

*If it's being used at quite low frequencies, is that really a good choice?  You will need quite large capacitors to handle the ripple current, too.

*Note that capacitors can be further reduced by using a multi-phase interleave design.

I think it's easier to design a slightly faster, more compact converter, that's lower cost, than to take a (lazy?) way out with oversized components and low switching frequency.  But, obviously, that's my experience talking.  On the other hand, if you lack that experience: you can solve all these problems at small scale, developing your knowledge at low voltages and modest power levels, in relative safety, and then apply it to high voltages or power levels such as this.  (Not that that helps solve whatever immediate project this might be for, unfortunately.)
Control:

*

*You say peak currents are higher, why is that?  Is this a voltage mode control?  (Is this under control at all, or say just a fixed square wave in the simulation?)

*Current mode controls are preferred, precisely for this reason: average or peak current is always regulated, entirely eliminating one failure mode of the converter (switch overcurrent).  There are plenty of other ways to destroy it (overvoltage, overtemp), but eliminating one is huge.

*Average current mode control is likely preferred, given the relatively high core loss of iron powder type cores.  (These are a fine choice for high power levels, where the somewhat increased size might not be as much of an issue as the higher cost of low-loss ferrite parts.)

Or, if this is for filtering, the large value still seems dubious (read: I'm not sure offhand what applications would need this), but earlier comments regarding avoiding saturation may be relevant.  Note that, if it's for filtering mains (like the larger inductors in a line impedance stabilization network (LISN)), mind the peak currents that nonlinear loads can draw (particularly SMPS without power factor correction (PFC)), and what effect that will have on network response with peaky loads.  Input rectifiers can easily draw peak currents over four times RMS, so it adds up quickly for a network like this.

A: You can build a simple saturable core model using an op-amp and a 1-F capacitor as shown by Larry Meares in a paper he published in 1986. The basic circuitry is shown below and mimics saturation effects of an inductor:

The original document was released in IEEE proceedings.
You can also easily build a saturating model with SIMPLIS using the piece-wise linear model they supply:

The picture is coming from a recent seminar I built and you can download it from my webpage.


text:
Q: Showing 2 sheets/panels - one-after-the-other I'm trying to show 2 sheets (panels) one after the other. However, it looks like the first sheet doesn't have enough time to close before the second one shows up - so, it ends up in quite a mess.
Here's my code...
Macros
#define DRK_ALERT_YESNO_SHOW(X,Y,W) \
NSAlert* yesnoAlert = [NSAlert alertWithMessageText:X \
defaultButton:@"Yes" \
alternateButton:@"No" \
otherButton:nil \
informativeTextWithFormat:Y]; \
[yesnoAlert beginSheetModalForWindow:[[NSApp delegate] window] \
modalDelegate:self \
didEndSelector:W \
contextInfo:nil];

// Open File Sheet

#define DRK_OPENFILE_SHEET_BEGIN(X,Y,Z,A) NSOpenPanel *openPanel = [NSOpenPanel openPanel];\
[openPanel setAllowsMultipleSelection: NO];\
[openPanel setCanChooseDirectories:NO];\
[openPanel setCanCreateDirectories:NO];\
[openPanel setCanChooseFiles:YES];\
[openPanel setShowsHiddenFiles:YES];\
[openPanel setPrompt:Y];\
[openPanel setAllowedFileTypes:A];\
[openPanel beginSheetModalForWindow:X completionHandler:^(NSInteger result) {\
    if (result == NSFileHandlingPanelOKButton) {\
        NSString* Z = [openPanel filename];

#define DRK_OPENFILE_SHEET_END }\
}];

Actual code
- (IBAction)openDo:(id)sender {

    DRK_ALERT_YESNO_SHOW(@"Are you sure you want to discard changes?",
                         @"You may lose any changes you have made to your current projects.",
                         @selector(shouldOpenDo:code:context:));

}

- (void)shouldOpenDo:(NSAlert*)alert code:(int)choice context:(void *)context
{
    if (choice==NSAlertDefaultReturn)
    {
        DRK_OPENFILE_SHEET_BEGIN(([[NSApp delegate] window]), @"Open Project", filename,(@[@"txt"]));

        // Yep, we can now open the file: filename

        DRK_OPENFILE_SHEET_END
    }
    else
    {
        // nope, don't open anything
    }
}

Any ideas?

A: OK, so that's all it took :
[[alert window] orderOut:nil];

just before DRK_OPENFILE_SHEET_BEGIN.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenGL doesn't seem to work in my Ubuntu I used to create SFML applications in Windows XP.
When I moved to Ubuntu and set my development environment up, a Segmentation fault error always comes up everytime I compile and run my program. Then I tried to check the OpenGL status by running glxinfo through terminal (as suggested in a website), I got these errors:
root@ubuntu:/# glxinfo
name of display: :0.0
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Error: couldn't find RGB GLX visual or fbconfig

Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0".
3 GLXFBConfigs:
   visual  x  bf lv rg d st colorbuffer ax dp st accumbuffer  ms  cav
 id dep cl sp sz l  ci b ro  r  g  b  a bf th cl  r  g  b  a ns b eat
----------------------------------------------------------------------
Segmentation fault

What should I do?

*

*Ubuntu 10.04 Lucid Lynx

*ATI Radeon 9550

I also have these packages installed:

*

*libgl1-mesa

*libgl1-mesa-glx

*libglu1-mesa

Any kind of help would be appreciated :)

A: You need to install the propreitory fglrx drivers. The Ubuntu Community Documentation page has details on how you can proceed with installing it.

A: Check your /var/log/Xorg.0.log for errors (search for (EE)). If you've installed proprietary drivers before, you could have overwritten your GL libraries. For ATI/AMD cards, the proprietary driver is provided by the fglrx package, nvidia cards use nvidia-current. After uninstallation of these drivers, reinstall the mesa libraries:
sudo apt-get --reinstall install libgl1-mesa-glx

Restart the X server (e.g. by rebooting) and these errors should be gone.

A: FWIW I have a Radeon 9550 on Ubuntu 10.04 as well without the proprietary drivers. Works just fine.
Your error messages suggest something is wrong with your X configuration. Which is weird, since for me it worked out of the box.
What happens if you try to run glxinfo as a regular user rather than root?


text:
Q: Table join and group by in laravel I am working on a API and I am using resource to return the collection. I am having problem in grouping data. I have following code.
return TicketResource::collection(
                Ticket::query()
                    ->search(request('search'))
                    ->whereHas(
                        'latestStatus', function($query) use ($request){
                            $query->whereIn('status_id', $request->status)
                            ->where(function($inner_query) use ($request){
                                if($request->status === 1){
                                   $inner_query->where( 'tickets.user_id', '!=', auth()->user()->id);
                                } elseif($request->status === 2){
                                    $inner_query->where( 'ticket_statuses.user_id', auth()->user()->id);
                                }
                            });
                        }
                    )
                    ->join('ticket_statuses', function($join){
                        $join->on('tickets.id', '=', 'ticket_statuses.ticket_id');
                    })
                    ->where(function ($query) use ($userBrands, $userAppliances, $buyerPurchasedTicket, $buyerexcludedZipCode, $buyerexcludedDevices) {
                        $query->whereIn('appliance_id', $userAppliances);
                        $query->whereIn('brand_id',  $userBrands);
                        // $query->whereNotIn('id', $buyerPurchasedTicket);
                        $query->whereNotIn('brand_id', $buyerexcludedDevices);
                        $query->whereNotIn('zip_code_id', $buyerexcludedZipCode);
                    })
                    ->when($request->filters['brand_ids'], fn ($q) => $q->whereIn('brand_id', $request->filters['brand_ids']))
                    ->when($request->filters['appliance_ids'], fn ($q) => $q->whereIn('appliance_id', $request->filters['appliance_ids']))
                    ->when($request->filters['province_ids'], fn ($q) => $q->whereIn('province_id', $request->filters['province_ids']))
                    ->when($request->price, fn ($q) => $q->whereBetween('price', [$request->min_price, $request->max_price]))

                    ->orderBy('tickets.created_at', $request->order ?? 'desc')
                    ->groupBy('ticket_statuses.status_id')
                    ->paginate($request->rows ?? 30)
                )
            ->response()->getData(true);

When I run the above code I get the following error

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'project.tickets.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select count() as aggregate from (select tickets. from tickets inner join ticket_statuses on tickets.id = ticket_statuses.ticket_id where exists (select * from ticket_statuses inner join (select MAX(ticket_statuses.id) as id_aggregate, ticket_statuses.ticket_id from ticket_statuses group by ticket_statuses.ticket_id) as latestOfMany on latestOfMany.id_aggregate = ticket_statuses.id and latestOfMany.ticket_id = ticket_statuses.ticket_id where tickets.id = ticket_statuses.ticket_id and status_id in (1, 2)) and (appliance_id in (1, 2, 3) and brand_id in (1, 2, 3) and 1 = 1 and 1 = 1) group by ticket_statuses.status_id) as aggregate_table)"

A: In your SQL query, your select list must only contains columns that are either appeared in the GROUP BY clause or aggregated columns.
MySQL enables STRICT mode by default, because there would be many weird cases happened without it. See an explanation of the STRICT mode here.


text:
Q: IOS: check a plist file I have this code: for the simulator to write a NSmutableArray in a plist
 NSString *path = [[NSBundle mainBundle] pathForResource: @"Array" ofType:@"plist"];

if([Array writeToFile:path atomically: YES]){
    NSLog(@"write succesful");}
else {
    NSLog(@"write failed");
}

but how I can check if really the file plist is empty?

A: Although this code works in the iOS Simulator, you will not be able to write into your app bundle on iOS devices.

A: Write the file.
[[NSFileManger defaultManager] createFileAtPath:path contents:plistData withAttributes:attributesDictionary];

Check the file for the array.
NSDictionary *infoDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
if ([infoDictionary count] == expectedIntegerValue) {
  NSLog(@"Success");
  if ([infoDictionary objectForKey:@"ARRAY_KEY"]) {
    NSLog(@"Found the array!");
  } else {
    NSLog(@"No Array Found.");
  }
} else {
  NSLog(@"Fail");
}

if you just want to know if there are any keys [infoDictionary count] > 0.


text:
Q: Solr highlighting to include hyphenated results returned by search Is there a way to get Solr to highlight the match if it includes hyphens?
In the image below, the search was 1600 and Solr highlighted the exact match. However, the search also matched on 16-00 but it was not highlighted. These are product sku's and we're trying to highlight them even if they are hyphenated.
Solr version: 5.2.1
The only setting added was hl.fl below. All the rest are not set and use the Solr defaults:

<requestHandler name="standard" class="solr.StandardRequestHandler" default="true">
    <!-- default values for query parameters -->
     <lst name="defaults">
       <str name="echoParams">explicit</str>
       <str name="hl.fl">summary title </str>

Note: portions of the image were redacted. That is why the results don't line up.


text:
Q: Asp Core net Kendo ui Cannot pass decimal value to model I'm using kendo ui to create a grid on my project. My problem is that i cannot pass a decimal value to my c# class model.
My class:
    public class BlocCoefficientSettings
{
    public int BlocCoefficientKey { get; set; }
    public string BlocName { get; set; }
    public string Category { get; set; }
    public string MinMaxFloor { get; set; }
    public int Rooms { get; set; }
    public decimal CoefficientValue { get; set; }
    public int GroupNumber { get; set; }
}

And this is my code that renders the grid
@section Scripts{
<script>

            function grid_init() {
                var dataSearch = {
                    classifierSearchKey: document.getElementById('classifierSearchKey').value
                }

                if (!dataSearch.classifierSearchKey == "") {

                    var dataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "/BlocCoefficientsSettings?handler=Json",
                                dataType: "json",
                                data: dataSearch
                            },
                            update: {
                                url: "/Common/UpdateBlocCoefficientsSettings",
                                type: "POST",
                                dataType: "json"
                            }
                        },
                        batch: true,
                        sort: [{ field: "groupNumber", dir: "asc" }, { field: "rooms", dir: "asc" }],
                        schema: {
                            data: "results",
                            total: "total",
                            model: {
                                id: "blocCoefficientKey",
                                fields: {
                                    blocName: { editable: false },
                                    rooms: { editable: false, type: "number" },
                                    minMaxFloor: { editable: false },
                                    coefficientValue: { editable: true, type: "number", nullable: true }
                                }
                            },
                        },
                        page: 1,
                        serverPaging: false,
                        group: { field: "category" }
                    });
                    $("#grid").empty();

                    $("#grid").kendoGrid({

                        dataSource: dataSource,
                        editable: true,
                        height: 700,
                        sortable: true,
                        groupable: false,
                        toolbar: [{ name: "save", text: "Сохранить" }],

                        columns: [

                            { field: "blocName", title: "Блок", width: "200px" },
                            { field: "minMaxFloor", title: "Этаж", width: "70px" },
                            { field: "rooms", title: "Комнат", width: "50px" },
                            { field: "coefficientValue", title: "Коэффициент этажности", width: "50px" },
                            { field: "category", hidden: true, groupHeaderTemplate: "Категория недвижимости: #= value #" }
                        ]
                    });
                }
                else {
                    alert("Выберите застройку!");
                }
            }

            $("#btnSearch").click(function () {
                grid_init();
            });

</script>

All works fine when put a whole number in the coefficientValue field. The whole number is passed to my model. But when i put a decimal number to my model is passed 0(In my example the value should be 1.5 for models[1])

How can i pass a decimal number?

A: I'm not sure how you are prompting for a number here, but be careful with culture settings.  JSON does not support comma decimal separation, only point.  Thus, you the JSON being posted has to show the value as 1.5, not 1,5 or it isn't going to parse correctly on server side.


text:
Q: Maven vs. Gradle (scope) / spring-boot JUnit5 I'm currently trying to implement JUnit5 Tests for my spring-boot rest services. I also found a promising tutorial, but I'm running into an error.
Tutorial: https://howtoprogram.xyz/2017/09/12/junit-5-spring-boot-example/
Compared to the tutorial, I'm using Gradle. My gradle looks like this:
dependencies {
    compile "com.google.code.gson:gson:2.8.0"
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
        exclude group: "com.fasterxml.jackson.core"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty")

    compile("io.springfox:springfox-swagger2:2.7.0")

    // reroute default logs
    compile "ch.qos.logback:logback-classic:1.2.3"
    compile "ch.qos.logback:logback-core:1.2.3"
    // json logs:
    compile "net.logstash.logback:logstash-logback-encoder:4.9"

    // junit
    testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0")
    // junit for spring-boot
    testCompile("org.springframework.boot:spring-boot-starter-parent:1.5.7.RELEASE")
    testCompile("org.springframework.boot:spring-boot-starter-test")//:1.5.7.RELEASE")
    {
        // exclude JUnit 4 support
        exclude group: "junit"
    }
    testCompile("org.junit.platform:junit-platform-engine:1.0.0-M5")
    testCompile("org.junit.platform:junit-platform-launcher:1.0.0-M5")
}

I can't find out how to apply Maven script's test to my gradle script.
Also I'm getting these errors when building
/home/udev/prj/research/java-unittest/src/test/java/one/utest/HelloControllerTest.java:6: error: package org.springframework
.test.context.junit.jupiter does not exist
import org.springframework.test.context.junit.jupiter.SpringExtension;
                                                     ^
/home/udev/prj/research/java-unittest/src/test/java/one/utest/HelloControllerTest.java:9: error: cannot find symbol
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
 ^
  symbol: class SpringBootTest
/home/udev/prj/research/java-unittest/src/test/java/one/utest/HelloControllerTest.java:13: error: cannot find symbol
   private TestRestTemplate restTemplate;
           ^
  symbol:   class TestRestTemplate
  location: class HelloControllerTest
/home/udev/prj/research/java-unittest/src/test/java/one/utest/HelloControllerTest.java:8: error: cannot find symbol
@ExtendWith(SpringExtension.class)
            ^
  symbol: class SpringExtension
/home/udev/prj/research/java-unittest/src/test/java/one/utest/HelloControllerTest.java:12: error: cannot find symbol
   @Autowired
    ^
  symbol:   class Autowired
  location: class HelloControllerTest
5 errors
:compileTestJava FAILED

A: Your tutorial talks about spring-boot-starter-parent version 2.0.0.BUILD-SNAPSHOT, but you use version 1.5.7.RELEASE. In that version there is no Junit 5 support yet.
I'm unsure what you mean by Maven script's test, but if you mean the scope test, then in Gradle you just use testCompile or testRuntime to get the same effect.


text:
Q: m.me links on Android do not work I'm struggling to use a referer parameter on a Messenger chatbot m.me link.
I found a documentation mentionning that "The referral parameter is supported in the Messenger web client, as well as the Messenger app for iOS and Android version 92.0 and above". But when I look on Android version 92 does not exist ?
Any idea ? What is wrong ?

A: Seems to work well. Here are two examples in case you're not clear on what is being discussed; they work on pretty much all desktop and mobile platforms including *nix, Android, OSX, iOS, Windows.
1 m.me link with no referral (basic entry to Gabrielle Union Fans bot): https://m.me/gabriellefans
2 m.me link with referral (embedded news story deep link in bot)
http://m.me/Botworx?ref=beIFwSiQH4PpmC896ErcbTjjPzum45vqHXpWS1BgKme6Mk-pFikxQPWq5B5T8CIh3RhTltTdUrWlLRb2mI5RU4hIbx6krpmLAysmT96MlnWtoVBdaRCeJIZ6YmE5dtUlXyyWC9B_YQz5CCxs_fpQ7eN7IL_IdXGxMAxnIdYYuRxuCpU8H0prIIhXMFWfBAed


text:
Q: I am trying to set up Leaflet map by their tutorial but something isn't working, can anyone take a look and see why? I am currently trying to follow the step by step instructions on the Leaflet page on how to set up a basic map but something isn't working for me, the map is not showing up at all. I downloaded the Leaflet-stable release and put all those files in a folder and in it I also created index.html file.
Here is the code I have so far,
This is the HTML file

    <!DOCTYPE html>

    <link rel="stylesheet" href="leaflet.css" />

///The above part comes from the download page from Leaflet.com. They say that if you download the files, the code above is what you should put in the head section///

And this is the .css. file. The instructions say that I have to add this "#mapid { height: 180px; }" in the .css file. Do I simply copy it in like this?
Original .css file that comes with leaflet.
/* required styles */

.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
    position: absolute;
    left: 0;
    top: 0;
    }

My .css file with the #mapid { height: 180px; } code
/* required styles */

#mapid { height: 180px; }

.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
    position: absolute;
    left: 0;
    top: 0;
    }

What am I doing wrong?

A: Hope below code will help you.
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>
    <title>Leaflet, Demo Fazal!</title>


text:
Q: error ORA-00998: must name this expression with a column alias I tried to create table from all_tab_columns but it throws me an error.
like error ORA-00998: must name this expression with a column alias.
i tried to figure it out but not working.
Declare

CURSOR c1 IS

SELECT COLUMN_NAME FROM (select 'standard_hash(MY_NAME) AS MY_NAME' COLUMN_NAME from DUAL
UNION
SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME='TABLE1' AND COLUMN_NAME<>'MY_NAME');

cols  c1%ROWTYPE;
sqlstmt  VARCHAR2(4000);

BEGIN
   OPEN c1;
     LOOP
         FETCH c1 into cols;
         EXIT WHEN c1%NOTFOUND;
         sqlstmt := sqlstmt ||cols.column_name||',';
      END LOOP;
   CLOSE c1;
   sqlstmt := 'CREATE TABLE TABLE2  AS SELECT '||substr(sqlstmt, 1, length(sqlstmt)-1)||' FROM TABLE1';
   DBMS_OUTPUT.PUT_LINE(sqlstmt);
   EXECUTE IMMEDIATE sqlstmt;
   EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('error '||sqlerrm);
END;
/

A: You just have to give the name to the expression as follows:
sqlstmt := 'CREATE TABLE TABLE2  AS SELECT '
           ||substr(sqlstmt, 1, length(sqlstmt)-1)
           ||' as column_name FROM TABLE1'; -- column_name will bre name of the column of new table

As it will become the name of the column of newly created table.

A: I think this can be simplified somewhat.
You don't need to declare an explicit cursor and a record type and fetch each row into it, as this is already built into the language as the Cursor FOR loop construction:
declare
    sqlStmt long := 'create table table2 as select ';
begin
    for r in (
        select 'standard_hash(my_name) as my_name' column_name
        from   dual
        union
        select column_name
        from   all_tab_columns
        where  table_name = 'TABLE1'
        and    column_name <> 'MY_NAME'
    )
    loop
        sqlStmt := sqlStmt || r.column_name || ', ';
    end loop;

    sqlStmt := sqlStmt || rtrim(sqlStmt,', ') || ' from table1';

    dbms_output.put_line(sqlStmt);
    execute immediate sqlStmt;
end;
/

But you can do this without any loop, as the listagg function can already build a comma-separated list for you. It also makes it easier to retain the order of columns in the original table.
declare
    selectList  long;
    sqlStmt     long;
begin
    select listagg(
               case column_name
                   when 'MY_NAME' then 'standard_hash(my_name) as my_name'
                   else lower(column_name)
               end, ', '
           ) within group (order by column_id) as select_list
    into   selectList
    from   user_tab_columns c
    where  c.table_name = 'TABLE1';

    sqlStmt :=
        'create table table2 pctfree 0 nologging parallel as '||chr(10)||
        'select '||selectList||chr(10)||
        'from table1';

    dbms_output.put_line(sqlStmt||';');
    execute immediate sqlstmt;
end;


text:
Q: Using switch statement with UITextfield Int Im am trying to convert UITextfield string into an Integar and then using a switch statement to perform a range check
Already converted the textfield string value into an integer and then implemented the value in the Switch statement
@IBOutlet weak private var load1: UITextField!
    @IBOutlet weak private var load2: UITextField!
    @IBOutlet weak private var load3: UITextField!

    @IBOutlet weak var SS: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

       var number1 = String(Int(load1.text!)!)
        var number2 = String(Int(load2.text!)!)
        var number3 = String(Int(load3.text!)!)

            switch number1 {
        case 10...33:
            print("success")
        case 66...77:
            print("success")
        case 103...109:
            print("success")
        default:
            print("failure")
        }

Getting an error called Expression pattern of type 'ClosedRange' cannot match values of type 'Int?'
This is even though the string value is already converted into a Integer


text:
Q: How to parse number in c#? I want to parse a number with 11 characters.
For example; number is 12345678900
With parse it should be ; 1234 5678 900
How can I do this?

A: Based on your example, you could use the following:
var numString = 12345678900.ToString();
var result1 = Convert.ToInt32(numString.Substring(0, 4)); //1234
var result2 = Convert.ToInt32(numString.Substring(4, 4)); //5678
var result3 = Convert.ToInt32(numString.Substring(8, 3)); //900

A: Something like this would probably work.
int number = 12345678900;
StringBuilder sb = new StringBuilder();
String nums = number.ToString();
char[] numsChar = nums.ToCharArray();

for(int x = 1; x < numsChar.length; x++){
   if(x%4==0)
    sb.Append(numsChar[x-1] + @" ");
   else
    sb.Append(numsChar[x-1]);
}

String parsedNumber = sb.ToString();

A: if you have the string with 11 chars which representing a number
so you can use something like this
string num = "12345678901";
num.ToString("0000 0000");

I am not sure but i think you want to show your number as phone number and easy to remember, so take a look at ToString method specs in MSDN

A: If you are talking about a string containing numeric characters then you can use this:
String.Format("{0:(####) #### ###}", 12345678900); OR
String.Format("{0:(####) #### ###}", txtPhoneNumber.text);

A: Assuming you mean you want the result string "1234 5678 900":
int num = 12345678900;
string numString = num.toString();

string result = String.Format("{0} {1} {2}",numString.SubString(0,4),numString.SubString(4,4),numString.SubString(8,3));

A: You could do:
Value.ToString("N", CultureInfo.InvariantCulture);

And then replace the dot and the comma with spaces. ;-)

A: long numberlong = 12345678900;
string number = numberlong.ToString();
int first = Convert.ToInt32(number.Substring(0, 4));
int second = Convert.ToInt32(number.Substring(4, 4));
int third = Convert.ToInt32(number.Substring(8, 3));
label1.Text = first.ToString() + " " + second.ToString() + " " + third.ToString();


text:
Q: Android studio Webview inside popup Window Hello Member stackover .
I programing app andoid  > i need to show (view ) web page inside popup window
i need to view this page in beatuy design
i used this statement but page not show and popupwindow show very small.
Mainactivity :
  button58.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               FragmentTransaction manger= getSupportFragmentManager().beginTransaction();
                        pop_web_view  pop3 =new pop_web_view();
                        pop3.show(manger,null);

            }
        });

popup window class :
public class pop_web_view extends DialogFragment implements View.OnClickListener{
    View view;
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.web_view, container, false);

         WebView   webView = (WebView) view.findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://www.google.com");

        return view;
    }

A: You should set width and height for dialog
@Override
public void onStart() {
    super.onStart();
    Dialog d = getDialog();
    if (d != null) {
        int width = ViewGroup.LayoutParams.FILL_PARENT;
        int height = ViewGroup.LayoutParams.FILL_PARENT;
        d.getWindow().setLayout(width, height);
    }
}

A:   webView = (WebView) view.findViewById(R.id.webview);
        loadWebViewLoad(webView);

   private void loadWebViewLoad(WebView webview) {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setSupportMultipleWindows(true);
        webview.setWebViewClient(new WebViewClient());
        webview.setWebChromeClient(new WebChromeClient());
        webview.loadUrl(GlobalUrl);
    }


text:
Q: Editing bitmap in memory using C++ I have a two dimensional array of data that I want to display as an image.
The plan goes something like this -
Create a bitmap using CreateCompatibleBitmap (this results in a solid black bitmap and I can display this with no problems)
Edit the pixels of this bitmap to match my data
BitBlt the bitmap to the window
I think that I need a pointer to the place in memory where the pixel data begins. I've tried many different methods of doing this and googled it for 3 days and still haven't been able to even edit a single pixel.
Using a loop of SetPixel(HDC, x, y, Color) to set each pixel works but VERY slowly.
I have accomplished this in C# by locking the bitmap and editing the bits, but I am new to C++ and can't seem to figure out how to do something similar.
I have mostly been trying to use memset(p, value, length)
For "p" I have tried using the handle returned from CreateCompatibleBitmap, the DC for the bitmap, and the DC for the window. I have tried all sorts of values for the value and length.
I'm not sure if this is the right thing to use though.
I don't have to use a bitmap, that's just the only thing I know to do. Actually it would be awesome to find a way to directly change the main window's DC.
I do want to avoid libraries though. I am doing this purely for learning C++.

A: This took QUITE a bit of research so I'll post exactly how it is done for anyone else who may be looking.
This colors every pixel red.
hDC = BeginPaint(hWnd, &Ps);

    const int
        width = 400,
        height = 400,
        size = width * height * 3;
    byte * data;
    data = new byte[size];
    for (int i = 0; i < size; i += 3)
    {
        data[i] = 0;
        data[i + 1] = 0;
        data[i + 2] = 255;
    }

    BITMAPINFOHEADER bmih;
    bmih.biBitCount = 24;
    bmih.biClrImportant = 0;
    bmih.biClrUsed = 0;
    bmih.biCompression = BI_RGB;
    bmih.biWidth = width;
    bmih.biHeight = height;
    bmih.biPlanes = 1;
    bmih.biSize = 40;
    bmih.biSizeImage = size;

    BITMAPINFO bmpi;
    bmpi.bmiHeader = bmih;
    SetDIBitsToDevice(hDC, 0, 0, width, height, 0, 0, 0, height, data, &bmpi, DIB_RGB_COLORS);
    delete[] data;

A: memset can be used on the actually RGB information array (but you need to also know the format of the bitmap, if a pixel has 32 or 24 bits ).
From a bit of research on msdn, it seems that what you want to get is the BITMAP structure :
http://msdn.microsoft.com/en-us/library/k1sf4cx2.aspx
There you have the bmBits on which you can memset.
How to get there from your function ?
Well, CreateCompatibleBitmap returns a HBITMAP structure and it seems you can get BITMAP from HBITMAP with the following code :
BITMAP bmp;
GetObject(hBmp, sizeof(BITMAP), &bmp);

This however seems to get a you copy of the existing bitmap info, which only solves your memset problem (you can now set the bitmap information with memset, eventhou I don't see any other use for memeset besides making the bmp all white or black).
There should be a function that allows you to set the DC bites to a bitmap thou, so you should be able to use the new bitmap as a parameter.


text:
Q: html vertical auto scroll with javascript Im new with pure javascript (well i found its easy to use jquery, but its too bad i cant use jquery in this case :D).
I tried to follow this sample code, but its not working in my web.
This is a screen shoot and explanation of my web :

So, this page is separated into 2 different html file, one for header and its jquery tabs, the other one for the content below the tab.
My plan is to let the content below the jquery tabs scrollable, so the following code is from the html of my content (below the jquery tabs):

top

    <?php echo form_open('backend/index') ?>

        Kelas :
        <?php echo form_dropdown('ddl_kelas1', $list_kelas, 'id="ddl_kelas1"');?> -
        <?php echo form_dropdown('ddl_kelas2', $list_kelas, 'id="ddl_kelas2"');?>

        Nama : <?php echo form_input('txt_nama');?>
        Alamat : <?php echo form_input('txt_alamat');?>
        Tanggal Lahir : <input type="text" id="datepicker" />

        <?php echo form_submit('btn_search', 'Search');?>
    <?php echo form_close(); ?>

    <?php echo $table ?>
    <?php echo $pagination ?>

bottom

Please note that the top and bottom div is just for the page limit (i followed the sample code above).
I have tried another way like change the id/element used for limit, but its still not working.
Thank you for your help :D
Note : i use codeigniter framework for this project :D

A: jQuery
$("html, body").animate({ scrollTop: $('#bottom').offset().top }, 2000);

      ^                                    ^                        ^
What to scroll ---------------------- to which element --------- duration

A: There seemed to be a lot of extra stuff in the bottom of your html screen in fiddle. I took that out and adjusted some of the javascript.
But taking the extra out did the trick already ...
// extra stuff starting at line 332


text:
Q: Chain of responsibility pattern vs Iterating over a list of strategies How does a CoR pattern compare to implementing the items in the chain as a list and having a single orchestrator class try the items in this list sequentially?
Which is a better approach?
Example:
Class A implements NodeInAChain{

NodeInAChain nextNode;

public Result doWork(Request request){
// Some logic
if(logicSuccessful) {
 return;
else
 nextNode.doWork(request);
}
}

Vs
Class ChainOrchestrator {

List<NodeInAChain> nodeList;

public Result doWork(Request request){
foreach(node : nodeList) {
 if(node.doWork(request) == 'success'){
   break;
 }
}
return result;
}

`


text:
Q: VMWare Workstation 16 conflicting with Hyper-V I have a Windows 10 Pro hosting Hyper-V, which has a VM (Windows 10 Enterprise). The VM has VMWare Workstation 16 installed, and I am trying to open an existing VM from a previous Windows 10 laptop.
I get the following error message:

I have followed the same answer steps within this link, but I still get the same message followed by another message, even after multiple reboots.
What I have done more importantly:

*

*Disabled virtual based security

*Amended the reg keys (and imported what was advised)

*Hyper-V is disabled, along with Virtual Platform and Virtualization features

Does something need to be configured within the Hyper-V settings for the Win10 Enterprise VM?


text:
Q: Pure Object oriented or not I just want to know weather java is purely object oriented programming or not, cause we have int, float e.t.c primitive datatypes in java, some people say java is not purely object oriented program, but i know primitive data types also objects of "Class" class.
                               Now here comes my actual question, if primitive data types are also objects of "Class" class then we can not store and retrieve them by using any collection class? when we try to store any primitive type in any collection class why auto boxing taking place? that means as collection Documentation says if we able to store only object not primitive data types in the collection classes then, data types are no more treated as object..!! ??

A: These primitive types have wrapper classes.
int - java.lang.Integer
float - java.lang.Float

This way, you can actually have List<Integer>, etc.

A: I define purity to be the degree of a programming language deviating from purely object-oriented programming, which consists only of objects and message passing. In other words,

*

*Everything is an object.

*All you can do is send a message.

Java is far from pure OO language compared to something like Smalltalk and Self but probably closer compared to C++, so it's a step forward. In Smalltalk for example, creation of an object is done through message passing:
| window |
 window := Window new.
 window label: 'Hello'.
 window open

In modern programming, I think the closer concept to pure OO is Erlang or Akka's actor model. I wrote blog post a while back: what is object-oriented programming?

A: Recommend you to have a look at this post: What's the difference between primitive and reference types?. To answer you original question, Java is not "pure" OO in terms of having primitive types besides the reference types. However, with autoboxing, this is almost transparent for the user of the language.


text:
Q: Linking 2 pages with Razor (WinFormApp) I'm working on a WinFormApp that is using a WebView as my UI (the razor part). I have 2 files that exist in the same directory (Index.razor and Test.razor).
Using HTML, I have setup so list items (Index and Test) that should open the appropriate page when I click on the appropriate item. However, I cannot seem to get this to work. I have tried basic  with no success. I have added the @page tags but this doesn't help. I have also tried using  but this only seems to remove my clickable link.
I feel like I'm missing something obvious, and I'm not sure what. Any guidance would be greatly appreciated.
Here is my Home code(Index.razor). Right now Test.razor just contains a header to show it switched pages:

Index Page

Index

Test

@code {

}


text:
Q: CS0433 error (System.Windows.Markup.IComponentConnector) when running automated build on TeamCity using MSBuild I have a C# assembly project containing a WPF GUI.
When compiling on my development machine, everything works fine.
When I compile it on a TeamCity agent using MSBuild, I get the following error:
error CS0433: The type 'System.Windows.Markup.IComponentConnector' exists in both
'c:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Xaml\v4.0_4.0.0.0__b77a5c561934e089\System.Xaml.dll'
 and 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll'

However, when compiling the project manually in VS2012 on the mentioned build machine, it also works fine.
What may be the issue? Can I resolve it by setting some compiler flags or do I have to rewrite my code in order to get this work with automated builds?
Thanks in advance for any help.

A: It seems I have found a workaround. Changing the buildrunner on teamcity from MSBuild to Visual Studio (sln) resulted in a successful compilation.


text:
Q: RDF avoiding rdfs:subClassOf I have the following RDF:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:ppl="http://www.blah.com/people#">

    <rdfs:Class rdf:ID="Person">
        <ppl:Name/>
        <ppl:LastName/>
    </rdfs:Class>

    <rdfs:Class rdf:ID="John">
        <rdfs:subClassOf rdf:resource="#Person"/>
        <ppl:name>John</ppl:name>
        <ppl:LastName>Smith</ppl:LastName>
    </rdfs:Class>
</rdf:RDF>

This looks fine but I would like to avoid the possibility of doing a subClassOf John.
For instance, this should not work:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:ppl="http://www.blah.com/people2#">

    <rdfs:Class rdf:ID="Person">
        <ppl:Name/>
        <ppl:LastName/>
    </rdfs:Class>

    <rdfs:Class rdf:ID="John">
        <rdfs:subClassOf rdf:resource="#Person"/>
        <ppl:name>John</ppl:name>
        <ppl:LastName>Smith</ppl:LastName>
    </rdfs:Class>

    <rdfs:Class rdf:ID="Peter">
        <rdfs:subClassOf rdf:resource="#John"/>
        <ppl:name>Peter</ppl:name>
        <ppl:LastName>Smith</ppl:LastName>
    </rdfs:Class>
</rdf:RDF>

How may I add that restriction?
EDIT:
After cygri's answer I tried a different approach:
<rdf:Description ID="John">
    <rdf:type rdf:resource="#Person"/>
    <ppl:name>John</ppl:name>
    <ppl:LastName>Smith</ppl:LastName>
</rdf:Description>

<rdf:Description ID="Peter">
    <rdf:type rdf:resource="#John"/>
    <ppl:name>Peter</ppl:name>
    <ppl:LastName>Smith</ppl:LastName>
</rdf:Description>

But this still works :(

A: Not sure what you're trying to do. Your modelling looks weird to me, why is John a class? John should be an individual of type Person. (And you can't have subclasses of individuals, so changing John into an individual answers your question about preventing subclassing too.)
Updated: RDF as such doesn't prevent you from saying nonsensical things. So you can still parse, serialize, and query your data even if it is nonsense. But you can use an OWL consistency checker to validate your ontology. In this particular case, you have to check wether the ontology is in OWL DL. (OWL DL is the variant of OWL that introduces the restriction that individuals can't have subclasses, amongst other things. In OWL Full, this would be allowed, unless you add a constraint that the Class class is disjoint with the Person class.

A: You're still treating John as a class. You want something like this:
<rdf:RDF
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:ppl="http://www.blah.com/people#">

    <rdfs:Class rdf:ID="Person" />

    <rdf:Description rdf:ID="John">
        <rdf:type rdf:resource="#Person"/>
        <ppl:name>John</ppl:name>
        <ppl:LastName>Smith</ppl:LastName>
    </rdf:Description>

</rdf:RDF>

rdfs:subClassOf and rdf:type are different sorts of relationships.
rdfs:subClassOf is useful for stating that, say, all People are Mammals, and all Mammals are Animals.
rdf:type is used for stating that, say, John is a Person (and John is a Mammal and an Animal for that matter).
For what it's worth, semanticoverflow.com is also a good place for asking RDF-related questions.


text:
Q: Angular: refactor cases of a switch statement to components without changing the resulting DOM I am trying to swap out the different cases of a switch statement into components without changing the resulting DOM tree.
Example
I made an example on stackblitz.
As a basis I used the example Dynamic Forms from the angular.io guide.
The Component i want to refactor is DynamicFormQuestion.
The goal is to introduce a new component per question controlType (QuestionDropdownComponent, QuestionTextBoxComponent) without changes to the resulting DOM.
DynamicFormQuestionComponent should still be used as a component for a question of any type.
Original dynamic-form-question.component.html:

  {{question.label}}

    <input *ngSwitchCase="'textbox'" [formControlName]="question.key"
            [id]="question.key" [type]="question.type">

    <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
      <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
    </select>

{{question.label}} is required

New templates
dynamic-form-question.component.html:
<ng-container [ngSwitch]="question.controlType">
    <app-question-textbox *ngSwitchCase="'textbox'" [question]="question" [form]="form"></app-question-textbox>
    <app-question-dropdown *ngSwitchCase="'dropdown'" [question]="question" [form]="form"></app-question-dropdown>
</ng-container>

question-textbox.component.html:

  {{question.label}}
  <input [formControlName]="question.key" [id]="question.key" [type]="question.type">

{{question.label}} is required

question-dropdown.component.html:

    {{question.label}}
    <select [id]="question.key" [formControlName]="question.key">
      <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
  </select>

{{question.label}} is required

This Example works, but the resulting DOM Tree contains the unwanted elements <app-question-textbox> and <app-question-dropdown>.
What is the best solution to get rid of it?

A: This can be done with the help of attribute selector but a single div is required. Can be done as below:
<ng-container [ngSwitch]="question.controlType">

</ng-container>

Rest will be same.


text:
Q: How to fetch the E Mail ID of A contact I am trying to fetch the E Mail address of A Contact.
I found How to get contact email id?     but I could not use this.
I have written following Code to fetch  Email
             Cursor c1;
            c1 = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);

            if(c1==null)
        return;
                    if(c1.getCount() > 0)
            {
                    while(c1.moveToNext())
                    {

                        String id = c1.getString(c1.getColumnIndex(Contacts._ID));
                                                    if(id==null)
                            continue;
                                                    Cursor email_crsr = getContentResolver().query(CommonDataKinds.Email.CONTENT_URI, null, CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                        if(email_crsr!=null)
                              email = phone_crsr.getString(phone_crsr.getColumnIndex(CommonDataKinds.Email.DATA));

      }
    }

I am following Exception :
04-09 10:38:59.487: E/AndroidRuntime(8150): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4


text:
Q: I can not get data from setResult Method while debug shows it has extras ..? I want that from second activity that is ShowActivity when I press back it returns the ArrayList but I cannot get it. In debug setResult() method shows the array but in next point on activityResult data is null why?
 In first activity , onActivityResult data is null.
MainActivity.java:
btnShow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                Intent show=new Intent(MainActivity.this,ShowActivity.class);
                // Create a Bundle and Put Bundle in to it
                Bundle bundleObject = new Bundle();
                bundleObject.putSerializable("key", showImagelist);
                show.putExtras(bundleObject);
                //startActivity(show);
                startActivityForResult(show,COUNTER_ARRAY_LIST);
        }
    });

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==SELECT_IMAGE){
        if(resultCode==RESULT_OK && null!=data){
          for (int i=0,c=0,r=0;i<count;i++,c++){
              if(c==coloumn){
                    c=0;
                    r++;
               }

          }

            ImageUri=data.getData();
            imageItemBin=new ImageItemBin();
            imageItemBin.setImage(ImageUri.toString());
            publicSelectedImage.add(imageItemBin);

            gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
            gridview.setAdapter(gridAdaptor);

        }
    }
    if(requestCode==REQUEST_CAMERA)
    {
        if(resultCode==RESULT_OK && data!=null){
            Bitmap mphoto = (Bitmap) data.getExtras().get("data");

            String stringImage=BitMapToString(mphoto);

            imageItemBin=new ImageItemBin();
            imageItemBin.setImage(stringImage);
            //imageItemBin.setImage(picturePth.toString());
            publicSelectedImage.add(imageItemBin);
            gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
            gridview.setAdapter(gridAdaptor);
            //gridAdaptor.notifyDataSetChanged();

           // tvcounter.setText(counter);
            //publicSelectedImage=selectedImage;
        }
    }
    if(requestCode==COUNTER_ARRAY_LIST){
        //if(resultCode==RESULT_OK && data!=null){
            Bundle bundle=getIntent().getExtras();
            showImagelist=(ArrayList<ImageItemBin>)bundle.getSerializable("BackArrayList");
            int sizeOfArrry=showImagelist.size();
            btnShow.setText("Show ( " + Integer.toString(sizeOfArrry) + " ) ");
            showImagelist.notifyAll();
        //}
    }

}

ShowActivity.java:
 @Override
public void onBackPressed() {
    super.onBackPressed();
    Intent back=new Intent();
    Bundle b=new Bundle();
    b.putSerializable("BackArrayList",showlist1);
    back.putExtras(b);
    //startActivity(back,b);
    setResult(2,back);
    finish();
    //startActivityForResult(back,MainActivity.COUNTER_ARRAY_LIST,b);
}

A: Why the result has to be set before the method super.onBackPressed() gets executed:
Look at the code for the onBackPressed() at grepcode.com
This method would call the method finishAfterTransition(), if no fragments are available on the backstack. In the method finishAfterTransition() you see a call to finish(). So before you set the result in your code, the system moves the activity to state "finished" and setting the result afterwards is ignored.
So you have to ensure that you set the result before the call to super.onBackPressed() in order to be sure that your result gets set before the activity gets finished.


text:
Q: YADCF range send request on both fields filled in Recently we started using datatables and YADCF to show and filter through records. I was wondering if someone managed to make sure the filters with type

range_number

and

range_date

only send a request once both fields are filled? All I could find is the option to add a delay but that's not a great solution in my opinion.

A: That is no possible and I find it more user friendly to allow to filter from certain value / date without forcing user to put a value in the  "TO" value / date
p.s
I'm the yadcf author


text:
Q: Intepretation of $p$-values for a Kolmogorov-Smirnov test I'm using a Kolmogorov-Smirnov test to examine how normal (or Gaussian) some data sets I have are. I am having trouble with interpreting the $p$-values (surprise surprise).
My present understanding is that if the returned $p$-value is $p > 0.05$ this suggests that the data is normally distributed, while datasets which produce a Kolmogorov-Smirnov test result $p < 0.05$ suggest that the data is not normally distributed.
Firstly, is my present understanding/interpretation correct?
Secondly I performed some very basic simulations. I simply generate data sets with $1000$ points which are normally distributed and perform a Kolmogorov-Smirnov test on each one. If I look at the distribution of $p$-values extracted from this, I see a square distribution with values ranging between 0 and 1.
I don't understand this -- I guess I don't really understand $p$-values as I expected for data which definitely is normally distributed (I generated it to be such) that there would be a median $p$-value.

A: You're on the right track. Two facts are key for understanding what's going on.
First, the null hypothesis $(H_\emptyset$) of the one-sample K-S test is that the sample data comes from the "reference" distribution. When it is being used as a normality test, that reference distribution is a Gaussian.
Second, for any test, p-values are uniformly distributed between 0 and 1 under the null hypothesis, assuming the test's assumptions are met. See this question for more details. While you should expect small $p$-values if the alternate hypothesis were true, it is not the case that you should expect only large $p$-values under the null hypothesis.
Combining these two facts accounts for your simulation: you set up conditions where the null hypothesis is definitely true, and the resulting p-values form a "square" histogram where each bin has approximately the same number of values. If you were to draw samples from a different distribution (e.g., an exponential distribution), you would instead find $p$-values clustered near 0, since it is unlikely that those values could have come from a Gaussian (your $H_\emptyset$).


text:
Q: Magento contacts forms with multiple transactional emails templates I want to have more contacts forms in my store and separate transactional emails templates for each contact form in part, for example:

*

*contact_form1.phtml with contact_form1.html email template;

*contact_form2.phtml with contact_form2.html;

*contact_form3.phtml with contact_form3.html;

*....

I need to be like this because I want to have different variable in each email template.
I found this Inchoo tutorial but I don't know how I can add multiple forms and email templates.
Thank you in advance

A: Step 1: Create a module using Sillk Software Silk Software Module Creator
and install the same.

Note: Here i am considering the module called Ewall_EmailTabTamplate

Step 2:  Now do the changes in config.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Ewall_EmailTabTamplate>
      <version>0.1.0</version>
    </Ewall_EmailTabTamplate>
  </modules>
  <frontend>
    <routers>
      <emailtabtamplate>
        <use>standard</use>
          <args>
            <module>Ewall_EmailTabTamplate</module>
            <frontName>emailtabtamplate</frontName>
          </args>
      </emailtabtamplate>
    </routers>
        <layout>
          <updates>
            <emailtabtamplate>
              <file>emailtabtamplate.xml</file>
            </emailtabtamplate>
          </updates>
        </layout>
  </frontend>
  <global>
    <helpers>
      <emailtabtamplate>
        <class>Ewall_EmailTabTamplate_Helper</class>
      </emailtabtamplate>
    </helpers>
    <blocks>
      <emailtabtamplate>
        <class>Ewall_EmailTabTamplate_Block</class>
      </emailtabtamplate>
    </blocks>

    <template>
            <email>
               <sales_email_order_template translate="label" module="sales">
                    ContactForm-1
                    <file>sales/contactForm1.html</file>
                    <type>html</type>
                </sales_email_order_template>
                <sales_email_order_tab_template translate="label" module="sales">
                    ContactForm-2
                    <file>sales/contactForm2.html</file>
                    <type>html</type>
                </sales_email_order_tab_template>
                <sales_order_email_temp_analyzer translate="label" module="sales">
                    ContactForm-3
                    <file>sales/contactForm3.html</file>
                    <type>html</type>
                </sales_order_email_temp_analyzer>
                <sales_email_order_email_temp_cabmaster translate="label" module="sales">
                    ContactForm-4
                    <file>sales/contactForm4.html</file>
                    <type>html</type>
                </sales_email_order_email_temp_cabmaster>
                <sales_email_order_email_temp_cabvision translate="label" module="sales">
                    ContactForm-5
                    <file>sales/contactForm5.html</file>
                    <type>html</type>
                 </sales_email_order_email_temp_cabvision>
            </email>
    </template>

  </global>
</config>

Note: Clear Cache and session after modifying the xml file/s.

Step 3: Create contactForm1.html, contactForm2.html ... in the below path
app/locale/en_US/template/email/sales/contactForm1.html

After html creation has been completed you will be able load the html files in the transaction emails from the admin end.

Login to admin => System => Transactional Emails => Add new template
  => Click on  load template

Screenshot: https://prnt.sc/fsddto
Step 4: Now coming to frontend contact us form in your custom template section
For Example: http://prntscr.com/fsqdri
Please keep the below code in the mentioned path: app/design/frontend/rwd/default/template/emailtabtamplate/index.phtml
<form action="<?php echo $this->getUrl('emailtabtamplate/index/contactForm1'); ?>" id="contactForm1" method="post"
class="scaffold-form">

<?php echo Mage::helper('contacts')->__('Contact Information') ?>

<?php echo Mage::helper('contacts')->__('* Required Fields') ?>

                    *<?php echo Mage::helper('contacts')->__('Name') ?>

                        <input name="name" id="name" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Name')) ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" />

                    *<?php echo Mage::helper('contacts')->__('Email') ?>

                        <input name="email" id="email" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Email')) ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserEmail()) ?>" class="input-text required-entry validate-email" type="email" autocapitalize="off" autocorrect="off" spellcheck="false" />

                <?php echo Mage::helper('contacts')->__('Telephone') ?>

                    <input name="telephone" id="telephone" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Telephone')) ?>" value="" class="input-text" type="tel" />

                *<?php echo Mage::helper('contacts')->__('Comment') ?>

                    <textarea name="comment" id="comment" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Comment')) ?>" class="required-entry input-text" cols="5" rows="3"></textarea>

        <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
        <button type="submit" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Submit')) ?>" class="button"><?php echo Mage::helper('contacts')->__('Submit') ?></button>

</form>

Step 5: Now keep the below code in the index controller and contactForm1Action
app/code/local/Ewall/EmailTabTamplate/controllers/IndexController.php
<?php
class Ewall_EmailTabTamplate_IndexController extends Mage_Core_Controller_Front_Action{

    public function IndexAction() {

      $this->loadLayout();
      $this->getLayout()->getBlock("head")->setTitle($this->__("Titlename"));
            $breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
      $breadcrumbs->addCrumb("home", array(
                "label" => $this->__("Home Page"),
                "title" => $this->__("Home Page"),
                "link"  => Mage::getBaseUrl()
           ));

      $breadcrumbs->addCrumb("titlename", array(
                "label" => $this->__("Titlename"),
                "title" => $this->__("Titlename")
           ));

      $this->renderLayout();

    }

    // contactForm1Action code starts here

    public function contactForm1Action()
    {

         $myParams=$this->getRequest()->getParams();
         $customerName= $myParams['name'];
         $customerEmail= $myParams['email'];
         $telephone = $myParams['telephone'];
         $comment=  $myParams['comment'];

         /*
         $customerName= 'Custom Testing';
         $customerEmail= 'test@test.com';
         $telephone = '123456789';
         $comment='Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged';*/

         $myCustomVars = array('customer_name' =>$customerName,
                        'customer_email'=>$customerEmail,
                        'customer_telephone'=>$telephone,
                        'customer_comment' => $comment
                        );

       $storeId = Mage::app()->getStore()->getId();
       $recepientName = "Custom Tester";
       $templateId = 1; // Template Id from admin end
       $sender  = array(
                        'name' =>   'Custom Tester',
                        'email' => 'customemail@gmail.com'
                    );
       $recepientEmail = 'recepient@gmail.com';
       $translate = Mage::getSingleton('core/translate');
       $mail = Mage::getModel('core/email_template');
       $mail->getMail()->addBCC('bccmail@gmail.com');
       $mail->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $myCustomVars, $storeId);
       $translate->setTranslateInline(true);

       $this->_redirect('emailtabtamplate');//redirect url
       Mage::getSingleton('core/session')->addSuccess('Successfully Sent');

    }
    // contactForm1Action code ends here

    public function contactForm2Action()
    {
        //Keep the code as shown contactForm1Action

    }

    public function contactForm3Action()
    {
         //Keep the code as shown contactForm1Action

    }

}

Step 6: coming to passing custom variables passing to transactional email
Please find the screenshot. http://prntscr.com/fsqpln
We have to use the email variables like as shown below in your contactForm.html (or) related transactional email in the Template Content section
{{var customer_name}}
{{var customer_email}}
{{var customer_telephone}}
{{var customer_comment}}

Output: http://prntscr.com/fsqssw


text:
Q: Not able to commit force.com project to Bitbucket due to specific error I have added a force.com project to eclipse, but when i am trying to push/commit the entire project to bitbucket master branch it's giving me the following specific error -
Following is the project in eclipse -
Then trying to commit the code in Bitbucket using -
Right Click on Project -> Team -> Commit, Its giving me the following error - -
Following is the Error -


text:
Q: Better ways to print out column names when using cx_Oracle Found an example using cx_Oracle, this example shows all the information of Cursor.description.
import cx_Oracle
from pprint import pprint

connection = cx_Oracle.Connection("%s/%s@%s" % (dbuser, dbpasswd, oracle_sid))
cursor = cx_Oracle.Cursor(connection)
sql = "SELECT * FROM your_table"
cursor.execute(sql)
data = cursor.fetchall()
print "(name, type_code, display_size, internal_size, precision, scale, null_ok)"
pprint(cursor.description)
pprint(data)
cursor.close()
connection.close()

What I wanted to see was the list of Cursor.description[0](name), so I changed the code:
import cx_Oracle
import pprint

connection = cx_Oracle.Connection("%s/%s@%s" % (dbuser, dbpasswd, oracle_sid))
cursor = cx_Oracle.Cursor(connection)
sql = "SELECT * FROM your_table"
cursor.execute(sql)
data = cursor.fetchall()
col_names = []
for i in range(0, len(cursor.description)):
    col_names.append(cursor.description[i][0])
pp = pprint.PrettyPrinter(width=1024)
pp.pprint(col_names)
pp.pprint(data)
cursor.close()
connection.close()

I think there will be better ways to print out the names of columns. Please get me alternatives to the Python beginner. :-)

A: The SQLAlchemy source code is a good starting point for robust methods of database introspection. Here is how SQLAlchemy reflects table names from Oracle:
SELECT table_name FROM all_tables
WHERE nvl(tablespace_name, 'no tablespace') NOT IN ('SYSTEM', 'SYSAUX')
AND OWNER = :owner
AND IOT_NAME IS NULL

A: You can use list comprehension as an alternative to get the column names:
col_names = [row[0] for row in cursor.description]
Since cursor.description returns a list of 7-element tuples you can get the 0th element which is a column name.

A: Here the code.
import csv
import sys
import cx_Oracle

db = cx_Oracle.connect('user/pass@host:1521/service_name')
SQL = "select * from dual"
print(SQL)
cursor = db.cursor()
f = open("C:\dual.csv", "w")
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
r = cursor.execute(SQL)

#this takes the column names
col_names = [row[0] for row in cursor.description]
writer.writerow(col_names)

for row in cursor:
   writer.writerow(row)
f.close()


text:
Q: DOS Batch script return code not being returned to caller We have a file1.cmd calling file2.cmd calling file3.cmd.
file3.cmd returns a failure as: exit /b 1
But in file2.cmd we seem to "lose" this failure code.  The %ERRORLEVEL% variable is being listed as 0 instead of 1.
Any ideas?

A: Usual problems that can be found:
Setting the errorlevel variable to a value
set errorlevel=0
echo test | find "x" > nul 2>nul
echo %errorlevel%

Here the errorlevel will be set (the find operation has failed) but the value echoed to console will be 0. errorlevel is a dynamic variable and setting a value to it blocks the access to the dynamic value. errorlevel value should not be set with the set command.
If it is necessary to set errorlevel you can

*

*When leaving the running batch: exit n or exit /b n

*Inside the running batch, without leaving it: cmd /c exit n
in both cases with n the numeric value to set in the errorlevel
To clear the errorlevel you can use: ver>nul
Variable expansion
if 1==1 (
    echo test | find "x" > nul 2>nul
    if %errorlevel%==1 echo failed
)

When the batch parser reaches a line or a block of lines (lines enclosed in parenthesis), it replaces all the read operations on variables with the value inside the variable before execute the line/block. So, if a variable changes its value inside the line/block, the new value can no be retrieved from inside the same line/block. The read operation does not exist, it was replaced with the initial value.
Delayed expansion can be enabled, allowing to change (where needed) the syntax from %var% to !var!, indicating to the parser that the read operation must be delayed until the command executes
setlocal enabledelayedexpansion
if 1==1 (
    echo test | find "x" > nul 2>nul
    if !errorlevel!==1 echo failed
)

But for any of the two previous cases, there is an alternative. The batch language includes a construct to test for errorlevel that is not affected by assigned values or variable expansion
if errorlevel n .....

This construct will be evaluated to true for any errorlevel greater or equal to n. For this reason, when using this construct and testing for different error levels, it is necessary to test for errorlevel from greater to lower values
if errorlevel 3 (
    ....
) else if errorlevel 2 (
    ....
) else if errorlevel 1 (
    ....
) else (
  ....
)

In the cases where the only check is if errorlevel is set or not, this construct can be abreviated using conditional execution
command && ( .... ) || ( .... )

where the commands after the && are executed when the errorlevel is not set, and the commands after || are executed when the errorlevel is set


text:
Q: unexpected end of stream on com.android.okhttp.Address@999f0c7e xamarin Estoy usando System.Net.Http y me genera el siguiente error al hacer una petición al servidor:
unexpected end of stream on com.android.okhttp.Address@999f0c7e.
El error me aparece despues de hacer varias peticiones.
        HttpClient client = new HttpClient();
        try
        {
            var response = await client.PostAsync(url, datos);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string jsonstring = await response.Content.ReadAsStringAsync();
                System.Console.WriteLine("post estatus code ok " + jsonstring);
                return JsonConvert.DeserializeObject<respuesta>(jsonstring);
            }
            else
            {
                var jsonstring = "{ 'errorCode':'500', 'log' : '" + response.StatusCode + "'}";
                Console.WriteLine("post error estatus code" + response.StatusCode);
                return JsonConvert.DeserializeObject<respuesta>(jsonstring);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw e;
           // return default;
        }

A: Ya solucione mi error
    HttpRequestMessage request = new HttpRequestMessage();
        request.RequestUri = new Uri(url);
        request.Method = HttpMethod.Post;
        request.Content =datos;
        request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
        request.Content.Headers.ContentType.CharSet = "UTF-8";
        request.Headers.Add("Connection", "close");
        request.Headers.Add("Accept", "application/json");
        request.Headers.Add("Accept-Encoding", "identity");
        HttpClient client = new HttpClient();
        var response = await client.SendAsync(request);

`


text:
Q: How to use an accounting/currency format for an entire column in shiny renderTable? I am currently experiencing difficulties with trying to format a column in a datatable from renderTable. The table is being rendered from a dataframe that I have defined. That dataframe is then filtered using user input and a subset to form the dataframe that is shown when implementing the output. Is there an easy way to apply an accounting/currency format to one column of the Data table output? I have added code below for reference:
UI:
tableOutput("datetest")

SERVER:
df6 <- data.frame(Account_Num,Account_Num_Spec,Account_Name,Billing_Num,Date,Tran_Type,Transaction_Amt2,Bar_Date, Bar_Month,Trannn)
df6_subset <- reactive({

# # Filter Data By Type "Billed" that need to still be paid
df6$Date <- as.Date(df6$Date, "%m/%d/%Y")
filter1_data <- subset(df6, Tran_Type == "Bill")

# Function to filter between 2 Dates
d <- format(as.Date(input$DI))
d1 <- format(as.Date(as.character(input$DI)) - 60)
d2 <- format(as.Date(as.character(input$DI)) - 30)

filter2_data <- filter1_data[filter1_data$Date >= d1 & filter1_data$Date <= d2,]
filter3_data <- na.omit(filter2_data)

filter4_data <- filter3_data[filter3_data$Billing_Num %in% hold,]

filter5_data <- subset(filter4_data,select = -c(Tran_Type,Bar_Date,Date,Bar_Month,Trannn))

return(filter5_data)

})

output$datetest <- renderTable(df6_subset(), spacing=c("xs"), align = NULL)

A: Lets assume you are making your custom money format function with dollar_format()
Foodollar <- scales::dollar_format(negative_parens = TRUE, prefix = "*@*")
set.seed(49) #just for reproducability

df <- data.frame(Let = LETTERS[1:10], Money=rnorm(10, 1000, 150))
df
#   Let     Money
#1    A  948.5101
#2    B  907.9918
#3    C  746.9616
#4    D  908.0822
#5    E 1011.4537
#6    F  902.0824
#7    G  828.3860
#8    H 1328.9407
#9    I 1059.6365
#10   J  990.0883

df$Money <- Foodollar(df$Money)
df
#   Let       Money
#1    A   *@*948.51
#2    B   *@*907.99
#3    C   *@*746.96
#4    D   *@*908.08
#5    E *@*1,011.45
#6    F   *@*902.08
#7    G   *@*828.39
#8    H *@*1,328.94
#9    I *@*1,059.64
#10   J   *@*990.09

This turns the df$Money vector from a double into a character vector with the format specified by Foodollar
In other words, we make our function with dollar_format and then use that function to redefine the column we want.


text:
Q: Meteor - What is the simplest way to allow a user to configure a Meteor package? I'm writing a Meteor/Meteorite package, and it's working, but many values are hardcoded that should be configurable.
I'd like users to be able to set values inside the package by putting
Package.config({
  setting1: value1,
  setting2: value2,
  ...
})

somewhere in the app code. I'd then read those values in the package with something like PackageConfig.setting1, PackageConfig.setting2, etc.
What's a good, simple way to do this? The packages I've looked at for examples seem a bit complex, and I wonder if that's necessary.

A: Here is a simple google maps package of mine which provides a similar design pattern you're asking for :
client/lib/google-maps.js :
GoogleMaps={
  // public methods
  config:function(options){
    _.extend(this,options);
  },
  ready:function(){
    this._loadingDependency.depend();
    return this._ready;
  },
  // private methods
  _loaded:function(){
    this._ready=true;
    this._loadingDependency.changed();
  },
  // public members
  apiKey:"",
  // private members
  _ready:false,
  _loadingDependency:new Deps.Dependency()
};

_googleMapsLoaded=function(){
  GoogleMaps._loaded();
};

Meteor.startup(function(){
  if(!GoogleMaps.apiKey){
    throw new Meteor.Error(-1,"API key not set, use GoogleMaps.config({apiKey:YOUR_API_KEY});");
  }
  $.getScript("https://maps.googleapis.com/maps/api/js?key="+GoogleMaps.apiKey+"&callback=_googleMapsLoaded");
});

package.js (WARNING, Meteor < 0.9 packages API, expect breaking changes in a near future)
Package.describe({
  summary:"Google Maps packaged for Meteor."
});

Package.on_use(function(api){
  api.use(["jquery","deps"],"client");
  //
  api.add_files([
    "client/lib/google-maps.js"
  ],"client");
  //
  api.export(["GoogleMaps","_googleMapsLoaded"],"client");
});

So basically it's a simple package that allows the user to specify its own google API key client side via this call : GoogleMaps.config(...);
When the maps API is fully loaded we get a notification via a reactive ready method.
I'm using a traditional OOP programming style to differentiate between what the package exposes and what is private to the implementation.
The package only exports a top level public object (GoogleMaps) which is configurable via a public interface.
You can then reference GoogleMaps.apiKey in the package implementation just as you requested.


text:
Q: Appending a List and Recursion (Hamming Distance) - Python 3 I'm supposed to write a program that takes a string of binary code and a number, and outputs all the strings within that hamming distance of the original string. I have a function that does everything, but in the output there are lists within lists. I understand why this is - the function is recursive, and sometimes it will return a list of possible values.
The problem is, I don't know how to change it so it outputs complete strings. For example, for a string of "0000" and hamming distance "2", I get:
["1['100', '010', '001']", "01['10', '01']", "001['1']"]
But what I want is:
1100
1010
1001
0110
0101
0011

Code is below:
def hamming(num, dist):
    if dist == 0:
        return num
    else:
        outputlist = list()
        for item in range(len(num)):
            if len(num[item:]) > dist - 1:
                if num[item] == "0":
                    restoflist = hamming(num[item + 1:], dist - 1)
                    outputlist.append(num[:item] + "1" + str(restoflist))
                else:
                    restoflist = hamming(num[item + 1:], dist - 1)
                    outputlist.append(num[:item] + "0" + str(restoflist))
        return outputlist

A: If you loop through the list that is returned by hamming you should be able to append the strings together the right way - like this:
def hamming(num, dist):
    if dist == 0:
        return num
    else:
        outputlist = list()
        for item in range(len(num)):
            if len(num[item:]) > dist - 1:
                if num[item] == "0":
                    restoflist = hamming(num[item + 1:], dist - 1)
                    if type(restoflist) is not str
                        for rest in restoflist:
                            outputlist.append(num[:item] + "1" + str(rest))
                    else
                        outputlist.append(num[:item] + "1" + str(restoflist))
                else:
                    restoflist = hamming(num[item + 1:], dist - 1)
                    if type(restoflist) is not str
                        for rest in restoflist:
                            outputlist.append(num[:item] + "0" + str(rest))
                    else
                        outputlist.append(num[:item] + "0" + str(restoflist))
    return outputlist

A: You can fix it by returning [num] rather that num in the base case, and in a general case, combine results from recursive calls using map and extend rather than append:
def hamming(num, dist):
    if dist == 0:
        return [num]
    else:
        outputlist = list()
        for item in range(len(num)):
            if len(num[item:]) > dist - 1:
                if num[item] == "0":
                    restoflist = hamming(num[item + 1:], dist - 1)
                    outputlist.extend(map(lambda x: num[:item] + "1" + x, restoflist))
                else:
                    restoflist = hamming(num[item + 1:], dist - 1)
                    outputlist.extend(map(lambda x: num[:item] + "0" + x, restoflist))
        return outputlist

>>> hamming('0000', 2)
['1100', '1010', '1001', '0110', '0101', '0011']
>>>


text:
Q: Uncaught TypeError: Object # has no method 'writeFile' I'm using Ionic framework that at it's heart is AngularJS and I'm trying to save a file to the device's storage. This code works in creating the pdf:
return $q(function(resolve, reject) {
            var dd = createDocumentDefinition(invoice);
            var pdf = pdfMake.createPdf(dd);

            pdf.getBase64(function (output) {
                resolve(base64ToUint8Array(output));
            });
        });

Now I'm trying to save the pdf using:
return $q(function (resolve, reject) {
                var dd = createDocumentDefinition(invoice);
                var pdf = pdfMake.createPdf(dd);

                //For download Android
                var pdf = pdfMake.createPdf(dd).getBuffer(function (buffer) {

                var utf8 = new Uint8Array(buffer); // Convert to UTF-8...

                binaryArray = utf8.buffer; // Convert to Binary...

                $cordovaFile.writeFile(cordova.file.externalApplicationStorageDirectory, "example.pdf", binaryArray, true) //This saves to device storage

                .then(function (success) {

                console.log("pdf created");

                }, function (error) {

                console.log("error");

              });

              });
          });

The main area the first few lines of converting is where I believe the problem is coming from but I don't seem to be able to fix it, I keet getting whenever the device tries to save:
Uncaught TypeError: Object #<Object> has no method 'writeFile'

What is the solution please?

A: Are you sure that the cordova file plugin is installed?  Keep in mind that you need to install the file plugin to use $cordovaFile.  Run the following command in your project directory...
cordova plugin add cordova-plugin-file

Sometimes you will need to remove and re-add the platform that you are building against when you add plugins.  If you add the plugin and still have trouble try to remove and then add the platform
cordova platform rm android
ionic platform add android

http://ngcordova.com/docs/plugins/file/


text:
Q: I can't figure out why my js script isn't actually navigating to another page by using querySelector() I have a queryselector in my script which is set to match a singular element on a page which is a "Next" button. Normally when the user clicks this button it would take them to the next question. I have confirmed that the selector is working by using firefox dev edition's instant evaluation and have used basic console.log statements to make sure my script was making it to where the queryselector would be evaluating to the button. For whatever reason though, even if I delete EVERY other button on the page, the .click() function for that button still navigates the browser to a page other than the one that the next button brings the user to every time I have run it as a single line outside of my program.
this is the element I am matching to:
<button type="submit" class="btn submit_button quiz_submit btn-secondary" id="submit_quiz_button" data-action="">
      Submit Quiz
    </button>`

this is the selector I'm using
document.querySelector("div#questions.assessing div.button-container input#last_question_id+button.Button.submit_button.next-question")


text:
Q: Cannot launch Internet Explorer with WebDriverJs in Selenium I followed the directions at this link: https://code.google.com/p/selenium/wiki/WebDriverJs and was able to get Chrome running.  I tried changing this line:
var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
   build();
to:
var driver = new webdriver.Builder().
   withCapabilities({'browserName':'internet explorer'}).
   build();

I started my node with:
java -jar selenium-server-standalone-2.42.1.jar -ro
le node  -hub http://localhost:4444/grid/register -Dwebddriver.ie.driver=IEDrive
rServer -browser browserName="internet explorer"
and it continues to open in Chrome.  I'm using IE11 and I know there are some issues with IE11 but I followed the work around with the zone settings and registry key.  I cannot seem to even get the browser to launch.
Other info:
Using Windows 8.1 browser IE11

A: You need to make 2 updates
1 - Update your capabilities
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.ie()).build();

2 - Update your ie.driver location in your node. At least, I see you missed ".exe" in the end of your driver configuration
Here's mine:
start java -jar selenium-server-standalone-2.42.2.jar -role node -hub http://localhost:4444/grid/register -nodeConfig node.json -Dwebdriver.chrome.driver="../res/chromedriver.exe" -Dwebdriver.ie.driver="../res/Iedriver.exe" -Dphantomjs.binary.path="../res/phantomjs.exe"

Good luck

A: As of Selenium version v.2.45.0, it now has native support for IE (which mean we dont need to install Selenium stand alone server. All you need to do is install the newest version of Selenium and turn on Internet Explorer protective mode for all zone.
Link to Selenium change log: https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/CHANGES.md


text:
Q: How to use grep to count no of files in which the given string appears atleast once? Using the command below i could find the total occurrences of the given string in the current directory.
cat * | grep -c 'nike'

In the same way, how to get the total count of files in which the given keyword appears atleast once?
Thanks a bunch

A: grep -l Nike * | wc -l
Don't use cat.

A: grep -l prints only file names
grep -l 'nike' * | wc -l

A: use grep with wc and -l option is for lines.
grep -R "pattern" .|wc -l


text:
Q: Trouble installing Tk module for perl using CPAN I am trying to install the Tk module in Strawberry Perl using  cpan install Tk, but I get the following error message.
Loading internal logger. Log::Log4perl recommended for better logging
Reading '\c\Users\Pravi\.cpan\Metadata'
  Database was generated on Mon, 18 May 2020 17:55:59 GMT
Running install for module 'Tk'
CPAN: Digest::SHA loaded ok (v6.02)
CPAN: Compress::Zlib loaded ok (v2.09)
Checksum for \c\Users\Pravi\.cpan\sources\authors\id\S\SR\SREZIC\Tk-804.035.tar.gz ok
The system cannot find the path specified.
Uncompressed \c\Users\Pravi\.cpan\sources\authors\id\S\SR\SREZIC\Tk-804.035.tar.gz successfully
Using Tar:/usr/bin/tar xf "Tk-804.035.tar":
The system cannot find the path specified.
Couldn't untar Tk-804.035.tar: child exited with value 1
CPAN: YAML loaded ok (v1.29)
  SREZIC/Tk-804.035.tar.gz
  Had problems unarchiving. Please build manually

I am confused by the "System cannot find the path specified" and am wondering how I can fix this issue.
Tk installation with CPAN
I have tried following the steps here but it looks like this for ActivePerl and NOT Strawberry Perl.


text:
Q: Is there any alternative option(GUI) for resizing disk partitions? I want to resize my disk partition in my device but the applications like disks and Gparted is not working.
So is there any GUI alternative for Resizing and Re-allocating memory of our Physical disks?
As you can see the minimum and maximum size is the same so we cannot resize


text:
Q: Arraylist.Contains Doesn't Return True VB.NET comps.Contains doesn't return TRUE even though comps contains it.
I debugged it step by step and I can't see where the problem is.
By the way the purpose of the code is to show the pairs that sum up to SUM value. (If the sum is 5 and theres 1 and 4 then the code should return 1 and 4)
Public Function getPairs(ByVal array As ArrayList, ByVal sum As Integer)
    Dim comps, pairs As New ArrayList
    For index = 0 To array.Count - 1
        If (comps.Contains(array(index)) = True) Then
            pairs.Add(array(index))
        Else
            comps.Add(sum - array(index))
        End If
    Next
    Return pairs
End Function

Sub Main()
    ' 1,3,2,5,46,6,7,4
    ' k = 5
    'Dim arraylist As New ArrayList()
    Console.Write("Enter your array :")
    Dim arraylist As New ArrayList
    arraylist.AddRange(Console.ReadLine().Split(","))
    Console.Write("Enter the sum:")
    Dim sum As Integer = Console.ReadLine()
    getPairs(arraylist, sum)
    Console.ReadKey()
End Sub

A: The ArrayList you populate from user input contains strings (results from splitting the user input string). The comps ArrayList contains integers (results from subtraction). When it tries to find the string "2" in the ArrayList that contains a 2, it fails.
You should convert your user input to integers so that you are comparing the same data types.

A: First, turn on Option Strict. Tools Menu -> Options -> Projects and Solutions -> VB Defaults. This will point out problems with your code and help you to avoid runtime errors.
ArrayList is not used much in new code but is around for backward compatibility. List(Of T) is a better choice for new code.
Module Module1
    Sub Main()
        ' 1,3,2,5,46,6,7,4
        ' k = 5
        'Dim arraylist As New ArrayList()
        Console.Write("Enter your array :")
        Dim arraylist As New ArrayList
        'Option Strict would not allow this line to compile
        '.Split takes a Char, the same c tells the compiler that "," is a Char
        arraylist.AddRange(Console.ReadLine().Split(","c))
        Console.Write("Enter the sum:")
        'Option Strict would not allow a string to be dumped into an integer
        Dim sum As Integer
        Dim Pairs As New ArrayList
        If Integer.TryParse(Console.ReadLine, sum) Then
            'Your Function returns an array list but you
            'throw it away by not setting up a variable to receive it
            Pairs = getPairs(arraylist, sum)
        Else
            Console.WriteLine("Program aborted. Sum was not a number.")
        End If
        For Each item In Pairs
            Console.WriteLine(item)
        Next
        Console.ReadKey()
    End Sub
    'Functions need a return data type in the declaration
    Public Function getPairs(ByVal array As ArrayList, ByVal sum As Integer) As ArrayList
        Dim comps, pairs As New ArrayList
        For index = 0 To array.Count - 1
            'I don't see how this can ever be true since comps is empty
            If comps.Contains(array(index)) Then 'Since .Contains returns a Boolean, no = True is necessary
                pairs.Add(array(index))
            Else
                'Ideally each item in array should be tested to see if it is a number
                'You will get an exception if CInt fails
                comps.Add(sum - CInt(array(index)))
                'You never use the comps ArrayList
            End If
        Next
        'The pairs ArrayList is empty
        Return pairs
    End Function
End Module

I don't see how this code could accomplish what you describe as your goal. I think you should start again. Talk through how you would accomplish your task. Then write it out on paper, not in code. Then you will see more clearly how to code your project.

A: The big problem is the original code is this line:
Dim comps, pairs As New ArrayList

That code creates two ArrayList reference variables, but only one ArrayList object. comps remains null/Nothing.
But beyond that, the ArrayList type has been dead since .Net 2.0 came out back in 2005... more than 10 years now. It only exists today for backwards compatibility with old code. Don't use it!
This is better practice, especially in conjunction with Option Strict and Option Infer:
Public Function getPairs(ByVal items As IEnumerable(Of Integer), ByVal sum As Integer) As IEnumerable(Of Integer)
    Dim comps As New HashSet(Of Integer)()
    Dim result As New List(Of Integer)()

    For Each item As Integer In items
        If Not comps.Add(item) Then
           result.Add(sum - item)
        End If
    Next
    Return result
End Function

Sub Main()
    Console.Write("Enter your array: ")
    Dim input As String = Console.ReadLine()

    Dim list As List(Of Integer) = input.Split(",").Select(Function(item) CInt(item)).ToList()

    Console.Write("Enter the sum: ")
    Dim sum As Integer = CInt(Console.ReadLine())

    Dim pairs = getPairs(list, sum).Select(Function(s) s.ToString())
    Console.WriteLine("Pairs are: {0}", String.Join(", " pairs))

    Console.ReadKey()
End Sub


text:
Q: Unit testing FTPWebRequest/FTpWebResponse How would you unit test FTPWebRequest and FTPWebResponse through MOQ.

A: You can't mock FTPWebRequest or FTPWebResponse with Moq, because it only allows you to mock interfaces or abstract classes. And it doesn't look like MS was thinking about testability when they wrote most of the System.Net namespace. That's the primary reason I've moved away from Moq to RhinoMocks.
You'll need to build your own FTPWeb* objects and pass them to your handler.

A: Not possible with Mock also because FTPWebResponse doesn't have constructors exposed to allow something to be derived from it.
Here is how I wrote my test in similar situation.
Method under test: ExceptionContainsFileNotFound(Exception ex)
contains following logic:
if (ex is WebException)
{
    var response = (ex as WebException).Response;
    if (response is FtpWebResponse)
    {
        if ((response as FtpWebResponse).StatusCode == FtpFileNotFoundStatus)
        {
            return true;
        }
    }
}

In order to test it I implemented quick trick.
try
{
    var request = WebRequest.Create("ftp://notexistingfptsite/");
    request.Method = WebRequestMethods.Ftp.ListDirectory;

    request.GetResponse();
}
catch (WebException e)
{
    // trick :)
    classUnderTest.FtpFileNotFoundStatus = FtpStatusCode.Undefined;

    var fileNotFoundStatus = classUnderTest.ExceptionContainsFileNotFound(e);

    Assert.That(fileNotFoundStatus, Is.True);
}

(Of course FtpFileNotFoundStatus is not exposed to the World.)

A: For that i use Rhino frameWork.
It can handle instance creation even if there is no public constructor, read only properties and more.
Example:
var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);


text:
Q: why atmoicinteger (incrementAndGet) returns new value in every new restful (stateless) service call Restful is stateless, so how does it maintain its previous value during subsequent new service calls. i think stateless means no state will be maintained by server
Even though we have cache-control=nocache in header
(i implement this tutorial: https://spring.io/guides/gs/rest-service/)

A:
Restful is stateless, so how does it maintain its previous value during subsequent new service calls.

Stateless, in the context of REST, means something precise -- and not what you are thinking.
As with most questions about the REST architectural style, Roy Fielding's thesis is the place to look.  In chapter 5, he writes

each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

I recommend comparing HTTP with FTP, to get a sense of the difference between stateless and stateful requests.

i think stateless means no state will be maintained by server

"Resources" have state -- see Fielding on Resource and Resource Identifiers and Representations.
A different idea is that the web server is segmented into two parts that can be scaled independently - stateless compute and a stable storage appliance (aka a database).  That kind of separation isn't mandated by REST -- part of the point of rest is that the implementation details of the server are not constrained beyond the requirement that they support the uniform interface.