text:
Q: Get all elements like myself in jQuery? Lets say I have this structure ( no classes , no Id's):  - it's a location finding question
The d[0,1,2] are pure divs . no class no id.
div (d0) wrapps a repeating structure like :

And let's say I have $(this) as the first d1
Is there any traverse function , method , solution for getting the other 2 d1 ? ( or all d1's.it doesn't matter..)
I'll prase it with words :

I'm $(this)=d1. I have a parent ( which is d2 , can be more ....this is just for my  sample) which has a parent
  (d3 ) and  hence, I have 2 more exact elements like me.

how can I get them ? JSBIN
edit
Maybe I wasn't clear but I don't have to know the structure. I just have $(this) and it should find by itself other twins relative to d0 ( as same as its position)
so it should be something like :
function getLikeMyself(objWhichIsThis , contextDivElement)
{
}

execute : getLikeMyself(theDivWhishIsThis, divElemtnWhichIs_d0)

A: This is my new try, a .me() method that will return you the selector of the current element built up until the body.
$.fn.me = function(){
  return this.first().parentsUntil("body").andSelf().map(function(){
    return this.tagName;
  }).get().join(">");
};

Usage:
var selector = $(this).me();
var $twins = $(selector);

See it here.

An alternative version that accepts a root element as an argument:
$.fn.me = function(root){
  return this.first().parentsUntil(root).andSelf().map(function(){
    return this.tagName;
  }).get().join(">");
};

Usage:
var selector = $(this).me("#root");
var $twins = $(selector, "#root");

See it here.

A third version that keeps the relative position of the descendants of the topmost element under the root element. For example, it will return DIV>DIV:nth-child(1)>SPAN:nth-child(2) instead of a generic DIV>DIV>SPAN selector.
$.fn.me = function(root){
  return this.first().parentsUntil(root).andSelf().map(function(){
    var eq = i ? ":nth-child(" + ($(this).index() + 1) + ")" : "";
    return this.tagName + eq;
  }).get().join(">");
};

Usage:
var selector = $(this).me("#root");
var $twins = $(selector, "#root");

A: You can iterate over each parent node and descend into their corresponding siblings, using the path that was built up on the way down:
var chain = [$('#imthis').prop('nodeName')];

$('#imthis')
  .parentsUntil('body')
  .each(function() {
    // i'm a parent
    $(this).siblings()
      .find(chain.join('>'))
    .each(function() {
      alert(this.textContent);
    });
    chain.unshift(this.nodeName);
  });

Demo

A: You could use a recursive function to "bubble up" the DOM until you reach the body element, then reverse this tree and use it as a selector. A little like:
function getChain(el){

    var parents = arguments[1] || [el.nodeName.toLowerCase()];

    if (el.parentNode.nodeName != 'BODY'){

        parents.push(el.parentNode.nodeName.toLowerCase());
        el = el.parentNode;

        return getChain(el, parents);

    } else {

        return parents.reverse().join('>');

    }

}

See a demo fiddle


text:
Q: How to process the csv file with 60000 rows and write in h2 database? I have a csv file with 60000 lines. i like to read and process the file and write in h2 database.
The problem is ,it had only processed the first 1000 rows. How to overcome this problem ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: vue.js watch array variable within v-repeat I am trying to watch a variable within an array that is bound to a repeating element using v-repeat but it doesnt seem to be working. There is a fiddle here
My HTML looks something like this

        <select v-model="hour">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

          {{ $data | json }}

and the vue js like this
new Vue({
        el: '#test',
        data: {
            details: [
                {
                    hour: 2,
                    changeThis: null
                },
                {
                    hour: 3,
                    changeThis: null
                }
            ],
        },
        watch: {
            'details': function (val, oldVal) {
                alert()
            },
        }
})

The binding to the hour properties is working fine, but I cannot get the watch to fire. I have also tried deep: true but that doesnt work either. If I define my watch as
watch: {
    'details[0].hour'

then I can get it to work, but as I dont know how many details I will have then I dont really want to do this for each one. What I ideally want to do is get a reference to the array item that is being updated and then go from there. I could possibly achieve what I want by adding a
v-on="change:someVar(detail)"

to the select element and doing it that way but I'm curious as to why the approach I am trying does not work.
Edit
It is actually possible to return the full array by using the deep watcher as @kishanterry notes below (thank you for that), I had overlooked this syntax in the docs.. However it still doesn't quite give the solution I was hoping for
// deep watcher
    'c': {
      handler: function (val, oldVal) { /* ... */ },
      deep: true
    }

A: Try this
new Vue({
 el: '#test',
 data: {
  details: [{
    hour: 2,
    changeThis: null
   },
   {
    hour: 3,
    changeThis: null
   }
  ],
 },
 watch: {
  details: {
   handler: function(val, oldVal) {
    alert('')
   },
   deep: true
  }
 }
})

It is working if I replace it in your js fiddle.I think it is what you need.
Js Fiddle Link


text:
Q: Button onClick event firing on page load I have an xpage in which I added a button.  The button has an Action Group and other actions following.
For some reason, the event is firing on page load.  I do not have any page load events.  The button is a core control, not the dojo button.
<xp:button id="button1" value="Approve Receiving Sheet"
    style="font-family:Arial;font-size:9pt;font-style:italic;width:180.0px"
    styleClass="button1">
<xp:eventHandler event="onclick" submit="true"  refreshMode="complete"
     immediate="false" save="true"><xp:this.action><xp:actionGroup>
<xp:this.condition>
 <![CDATA[#{javascript:var lookup = document1.getDocument().getUniversalID()
 var checkInvoices:string
 checkInvoices = @DbLookup("", "(Invoices by RS UNID)", lookup, 2)
 var returnValue = @If(@Implode(checkInvoices) == "", false, true)
 if(returnValue == false)
 {
    var x="alert('msg to user');"
    view.postScript(x)
    return false
 }

 return true}]]></xp:this.condition><xp:confirm>

Other actions follow conditional action.  Changing button from button to submit doesn't do anything.  The postscript message was showing up for true or false, which is why I moved it into an if statement.  Thanks in advance, Steve

A: EDIT: My first answer was not correct! Here is the second one:
The condition will be calculated as soon as one of the actions in the actionGroup are invoked. This means that as long as there is "nothing to do", your condition will not be executed.
But you have added a confirmation action: This type of action generates a CSJS code block, and checks the condition of the action group before it gets rendered (aka send to the browser). That's why your CSJS alert is executed.
P.S.
If you are clicking the action multiple times and set the condition to false, the confirmation message will apear anyway. This seems to be a bug.


text:
Q: what is the value of an uninitialized static char in c? The default value of an uninitialized static int is zero. What about if the datatype is a char?
#include<stdio.h>

int main()
{
    static char i;
    printf("%c", i);
    return 0;
}

This program executes without giving any output - why?

A: In your example, i is default initialized to zero, and when you output that as a character using printf with the %c format you are outputting the null character \0, which is why you don't see anything.
If you wanted to see the numerical value, you should use printf("%i", (int)i)

A: In C static variables are auto initialized.

*

*If it's of integer number type, like int, etc… It will be initialized to 0.

*If it is of floating number type like float, etc... It will be initialized to 0.0.

*If it's of char type then it will be initialized with null character, \0.

*If it's of pointer type it will get it's default value as  NULL


text:
Q: How to pass generically scoped suspend lambda to class method in Kotlin? Want to have a function inside an open class which can accept a suspend lambda and run it.
I know this works when you specify the type explicitly but if possible need it to accept generically scoped lambdas.
class ChildClass : SuperClass() {

    // does work :)
    fun launch(block: suspend ChildClass.() -> Unit) =
        coroutineThing { this.block() }

}

open class SuperClass {

    // doesn't work :(
    fun <T : SuperClass> launch(block: suspend T.() -> Unit) =
        coroutineThing { this.block() }

}

The error I am getting is Expression 'block' of type 'suspend T.() -> Unit' cannot be invoked as a function. The function 'invoke()' is not found.
Edit:
Looking to eventually call this method from an instance of the ChildClass like this: ChildClass().launch { doStuff() }

A: You can write like this but I don't know how it works :) For me, it looks like Kotlin issue.
open class SuperClass {
    fun <T : SuperClass> launch(block: suspend T.() -> Unit) =
        coroutineThing { block.invoke(this as T) }
}

but in that case you have to invoke it like this:
ChildClass().launch<ChildClass> { println("test") }

but you can change it a bit to invoke it like you want:
open class SuperClass<T : SuperClass<T>> {
    fun launch(block: suspend T.() -> Unit) =
        coroutineThing { block.invoke(this as T) }
}

class ChildClass : SuperClass<ChildClass>()

//invokation
ChildClass().launch { println("test") }

A: How about this ?
open class SuperClass {

    fun<T: SuperClass> launch(superClass: T, block: suspend T.() -> Unit) {
        GlobalScope.launch {
            superClass.block()
        }
    }

}

open class ChildClass: SuperClass() {
    suspend fun print() {

    }
}

fun test () {
    val a = ChildClass()
    a.apply {
        launch(this) {
            print()
        }
    }
}


text:
Q: Create similar iOS apps reusing almost everything (with Xcode) I want to make multiple apps which share the same structure and code, but have different images, fonts, names and urls.
I would like a simple way to make this apps without replicating the whole project, so that when I find a bug I'll have to correct it only once.
Thank you.
PS: It isn't important the language (Objective-C or Swift)

A: Create multiple targets within the same project. You can then include or exclude asset catalogues, configuration JSON files etc. on a per-target basis. If you're consistent with the names this should get you most of the way there. You can also look at target-specific build flags or constants.


text:
Q: Numpy Arange generating values of inconsistent decimal points Can someone explain me what's happening here?
Why is there more decimal points for 0.3 and 0.7 values.
I just want 1 decimal point values.
threshold_range = np.arange(0.1,1,0.1)
threshold_range.tolist()

[Output]: [0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7000000000000001, 0.8, 0.9]

A: Use np.round
Ex.
import numpy as np

threshold_range = np.arange(0.1,1,0.1)
print(threshold_range.tolist())
print(np.round(threshold_range, 2).tolist())

O/P:
[0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7000000000000001, 0.8, 0.9]
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

A: Solution: You can simply use round function:
threshold_range = np.arange(0.1,1,0.1).round(1)
threshold_range.tolist() # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Reason of error: I think it has to do with floating point precision ;)


text:
Q: Can't pass 'greater than' or 'less than' operators in reportFilters via url I have a lightning component that redirects to a custom report passing filters via url. This component is working inside a community and, as far as I know, you need to generate your url with a 'reportFilters' url parameter.
This parameter is an encoded string based on a JSON with this structure:
[
{'operator' : 'equals',
 'value' : value,
 'column' : columnName},
{...}
]
The point is that if I try putting an operator different from 'equals' it tells me that kind of value for operator doesn't exist although is referenced in salesforce documentation (https://help.salesforce.com/articleView?id=filter_operators.htm&type=5).
Does anyone know how can I implement this or if it's a salesforce limitation?
EDIT
The fields that need to have this operator are datetime fields parsed as String (CreatedDate and LastModifiedDate). Maybe I need to pass them as date values instead of string?

A: You should actually use greaterthan or lessthan. You also have lessthanorequal and greaterthanorequal. You cannot use > or < directly because that implies starting or ending of tag. Also you should not really use == as a best practice. Instead you should be using equals.
In Expression Functions Reference, you will find all the function names that can be used.

NOTE
If you need < or > in value, you can set it in javscript controller.
Example:
cmp:
<aura:attribute name="myUrl" type="String" default="" />

<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

{!myUrl}

JS:
doInit : function (component, event, helper) {
    component.set("v.myUrl", "https://www.some.url.with_>_and_<_works_Fine_Here");
},

A: I just find out that the issue was with the operator value declaration. It needs to be 'greaterThan' and 'lessThan' instead of 'greaterthan' and 'lessthan' although sf documentation doesn't say so.


text:
Q: How can Interactive Grid region be refreshed when region display selector changes in Oracle Apex? I have three regions named Order Taken, Order Process and order Completed. Each of the regions are based on Interactive Grid and each regions set to on as region display selector.
Now, when I updated order-status of 481 order-no to taken-order-status(0) in order process region, then i want to show the changes occur in taken-order region.
More simply, I just wants refreshed data every-time only when i changes/switches region or changes region display selector.

A: Probably the easiest way would be to hide the Save buttons on the individual Interactive Grids (IGs) and instead have a page button called Save that submits the page.  This will cause all IGs to be processed and the page to be reloaded, so all IGs will be up to date.

A: Have you tried adding dynamic actions on region display selector? You can refresh the region when that region is clicked on the region display selector.

*

*Create a dynamic action on region display sector - on click event on the region. One dynamic action for each region.

*Create a refresh action under true. and select the same region to refreshed as one clicked.
Does that help your case?

A: Put the below code in the Function and Global Variable Decleration Section
$('.apex-rds').data('onRegionChange', function(mode,activeTab) {
                if ((activeTab.href === "#REGION_STATIC_ID")){
                    apex.region(activeTab.href.replace("#","")).refresh();
                }
        });

NOTE: Replace REGION_STATIC_ID with the static id of your region.


text:
Q: Using numpy.fill with Numba 'nopython' mode I am trying to use numpy fill function to fill up values in an ndarray. I have this under a function using Numba and I get an attribute error. Here is an example of my code:
@jit(nopython=True)
def computething(param1):
    x = np.sum(param1)
    x1 = np.zeros(10)
    x1.fill(x)

*Note this is only an example code.
And I get the following error:
UntypedAttributeError: Unknown attribute 'fill' of type array(float64, 1d, C)

How can this error be prevented? thank you!

A: A possible solution that works is:
@jit(nopython=True)
def computething(param1):
    x = np.sum(param1)
    x1 = np.zeros(10)
    x1[:] = x

The numpy fill function however still gives an attribute error when nopython=True is set. It works ok with nopython=False.


text:
Q: Data flowing from Google Sheets to Slack Channel and asking for approval I am trying to create a flow in which whenever I receive a leave approval request in a google form, it goes straight to my slack channel (I should be able to define what all I want to show in the slack channel from that google form response), wherein I am given two buttons "Approved" and "Rejected", and upon clicking on any of those two buttons, "Approved" or "Rejected" gets pasted in front of that request in the google response sheet in a new column.
What I've been able to do till now is send the message to slack for every new response in the format I want but without the Approve or Reject buttons. I haven't been able to figure out a way to bring my response (Approve or Reject) back to the google sheet in the row of that request.
I tried to look everywhere but I could not find integration between google script and slack with buttons. Any help would be greatly appreciated.


text:
Q: How do I comment out a block of javascript code mixed with server tags Say I have this piece of javascript/jQuery code and I want to comment out the marked code block.
<script>

function checkValues() {
    // Important function
}

$(document).ready(function () {

    $(".item").click(function () {
        // Important action
    });

    /* I want to comment this block out, from here...
     $("#<%=Application("InstID")%>").blur(function () {

     });
     $("#<%=Application("ComID")%>").blur(function () {

     });
    ...to here */
});
</script>

But the server tags won't allow a regular comment block with /* comment */. Is there another way to make a code block in this case?
Visual studio won't recognize the Ctrl+K+C either.

A: You can wrap them with the comment block of <%-- --%>:
$(document).ready(function () {

    $(".item").click(function () {
        // Important action
    });

    <%--
    $("#<%=Application("InstID")%>").blur(function () {

    });
    $("#<%=Application("ComID")%>").blur(function () {

    });
    --%>
});


text:
Q: Where do I find proguard.cfg in my project? I want to enable the ProGuard for my application and in this documentation ProGuard it says that the proguard.cfg, where I have to modify something, is automatically generated. But if I look in my project folder I only see a proguard-project.txt file but I dont see the proguard.cfg which I need.
How can I get this proguard.cfg? Or was I'm doing wrong?
Please guid me to this file.

A: The documentation is slightly inaccurate. The generated file is proguard-project.txt and will be in the root directory of your project.
To enable Proguard, you will need to ignore the "do not modify" warning in project.properties and uncomment the following line:
     proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

The Android tool chain will sometimes make changes to project.properties, but your Proguard path will be preserved.

A: From this you can get your right way:
Proguard.cfg Missing
i am searching for default.properties file for missing proguard.cfg
proguard.cfg file missing
android studio - proguard.cfg file is missing


text:
Q: iOS Using different splash screen when opened from remote notification? I have launch screen that is storyboard launch file. And when i start my app it is shown. But now i want to add when i open my app from remote notification to show different splash. In notification payload it is possible to specify field launch image. And i have specified image.
But even though i specify my launch image, the default launch image is shown, the one from storyboard launch. Is it possible to do this, to have a different launch images, if i use launch storyboard file?

A: It's not possible until current version ,iOS9.
Besides,you can only get your remote notification after
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions being called when you launch your app.


text:
Q: CAML Query at a time how many OR Conditions we can use? I was retrieving data from sharepoint list. When my query was less that time no issues to display the data. But more than 300 or conditions invloved in that query exception is coming "value does not fall within the expected range"
 SPList olistLegal = oWeb.Lists.TryGetList("TestList");
                                        SPQuery LEoquery = new SPQuery();

                                        LEoquery.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + Legalentityname + "</Value></Eq></Where>";
                                        // SPListItemCollection oItemLegalentitycoll = olistLegal.GetItems(LEoquery);
                                        foreach (SPListItem oItemLegalentitycoll in olistLegal.GetItems(LEoquery))
                                        {
                                            string contractid = Convert.ToString(oItemLegalentitycoll["ContractID"]);
                                            if (string.IsNullOrEmpty(LegalEntityquery) == true)
                                            {
                                                LegalEntityquery = "<Eq><FieldRef Name='ContractID' /><Value Type='Text'>" + contractid + "</Value></Eq>";
                                            }

                                            else
                                            {
                                                LegalEntityquery = "<Or>" + LegalEntityquery + "<Eq><FieldRef Name='ContractID' /><Value Type='Text'>" + contractid + "</Value></Eq></Or>";
                                            }
                                        }

i was receiving this error in my webpart.

A: Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group.


text:
Q: Telegraf: "replyWithInvoice" isn't available for "callback_query::" I have a callback_query when users hit on a purchase button. The callback_query is to send an invoice to the user, but it is throwing the above error.
bot.on('callback_query', (ctx) => {
    let data = ctx.callbackQuery.data
    if (data.includes('purchase') == true) {
        return handlePurchase(ctx)
    }
})

function handlePurchase(ctx) {
    let data = ctx.callbackQuery.data
    let itemId = data.split(':')[1]
    let invoice = {
        chat_id: ctx.callbackQuery.from.id,
        title: "Title",
        description: "Description",
        payload: itemId.toString(),
        provider_token: stripeToken,
        start_parameter: itemId.toString(),
        currency: "USD",
        need_phone_number: true,
        need_shipping_address: true,
        photo_url: the_image_url,
        prices: [{
            label: "Item",
            amount: 1000
        }]
    }
    return ctx.replyWithInvoice(invoice)
}

I also attempted to use ctx.telegram.sendInvoice(invoice) instead but the bot did not send an invoice to the user, ie the bot did not respond at all.


text:
Q: Virtual Environment and Base Environment are Active at the Same Time I'm using Ubuntu Linux. I started the terminal and created a virtual environment as follows: python3 -m venv test. Then when I activated the test virtual environment by typing source test/bin/activate, in the prompt base environment was also showed as active. Why both base and virtual environment are active at the same time? How to solve this issue?
Prompt is like that: (test) (base) tkarahan@tkarahan:~$

A: The last environment you activate is active. It's just an UI glitch caused by combining anaconda with some other environment manager. You can check which Python is on Your PATH with
which python


text:
Q: Android Image Button Issue I have the following imageButton
    <ImageButton
    android:id="@+id/header_buttonleft"
    android:layout_width="40dip"
    android:layout_height="40dip"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="10dip"
    android:layout_marginTop="5dip"
    android:src="@drawable/icon_download"
    android:clickable="true"/>

But when I load my application in the device, it appears too small:

Anyone knows how can I make the icon bigger. I have tried to increase the resolution (actually the icon is 70x70) but it still doesn't work. Any idea?

A:
Anyone knows how can i make the icon
  bigger.

Make a bigger button.
As an experiment, remove android:src from your layout, then run your app. That is the smallest an ImageButton can go without a custom background.
You are welcome to create your own custom ImageButton background with custom nine-patch PNG files for the different background states, where you adjust the nine-patch control frame to allow for a smaller gap between where your icon goes and the edges of the button.


text:
Q: i18n for rails works in dev not in production The i18n is configured in the rails 3.0.3 project  :
config.i18n.default_locale = :fr

In my dev environnement, everything works fine with price in € and text (like next previous from will_paginate) correctly displayed.
In production environnement, everything is in english and in $.
Where can i found the problem of my i18n ?
What am I missing in i18n in production?
More Info:
On the production server in the rails console production :
irb(main):002:0> I18n.config.default_locale
=> :fr

2Nd Edit
Is there a way to  display I18n properties or config in a debug or in a view?

A: I think this is related to this bug: http://groups.google.com/group/rubyonrails-core/browse_thread/thread/1fe3e88f9fe73177/ .

18n.locale is called before the config.i18n.default_locale is
  propagated to the I18n class.

I will try to also change it in config/initializers/locale.rb.  According to 2.2 Optional: Custom I18n Configuration Setup in http://guides.rubyonrails.org/i18n.html, you should also change it in config/initializers/locale.rb .  Hope this will fix it for you.

A: Resolved by adding config.i18n.locale = :fr in addition of the default config.i18n.default_locale = :fr in my application.rb

A: I had this problem with rails admin. But I believe it is the same with any Rails app
At the beginning I have set locale statically in application.eb.
Later I have solve this be removing this a from application.rb
if ENV['language']
  config.i18n.default_locale = ENV['language']
else
  config.i18n.default_locale = :he
end

And just leaving this in rails_admin/application_controller.rb
(or just application_controller.rb for regular rails app)
before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || 'he'
end

def default_url_options
  { locale: I18n.locale }
end

Also a nice tuturial on how to set i18n locale based on Url:
https://dev.to/morinoko/setting-up-i18n-for-rails-with-locales-from-url-params-38pg


text:
Q: A new row in pdfptable I am using iText library to print certain data in table format in a pdf file. I have 11 columns and can have multiple rows. After creating header for titles of each column, how do I create a new row in pdfptable so that I can print the real data on a separate row.

A: In the constructor of PdfPTable you specify the number of columns in a row.
PdfPTable table = new PdfPTable(4) // 4 Columns
PdfPCell cell;
cell = new PdfPCell( new Phrase("Cell with colspan of 4") ) ;
cell. setColspan(4) ; // an entire row

anotherCell = new PdfPCell( new Phrase("Cell with colspan of 4") );
anotherCell.setColspan(4); // a second row

As you can see, a new row is created when you reach the colspan in the current row.


text:
Q: Django, JSON serialize queryset and list of models has different behavior I have a Django model with a function (on the Python class) that modifies some of its fields.
class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class MyModel(TimeStampedModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    a_number = models.FloatField()
    some_text = models.CharField(max_length=64)

    def MyFunction(self):
        self.a_number = 123.123

I can do this, and it works
from django.core.serializers.json import DjangoJSONEncoder
json.dumps(list(MyModel.objects.filter(...).values()), cls=DjangoJSONEncoder)

Now I'd like to call the function MyModel.MyFunction on all the models before JSON encoding them. I've tried this, but obviously it returns the fields as they are in the database, not modified by MyFunction:
from django.core.serializers.json import DjangoJSONEncoder

mymodels = MyModel.objects.filter(...)

for mymodel in mymodels:
    mymodel.MyFunction()
    # or mymodel.myfield = somethingelse

json.dumps(list(mymodels.values()), cls=DjangoJSONEncoder)

So I've tried this
from django.core.serializers.json import DjangoJSONEncoder

mymodels = MyModel.objects.filter(...)

_mymodels = []

for mymodel in mymodels:
    mymodel.MyFunction()
    # or mymodel.myfield = somethingelse
    _mymodels.append(mymodel)

json.dumps(_mymodels, cls=DjangoJSONEncoder)

but TypeError: Object of type MyModel is not JSON serializable.
I've read on other answers that you'd have to either install django rest framework or implement a to_json function on MyModel.
However, I'd like not to clutter my application to achieve a behavior that is already available. How can I tell django to behave the same way on an array of models that it behaves on a queryset of the same model?

A: django.forms.models.model_to_dict did the trick
from django.core.serializers.json import DjangoJSONEncoder
from django.forms.models import model_to_dict

mymodels = MyModel.objects.filter(...)

_mymodels = []

for mymodel in mymodels:
    mymodel.MyFunction()
    # or mymodel.myfield = somethingelse
    _mymodels.append(model_to_dict(mymodel))

json.dumps(_mymodels, cls=DjangoJSONEncoder)

A: Another alternative is to try using json.dumps(MyModel.objects.filter(...).values(), cls=DjangoJSONEncoder), as this will mostly do the same thing as model_to_dict, but without the overhead of creating model instances (from something like a dict) and then converting them back to dicts.
You may need to write a custom DjangoJSONEncoder subclass if you use any custom field types, to instruct json.dumps() how to encode those.


text:
Q: ARSKView not releasing memory on dismissing ViewController I am creating an app in which I am using ARSKView. I am seeing that it is not releasing memory on dismissing ViewController. I am not able to find any issue in my code.
Here is my code for using ARSKView.
class ARViewController: UIViewController, ARSKViewDelegate {

    weak var sceneView: ARSKView?

    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView = ARSKView(frame: self.view.frame)
        self.view.addSubview(sceneView!)
        sceneView?.delegate = self

        let scene = CustomScene(size: view.frame.size)
        scene.sceneDelegate = self
        sceneView?.presentScene(scene)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        activateARView()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        sceneView?.session.pause()
    }

    var configuration = ARWorldTrackingConfiguration()
    func activateARView() {
        configuration.worldAlignment = .gravityAndHeading
        sceneView?.session.run(configuration)
    }

}

A: The controller is just paused, you can try by setting the controller equal to "nil" just make sure all dependencies are cleared before that.


text:
Q: Communication between a chat engine and an application containing REST APIs in node.js I have two applications, one a chat engine and another is a application consisting of REST APIs developed in node.js. How do I make the two applications communicate with each other. Shall I use Microservices architecture be a good fit to facilitate communication. between the two applications?
Would highly appreciate any feedbacks.


text:
Q: Capture max used bandwidth I have a Windows Server 2003 that I'd like to measure the max used bandwidth.
I'd like to have a report showing the peak bandwidth on an hourly and
daily basis.
Can I do this using Performance monitor somehow?

A: Performance Monitor can capture to various file formats (with the advantage that this can be done without an interactive session needed).
This can include CSV which can be loaded into (say) Excel and then processed.
To set this up:

*

*From Start | Run enter PerfMon

*Select Performance Logs and Alerts | Counter Logs

*Action | New Log Settings

*Enter a name

*Select the performance objects (groups of counters) or counters you want

*Enter you sample rate, to capture maxima you'll need a reasonably short interval

*On the log files tab select the format and location. The tools can auto number files to avoid overwriting.

*On the schedule tab select when you want data to be collected.

When you have the CSV files, use Excel and its normal functions to extract peaks.


text:
Q: ASP NET Entity Framework primary key Duplicate resolution     [HttpGet]
    public ActionResult Create()
    {
        Articles article = new Articles();
        return View(article);
    }

    [HttpPost]
    public ActionResult Create(Articles article)
    {
        try
        {
            article.ViewCount = 0;
            article.IPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
            article.RegistDate = DateTime.Now;
            article.RegistMemberID = "admin";
            article.ModifyDate = DateTime.Now;
            article.ModifyMemberID = "admin";

            db.Articles.Add(article);
            db.SaveChanges();

            if (Request.Files.Count > 0)
            {
                var attachFile = Request.Files[0];

                if (attachFile != null && attachFile.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(attachFile.FileName);
                    var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
                    attachFile.SaveAs(path);

                    ArticleFiles file = new ArticleFiles();
                    file.ArticleIDX = article.ArticleIDX;
                    file.FilePath = "/Upload/";
                    file.FileName = fileName;
                    file.FileFormat = Path.GetExtension(attachFile.FileName);
                    file.FileSize = attachFile.ContentLength;
                    file.UploadDate = DateTime.Now;

                    db.ArticleFiles.Add(file);
                    db.SaveChanges();
                }
            }

            ViewBag.Result = "OK";
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Board");
            Debug.WriteLine(ex.ToString());
            ViewBag.Result = "FAIL";
        }

        return View(article);
        //return RedirectToAction("ArticleList");
    }

The controller writes a message. But if you write a message (through a POST request) on a bulletin board, it will work normally when you try to post it the first time. But when you try to post again, it fails. I think the cause is a duplicate primary key.
Please let me know what you can do in case of a duplication of the primary key.
    namespace HeadHomePage1.Models
    {
        public class ArticlesEditViewModel
        {

            public Articles Article { get; set; }

            public List<ArticleFiles> Files { get; set; }
        }
    }

모델부분입니다.


text:
Q: Vaadin - using FileDownloader without a button I want to use the FileDownloader of Vaadin without extending a Button. The final result should be that the user clicks on an entry of a table, and that should then trigger the download.
With the FileDownloader it works fine, but it seems like you need to extend a Button to make this work. Here is the code so far if it helps:
        table.addItemClickListener(new ItemClickListener()    {
        public void itemClick(ItemClickEvent event) {
            Map<String, Object> dok = dbService.getDokument(event.getItem().getItemProperty("Id").getValue().toString());

            myResource = createResource(dok);
            fileDownloader = new FileDownloader(myResource);
            //HERE I WANT TO TRIGGER THE DOWNLOAD
        }
    });

private StreamResource createResource(Map<String, Object> dok) {
    return new StreamResource(new StreamSource() {
        @Override
        public InputStream getStream() {
            byte[] file = (byte[]) dok.get("DATA");

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(file, 0, file.length);
            return new ByteArrayInputStream(bos.toByteArray());

        }
    }, getValue(dok.get("DOK_NAME")));
}


text:
Q: How to build a 64 bit application on 32 bit OS? [c#] I have a application which implements Geckofx web browser control. I have 64 bit compiled geckofx.dlls(compiled from a 64 bit OS). But currently i don't have access to 64 bit OS and i want to compile the whole application with the 64bit geckofx.dlls targetting 64 bit OS. How can i do that from my 32 bit OS?
I need a good tutorial to do this. Do i need to download and install 64 bit compilers in my pc? if so, how? and how to check if i already have that compilers?

A: I don't think I've ever done this, but can't you just set the code generation ("platform target") as x64 in the project's "Build" configuration?
Or, in the command line: csc.exe /platform:x64?
As far as I know, the C# compiler (csc) is a 32bit application, it should be able to generate code for any supported platform


text:
Q: is there a command for "AS" in postgres? I'm wondering if there is a command like AS for postgres. Does anyone know if postges has this ability? I've tried to google it but it's a very difficult question to google :P I want to make a select statement and store it as a new table name. I want to say something like:
select subj, user as 'new' from table_name;

A: Yes. It's a reserved SQL key word in PostgreSQL. See Table C-1 at the linked documentation page.
It's typically used with column labels.

The AS keyword is optional, but only if the new column name does not
  match any PostgreSQL keyword (see Appendix C).

A: CREATE TABLE new_table AS SELECT subj, user FROM table_name

So, your new table will be ready.

A: "I want to make a select statement and store it as a new table name" --
CREATE VIEW view_name AS
SELECT subj, user AS "new" FROM table_name;

A: If you don't want to leave any changes in the schema, you can do something like this-
select new.* from (
  select foo, bar from old
) as new

A: *

*develop your query: SELECT field AS new_field FROM table WHERE ...;

*If it runs ok, copy it

*Go to VIEW and do that: CREATE OR REPLACE VIEW new_view AS <QUERY>;

*Save the view and use it as table.

*enjoy.

A: In my way, you can do alias for the field and create view to store it. which ll act like table.
select subj, user as new from table_name;
By using the above query can get subj and new as a field.
And create view.
create or replace view_name as
select subj, user as new from table_name;
And just call
 select view_name;


text:
Q: Configure PhpStorm Run gutter icons Since updating to 2017.1 I've noticed these Run gutter icons in my Karma files.
They look cool and could be useful, however when I click them they run as pure node instead of using the Karma plugin.
Is there a way of configuring these icons to use Karma as the default configuration instead of Node?

A: No, this can't be configuraed.
Running individual karma tests is not yet supported, please follow WEB-13173 for updates.
WebStorm tries to run your tests with other available runners instead, this usability issue is tracked as WEB-25932


text:
Q: how to fit a concatenated model when we have two X_train and two y_train I want to concatenate two CNN models, each one with different input.
the first model has its x_train and y_train
the second one too X_train, Y_train
(it's the same image but in the second branch I did some processing)
`merge = Concatenate()([model_a.output, model_b.output])
 merged_out = Dense(units=512, activation='relu')(merge)
 merged_out = Dense(units=1, activation='softmax')(merged_out)
 from tensorflow.keras.optimizers import Adam
 merged_model = Model([model_a.input, model_b.input], merged_out)
 merged_model.compile(optimizer=Adam(learning_rate=0.001), loss=tf.losses.BinaryCrossentropy(), metrics=['accuracy'])

Now the problem is how to fit the merged model

A: What have you tried? Where do things break?
Your merged_model is a model, you can just call fit on it, it expects a pair of images, just like the way you defined it: [image_a, image_b]. So you need to create a dataset ([image_a, image_b], labels) to train it on.
So your data pipeline would need to be something like this:
ds = tf.keras.utils.image_dataset_from_directory(...)

def preprocess_ab(images, labels):
  image_a = preprocess_a(images)
  image_b = preprocess_b(images)

  return (image_a, image_b), labels

ds =  ds.map(preprocess_ab)

model.fit(ds)


text: Q: Time consumed by sigtimedwait function in C The sigtimedwait() function can be interrupted by a signal that is defined in the set. But how can I get the time it took for the timeout to expire? Or the time consumed?


text:
Q: Is it possible to disable a fragment? I have two fragments, in each fragment there are 9 buttons. I want when I click on a fragment the other is enabled and the one where I clicked is disabled and the opposite.
I can't find anything that allows me to deactivate a fragment without it disappearing.

A: I know two methods to get it. The first one is more correct but also is more bulky than the second, so you need add to both fragments a static boolean variable with name for e.g. "isClickable" then when you click on the first fragment set it's "isClickable" variable to false, and the same variable of the second fragment set to true and the opposite, finally add to each of your buttons onClickListeners condition:
if (isClickable) {
// and here do needed actions
}

In the second method, you also need to have the two "isClickable" variables, but also you need to set to each of your fragment's root layout an onTouchListener (exactly onTouch, not onClick) and put to it's return statement the "isClickable" variable but necessary with negation:
return !isClickable.


text:
Q: Django sqlite to postgres database migration I have a quite large db of 750MB which I need to migrate from sqlite to postgres. As, the db is quite large I am facing some issues that some of the previous questions on the same topic did not had.
Few days ago, I have migrated one sqlite db of size 30MB without any issues with loaddata and dumpdata commands. But for this large db, one of my app throws Database image is malformed error when running command dumpdata. Another of my app dumps successfully but does not load. I have seen the with -v 3 verbose flag that the objects are not even processed. To be precise, while running the loaddata command data from json file is processed first to check duplicate primary key and other model constraints then those data are used to create model objects. But for this app, data are not processed in the first place.
Apart from this two commands there are some other methods that does the migration. But, the schema is completely changed in those way which I don't desire to do. Moreover I have faced issue DurationField becomes a string after migration and I couldn't typecast those fields. Bigint becomes int and varchar becomes text etc are some of the issues. I cannot afford to have this kind of issues.

A: I found the issues for these problems.

*

*Database image is malformed occurred because I was copying entire db file directly. Just as, angardi suggested, I compressed the db file using gzip package and then copied it. Which solved this issue.

*There were two issues for which loaddata was not loading a certain app. That app contained a model which had a foreign key to itself. And one of the entry of the model had the foreign key set to the entry. This resulted in an infinite loop and the app wasn't loading. Even after fixing the entry I was facing the same issue. This happened because I dumped data of a specific app. One of the model of the app had a ManyToMany field set to a model of another app. Though, loaddata throws error when ForeignKey field reference is not found, I think it kept searching for the ManyToMany fields without throwing an error which turned into an infinite loop type of situation. All, I had to do here is, dump the entire database or the related app on the same file.

A: Read this for the image malformed part.
When migrating from one database to another, you should first dump all data, then run django migrations on the new database and the load data. That should retain all column types.
When running loaddata, the tables that have no dependencies should be loaded first and then the ones that depend on those already loaded.


text:
Q: Why does my USB wireless adapter stop working when connected to a VM running BackTrack? I wanted to know why my USB wireless adapter stops working when it's been connected to VMware? When it is disconnected from the VM (connect to host), it works like normal.
Result for lsusb:
Bus 1 Device 2: ID 148f:2070 Ralink Technology, Corp.
Bus 1 Device 1: ID 0000:0000
Bus 2 Device 2: ID 0e0f:0002
Bus 2 Device 1: ID 0000:0000

Result for ifconfig:
eth0      Link encap:Ethernet  HWaddr 00:0C:29:28:D8:45
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST NOTRAILERS RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:461 errors:0 dropped:0 overruns:0 frame:0
          TX packets:299 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:276800 (270.3 KiB)  TX bytes:50080 (48.9 KiB)
          Base address:0x2000 Memory:d8920000-d8940000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

A: You probably don't have the correct driver and/or configuration installed inside the VM.
Start with lsusb, make sure it's recognized, then check dmesg to see if a driver got loaded, then ifconfig -a to see if maybe it's just waiting for you to configure its address.

A: You'll want to ensure that the USB adapter is compatible with the USB redirection in VMWare.
From there, you'll want to ensure the wireless adapter is also supported in the Linux distro that BackTrack is built on, and that there's a driver loaded for it.
Beyond that be aware that BT is VERY picky about which wireless adapter chipsets will work for the wireless sniffing/cracking utilities.
I would assume that's what you want to do, as most (all?) of the other stuff in BT could be done via the regular VMware networking bridge to the host. :)
Hope that helps...


text:
Q: how to add arraylist in Jsp <html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
  </head>
  <body>
<%=new Date() %>

<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>

    <select>
      <option value="<%=al%>"></option>
    </select>
  </body>
</html>

This is my code i want to add Arraylist in drop down in Jsp I dont know how to Bind arraylist in html obtion or drop down please help me i have tried Much but unable to do this .

A: EDITED
Try this:
<%

ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

%>

<select>
   <%  for(int i = 0; i < al.size(); i++) {
           String option = (String)al.get(i);
   %>
   <option value="<%= option %>"><%= option %></option>
   <% } %>
</select>
</body>
</html>

A: You have to use JSTL <forEach> to iterate through the elements and add it to the select-option . Probably make the List a scoped attribute . Populate the List object in the servlet, set it in request/session scope and forward the request to this JSP. Remember you can populate the List in the JSP itself and use pageScope to refer it , but that will be bad design in my opinion.
<select>
 <c:forEach var="element" items="${al}">
  <option value="${element}">${element}</option>
 </c:forEach>
</select>

Here , al is the name of the attribute which stores the List in probably request or session scope.
Use JSTL in project :

*

*Download the JSTL 1.2 jar .

*Declare the taglib in JSP file for the JSTL core taglib.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

If you want to use just the scriptlets(which is bad off course) :
<%

List<String> al = new ArrayList<String>();
al.add("C");
..........
...........

%>
<select>
  <%  for(String element: al) { %>
   <option value="<%=element%>"><%=element%></option>
  <% } %>
</select>

The above code will work if you have defined the List as List<String> , or else you need to cast the element to String.
Read How to avoid Java Code in JSP-Files?.

A: Take a look at the  tag in the core JSTL library.
Store the arraylist in pageScope.myList and loop as follows:
<select>
<c:forEach items="${pageScope.myList}" var="item" varStatus="status">
<option value='${item}'></option>
</c:forEach >
</select>

This is preferable than using scriptlets which are not considered good practice

A: Try this: declare your arraylist in between <%! … %>
<%! ArrayList al = new ArrayList(); %>


text:
Q: Detect Debug Privileges on a process (Windows, C) in a previous question I asked how to overcome the fact that in certain users the debug privileges were not there.
Now, since I can't set something that doesn't exist, how would I check if a user has debug privileges?
I know I have to use LookupPrivilegeValue(), I just can't figure where to read on the returned value that would indicate whether a particular privilege is there or not.
Code is appreciated.
Thanks

A: From http://msdn.microsoft.com/en-us/library/aa446619%28VS.85%29.aspx
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;

    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }

    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;

    // Enable the privilege or disable all privileges.

    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)

    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }

    return TRUE;
}

if the function returns ERROR_NOT_ALL_ASSIGNED when requesting to set debug privileges then the token is not there.


text:
Q: Fuzzing for boolean checks? I have a function that checks if a string is a valid representation of an hexadecimal number ('0xdEAdBEef' and that sort of strings.) Now I have a check on isHexaString(string) which returns a bool that is false when it's not. But running go -fuzz=Fuzz with a bunch of seeds and they the checks with errors, I am not getting anything meaningful (no panics). Does that mean my code (isHexaString) is okay?
func FuzzIsHexAddress(f *testing.F) {
    testcases := []string{
        "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed",
        "5aaeb6053f3e94c9b9a09f33669435e7ef1beaed",
        "0X5aaeb6053f3e94c9b9a09f33669435e7ef1beaed",
        "0XAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
        "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    }
    for _, tc := range testcases {
        f.Add(tc) // Use f.Add to provide a seed corpus
    }

    f.Fuzz(func(t *testing.T, orig string) {
        if result := isHexaString(orig); !result {
            t.Errorf("IsHexAddress(%s) == %v",
                orig, result)
        }
    })
}

What's the best way to fuzz test this type of unit tests?
Oh and running on one package only triggers the whole unit tests to be ran (must be a behaviour of Go to want to run unit tests first?)

A: I don't think this fuzz test is correct. This condition result := isHexaString(orig); !result evaluates to true when orig is not a valid hex string. So you are basically saying "fail when the input string is not a hex string". But why the test should fail then? If orig was indeed not a hex string, your function yielded the correct result: false.
The point is that you are not in control of the fuzz input (it is fuzzed!), therefore you should not rely on the output of the function under test alone to determine a pass or fail.
The fuzz tutorial suggests the example of a string reverse function:
rev := Reverse(orig)
doubleRev := Reverse(rev)
if orig != doubleRev {
    t.Errorf("Before: %q, after: %q", orig, doubleRev)
}

In this particular case Reverse is supposed to be an involution, i.e. the reverse of itself. Your function isHexaString is not an involution, and it doesn't even have an inverse (it's only surjective) but you can check its output against a golden standard, e.g. some other function that is known to always correctly identify valid hex strings.
Or, you can keep using the condition result := isHexaString(orig); !result to find interesting edge cases that are not hex strings and include those into your non-fuzzed unit test.


text:
Q: Finding variance of infimum of a set Let $X_1, X_2, \cdots,X_n$ be independent and identically distributed random variables having an exponential distribution with mean $\frac{1}{\lambda}$.
Let $S_n=X_1+X_2+\cdots+X_n$ and $N = \text{inf}\left\{n \geq \ 1:S_n > 1\right\}$. Then $\operatorname{Var}(N)$ equals

*

*1

*$\lambda$

*$\lambda^2$

*$\infty$
I don't understand the question and only thing I could deduce from the question is that $S_n$ has variance $\frac{n}{\lambda^2}$. Can somebody please explain what the question demands.

A: Define $N^*(t)$ as
$$
N^*(t) = \text{max}(n \mid S_n \leq t)
$$
and  $N(t)$ as
$$
N(t) = \text{min}(n \mid S_n > t)
$$
We have $N(t) = N^*(t) + 1$ and $N = N(1)$.
Since $S_n$ is a sum of $n$ iid random variables exponentially distributed (with parameter $\lambda$), $N^*(t)$ is a Poisson process.
For fixed $t$, $N^*(t)$ thus follows a Poisson distribution with intensity $\lambda t$ and so we have
$$
\mathbb{E}[N^*(t)] = \lambda t
$$
and,
$$
\text{var}[N^*(t)] = \lambda t
$$
Thus,
$$
\mathbb{E}[N(t)] = \lambda t +1
$$
$$
\text{var}[N(t)] = \lambda t
$$
Finally  $\mathbb{E}[N] = \mathbb{E}[N(1)]= \lambda +1$ and $\text{var}(N) = \lambda$
This result can be checked using simulations, for example assuming $\lambda=15$,
R=sapply(1:1000,function(i){
X<-rexp(100,15)
S<-cumsum(X)
N<-min(which(S>1))
return(N)})

The command
mean(R)

should gives something close to 16.


text: Q: How do you alter the default WordPress thumbnail? I have selected 'thumbnail' under 'Apply changes to:', however, nothing seems to happen in either the media library or on the site. I've also tried regenerating the images after making changes, but the result shows the changes being added to the full-size image, not the thumbnail.


text:
Q: How reliable is yahoo finance? How reliable is yahoo finance ?
For example the below request :
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22%29
intermittently returns the response : "The current table 'yahoo.finance.quotes' has been blocked. It exceeded the allotted quotas of either time or instructions"
Here is the complete response :
<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="0" yahoo:created="2013-04-08T11:16:18Z" yahoo:lang="en-US">
    <diagnostics>
        <publiclyCallable>true</publiclyCallable>
        <url execution-start-time="24" execution-stop-time="25"
            execution-time="1" proxy="DEFAULT"><![CDATA[http://www.datatables.org/yahoo/finance/yahoo.finance.quotes.xml]]></url>
        <cache execution-start-time="27" execution-stop-time="27"
            execution-time="0" method="GET" type="MEMCACHED"><![CDATA[13c4f8eac77ad886bade5a711c8c1ef5]]></cache>
        <javascript name="yahoo.finance.quotes" verb="select"><![CDATA[The current table 'yahoo.finance.quotes' has been blocked. It exceeded the allotted quotas of either time or instructions]]></javascript>
        <user-time>28</user-time>
        <service-time>1</service-time>
        <build-version>35405</build-version>
    </diagnostics>
    <results/>
</query>

To get a reliable service do I need to sign up and pay ?

A:
To get a reliable service do I need to sign up and pay ?

Here are the limits:
                    Public  OAuth with API Key
Hourly Cap          2,000   20,000
Daily Cap           None    100,000

To better understand the rate limits in the above table, let's use the following example. Suppose you create an application that generates around 3,000 requests from each user per hour. You notice though that users are capped at a maximum of 2,000 calls using the public endpoint, so you register an API Key with Yahoo! to use the authenticated/authorized endpoint. Now your users can make 20,000 requests per hour and up to a total of 100,000 requests per day.

oAuth is free.
References

*

*YQL Overview - Yahoo Developer Network

*Public API Down Detector


text:
Q: For loop is adding an extra value/element Here is the sample dataframe.
I have a function which uses a for loop to go through a dataframe for a specified number of columns, remove NA values, remove duplicate values, then return the length of the final vector which has all the unique values present in the specified columns. The columns represent time, and the goal is to show how many total unique values have existed up until a certain point in time. Here's the sample matrix:
    X1   X2   X3 X4 X5   X6
1    F    F    F  F  F    F
2    C    C    C  C  C    C
3    D    D    D  D  D    D
4   A#   A#   A#  A  A    A
5 <NA> <NA> <NA>  G  G <NA>

And here's the function:
uniquepitches <- function(file, col){
  y <- read.csv(file, na.strings=c(""))
  frame <- data.frame(y)
  x <- c()

  for(i in 1:col) {
    noNAframe <- frame[!is.na(frame[, 1:i])]
    x[i] <- length(unique(noNAframe))
  }
  x
}

The issue is that when I run it for any value for col, I get the wrong values. For example, uniquepitches("testnotes.csv", 1) gives me 5, which should be 4. uniquepitches("testnotes.csv", 6) gives me [1] 5 5 5 6 6 6, which should be [1] 4 4 4 6 6 6. So as of right now it looks like the x vector has one element too many in the first three run-throughs, which is why the length is one too many. How can I fix it so that it's the correct length?

A: This task can be accomplished with sapply():
df <- data.frame(X1=c('F','C','D','A#',NA), X2=c('F','C','D','A#',NA), X3=c('F','C','D','A#',NA), X4=c('F','C','D','A','G'), X5=c('F','C','D','A','G'), X6=c('F','C','D','A',NA) );
sapply(df, function(c) length(unique(c[!is.na(c)])) );
## X1 X2 X3 X4 X5 X6
##  4  4  4  5  5  4

Edit: @Molx might be correct, although the OP needs to clarify to be sure. If the requirement is indeed to process the cumulative column content, rather than each individual column in isolation, then you can do this:
sapply(1:ncol(df), function(c) length(unique(df[,1:c][!is.na(df[,1:c])])) );
## [1] 4 4 4 6 6 6

Edit: Sorry, I should've been clearer. The sapply() call replaces the entire for loop. So the function can be rewritten as follows:
uniquepitches <- function(file,col) {
    frame <- read.csv(file,na.strings=c(""));
    sapply(1:col, function(c) length(unique(frame[,1:c][!is.na(frame[,1:c])])) );
}

(Also notice that read.csv() returns a data.frame, so there's no need for manual coercion.)


text:
Q: Windows Null not Working Correctly GitHub for Windows is not working correctly, citing a /dev/null error. I have since discovered that Windows' null.sys and Null device may have something to do with it, as running dir > nul returns an error rather than nothing (like it supposedly should, as it does on installations that work correctly).
This is on Windows 7 64-bit Home Premium (not as many administrative tools, sorry) if it helps.
I have already:

*

*run sfc /scannow (multiple times)

*rebooted (many times)

*stopped and started the Null device in device manager

Even through a lot of Googling, I still haven't found a solution (or anyone else with the problem, for that matter) so I think this might be a special case.
Has anyone seen this before? Did you find a solution? Thanks in advance.


text:
Q: Difference between printf %.3f and bc rounding behavior Ok so this is a hackerrank problem (https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations). Basically, input is an arithmetic expression and I'm supposed to print out formatted answer (3 decimal places). I tried this at first
read exp
echo "scale = 3; $exp" | bc -l

It passed several tests but not the first one.
5+50*3/20 + (19*2)/7 The answer is 17.929 but my code prints out 17.928. I tried this code instead
read exp
printf "%.3f\n" `echo $exp | bc -l`

Note: the echo part should be in backticks but I put ' ' to not confuse with block quotes. All tests passed. So what's the difference?

A: The reason that the two differ is that bc always cuts off the numbers instead of rounding them. I. e. echo "scale = 3 ; 8/9" | bc produces 0.888 instead of the correctly rounded 0.889.
Your test case evaluates to 17.928571429, which is rounded to 17.929 with your printf approach, but cut off to 17.928 with the bc approach.

A: I think the problem is scale = 3; part. For example, if you use
      printf "%.3f\n" ` echo  "scale = 3 ; $exp " | bc -l`

You will get 17.928 again. So the answer is you need to set scale at least to 4 and then print it in three digit.

A: The problem is rounding and/or significant digits returned by bc. When you use echo with scale=3 you are relying on bc to return only 3 digits. When you tell printf to output only 3 decimal places (using the format %.3f), you are relying on printf to determine which digits. Essentially, the difference is in the rounding done by bc utilizing scale=3 and that done by printf with the double %.3f conversion.

A: v=$(sed 's/[[:blank:]]//g')
(echo "scale=4"; echo $v) | bc | xargs printf '%.3f'

The above reads the integer from stdin, removes the blank lines, pipes it to bc to perform the calculation with 4 digits precision, then formats it with correct rounding to 3 digits with the help of printf. My solution to the above mentioned HackerRank problem.


text:
Q: Intermittent windows sign-in pop up in ASP .NET MVC 5.2.0 hosted on IIS I have an ASP.NET MVC application hosted on IIS on windows server 2019. The webapp runs fine but upon clicking a button(which triggers a service call), I get windows sign-in pop up intermittently.

Note that, we have disabled windows authentication at IIS level and user authentication is being done at application level using Azure active directory.

We have the following authentication settings in web.config:
<system.web>
   <authentication mode="None" />
   <authorization>
      <allow users="*" />
   </authorization>
</system.web>

<modules runAllManagedModulesForAllRequests="true">
     <remove name="FormsAuthentication" />
     ...
</modules>


text:
Q: openmpi installation fails locally and on remote server I tried installing version 4.0.5.tar.gz on an Ubuntu 18.04 LTS server at school but it failed following instructions here that say:
shell$ gunzip -c openmpi-4.0.5.tar.gz | tar xf -
shell$ cd openmpi-4.0.5
shell$ ./configure --prefix=/usr/local
<...lots of output...>
shell$ make all install

So I tried version 3.1.6 and it failed again.
The error was:
  make[2]: Nothing to be done for 'install-exec-am'.
 /bin/mkdir -p '/usr/local/share/openmpi/amca-param-sets'
 /usr/bin/install -c -m 644 amca-param-sets/example.conf '/usr/local/share/openmpi/amca-param-sets'
/usr/bin/install: cannot remove '/usr/local/share/openmpi/amca-param-sets/example.conf': Permission denied
Makefile:1806: recipe for target 'install-dist_amca_paramDATA' failed
make[2]: *** [install-dist_amca_paramDATA] Error 1
make[2]: Leaving directory '/home/T00057442/openmpi31/openmpi-3.1.6/contrib'
Makefile:1897: recipe for target 'install-am' failed
make[1]: *** [install-am] Error 2
make[1]: Leaving directory '/home/T00057442/openmpi31/openmpi-3.1.6/contrib'
Makefile:1896: recipe for target 'install-recursive' failed
make: *** [install-recursive] Error 1

for version 3.1.6 on the server and locally:
make[2]: Nothing to be done for 'install-exec-am'.
 /bin/mkdir -p '/usr/local/share/openmpi/amca-param-sets'
/bin/mkdir: cannot create directory '/usr/local/share/openmpi': Permission denied
Makefile:1789: recipe for target 'install-dist_amca_paramDATA' failed
make[2]: *** [install-dist_amca_paramDATA] Error 1
make[2]: Leaving directory '/media/nobu/UbuntuFiles/Downloads/openmpi-4.0.5/contrib'
Makefile:1880: recipe for target 'install-am' failed
make[1]: *** [install-am] Error 2
make[1]: Leaving directory '/media/nobu/UbuntuFiles/Downloads/openmpi-4.0.5/contrib'
Makefile:1879: recipe for target 'install-recursive' failed
make: *** [install-recursive] Error 1

so both times it is install-am?  What is that and has anyone successfully installed openmpi or mpich?  I need it for Ray Surveyor:  http://zorino.github.io/raysurveyor-tutorial/#/42
Edit:
I run
base) nobu@gold3forever:~/Desktop/BioInformatics/RA/kover/ray$ mpiexec --version
mpiexec: error while loading shared libraries: libopen-rte.so.40: cannot open shared object file: No such file or directory

then I tried:
(base) nobu@gold3forever:~/Desktop/BioInformatics/RA/kover/ray$ mpirun --version
mpirun: error while loading shared libraries: libopen-rte.so.40: cannot open shared object file: No such file or directory

Finally
(base) nobu@gold3forever:~/Desktop/BioInformatics/RA/kover/ray$ mpicxx --showme:version
mpicxx: error while loading shared libraries: libopen-pal.so.40: cannot open shared object file: No such file or directory

I thought I was okay, following directions from @NOrbert in his answer but when I try to install Ray Surveyor I get
(base) nobu@gold3forever:~/Desktop/BioInformatics/RA/kover/ray$ make PREFIX=`pwd`/BUILD MAXKMERLENGTH=64 HAVE_LIBZ=y HAVE_LIBBZ2=y ASSERT=n;
  CXX code/application_core/ray_main.o
mpicxx: error while loading shared libraries: libopen-pal.so.40: cannot open shared object file: No such file or directory
Makefile:160: recipe for target 'code/application_core/ray_main.o' failed
make: *** [code/application_core/ray_main.o] Error 127

A: Per the comment above, sudo ldconfig I read on that link after the steps provided by @NOrbert.

A: You do not need to compile OpenMPI by yourself.
This package is presented in Ubuntu repositories.
Simply install it with:
sudo apt-add-repository universe
sudo apt-get install libopenmpi-dev

and then continue with compilation of only Ray Surveyor.

A: I got this error while trying to install OpenMPI 4.0.0 in Ubuntu 18.04. I wanted this particular version for another library. I solved this by running sudo make all install instead of make all install. You can notice this error in the
error logs in the question too (Permission denied).


text:
Q: Add forward and Backward buttons on Hstack in SwiftUI I write the following code for date picker customization, and get the output as
Here I want to add the forward and Backword buttons for the Date picker this way
Anyone help me with my code modification to add forward and Backword buttons with Expect output]2
Give any idea or share any references with me.
    struct CalendarDay: Identifiable {
    let id = UUID()
    var number: String
    var weekday: String
    var isToday: Bool
}

struct ContentView: View {
    @State var days = [CalendarDay]()

    var body: some View {
        ZStack{
            VStack {

                Button(action:{
                    //Button Action
                    })
                    .padding(.leading, 10)
                Spacer()
                ScrollView(.horizontal, showsIndicators: false){
                    HStack(spacing: 20) {
                  ForEach(days.indices, id: \.self) { i in
                        CalendarView(
                            number: self.days[i].number,
                            days: self.days[i].weekday,
                            color: self.days[i].isToday ? #colorLiteral(red: 0.9060331583, green: 0.2547450066, blue: 0.3359550834, alpha: 1) : #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),
                            textcolor: self.days[i].isToday ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
                        )
                            .onTapGesture{
                                print(self.days[i])
                                // this is just for replacing the current selection
                                for j in self.days.indices { self.days[j].isToday = false }
                                self.days[i].isToday = true
                            }
                    }}
                    .padding(.leading,10)
                    .padding(.bottom, 10)
                    .shadow(radius: 3, x: 3, y: 3)
                }
                Spacer()
                Button(action:{
                                   //Button Action
                                   })
                                   .padding(.leading)
                               Spacer()

            }
        }
        .onAppear {
            self.getCurrentWeekdays()
        }
    }

    func getCurrentWeekdays() {
        /// from https://stackoverflow.com/a/62355272/14351818
        let dateComponents = Calendar(identifier: .gregorian).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
        let startOfWeek = Calendar(identifier: .gregorian).date(from: dateComponents)!
        let startOfWeekNoon = Calendar(identifier: .gregorian).date(bySettingHour: 12, minute: 0, second: 0, of: startOfWeek)!

        days = (0...6).map {
            let calendar = Calendar(identifier: .gregorian)
            let date = calendar.date(byAdding: .day, value: $0, to: startOfWeekNoon)!

            let numberDateFormatter = DateFormatter()
            numberDateFormatter.dateFormat = "d"
            let number = numberDateFormatter.string(from: date)

            let weekdayDateFormatter = DateFormatter()
            weekdayDateFormatter.dateFormat = "E"
            let weekday = weekdayDateFormatter.string(from: date)

            let calendarDay = CalendarDay(
                number: number,
                weekday: weekday,
                isToday: calendar.component(.day, from: Date()) == calendar.component(.day, from: date)
            )

            return calendarDay
        }

    }
}

struct CalendarView: View {
    var number : String
    var days : String
    var color : UIColor
    var textcolor : UIColor

    var body: some View {
        VStack{
            Text(self.number)
                .font(.system(size: 20, weight: .bold, design: .rounded))
                .foregroundColor(Color(self.textcolor))
            Text(self.days)
                .font(.headline)
                .foregroundColor(Color(self.textcolor))
        }.padding([.top,.bottom], 10)
            .padding([.leading,.trailing],10)
            .background(Color(self.color))
            .cornerRadius(30)
    }
}

A: you could try something like this: edited for ScrollViewReader
struct ContentView: View {

@State var days = [CalendarDay]()
@State var selectedDay: Int = 0

var body: some View {
    ScrollViewReader { scrollProxy in
        HStack {
            Button(action: {
                if selectedDay > 0 {
                    for j in days.indices { days[j].isToday = false }
                    days[selectedDay-1].isToday = true
                    selectedDay -= 1
                    withAnimation { scrollProxy.scrollTo(selectedDay) }
                }
            }) {
                Image(systemName: "chevron.left.circle.fill")
            }
            ZStack{
                VStack {
                    ScrollView(.horizontal, showsIndicators: false){
                        HStack(spacing: 20) {
                            ForEach(days.indices, id: \.self) { i in
                                CalendarView(
                                    number: days[i].number,
                                    days: days[i].weekday,
                                    color: days[i].isToday ? #colorLiteral(red: 0.9060331583, green: 0.2547450066, blue: 0.3359550834, alpha: 1) : #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),
                                    textcolor: days[i].isToday ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
                                ).onTapGesture {
                                    selectedDay = i
                                    for j in days.indices {
                                        if j == i {
                                            days[i].isToday = true
                                        } else {
                                            days[j].isToday = false
                                        }
                                    }
                                }
                            }

                        }
                        .padding(.leading,10)
                        .padding(.bottom, 10)
                        .shadow(radius: 3, x: 3, y: 3)
                    }
                }
            }
            Button(action: {
                if selectedDay < days.count-1 {
                    for j in days.indices { days[j].isToday = false }
                    days[selectedDay+1].isToday = true
                    selectedDay += 1
                    withAnimation { scrollProxy.scrollTo(selectedDay) }
                }
            }) {
                Image(systemName: "chevron.right.circle.fill")
            }
        }
    }
    .onAppear {
        getCurrentWeekdays()
    }
}

    func getCurrentWeekdays() {
        /// from https://stackoverflow.com/a/62355272/14351818
        let dateComponents = Calendar(identifier: .gregorian).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
        let startOfWeek = Calendar(identifier: .gregorian).date(from: dateComponents)!
        let startOfWeekNoon = Calendar(identifier: .gregorian).date(bySettingHour: 12, minute: 0, second: 0, of: startOfWeek)!

        days = (0...6).map {
            let calendar = Calendar(identifier: .gregorian)
            let date = calendar.date(byAdding: .day, value: $0, to: startOfWeekNoon)!

            let numberDateFormatter = DateFormatter()
            numberDateFormatter.dateFormat = "d"
            let number = numberDateFormatter.string(from: date)

            let weekdayDateFormatter = DateFormatter()
            weekdayDateFormatter.dateFormat = "E"
            let weekday = weekdayDateFormatter.string(from: date)

            let calendarDay = CalendarDay(
                number: number,
                weekday: weekday,
                isToday: calendar.component(.day, from: Date()) == calendar.component(.day, from: date)
            )
            //  <--- here --->
            if calendar.component(.day, from: Date()) == calendar.component(.day, from: date) {
                selectedDay = $0
            }

            return calendarDay
        }

    }
}

A: You could also try like below-:
You can replace Text view with Image view for buttons. The Back and forward buttons retain their positions, while the date selector is still scrollable.
import SwiftUI

struct CalendarDay: Identifiable {
    let id = UUID()
    var number: String
    var weekday: String
    var isToday: Bool
}

struct Test1: View {
    @State var days = [CalendarDay]()

    var body: some View {

        HStack(){
            Button {

            } label: {

                ZStack {

                    Circle()
                        .fill(Color.red)
                        .opacity(0.6)

                    Circle()
                        .strokeBorder(Color.red, lineWidth: 1)

                    Text("B").foregroundColor(.white)

                }.frame(width: 30, height: 30)
            }.padding([.leading],3)

            HStack(alignment:.center){
                GeometryReader{ proxy in
                    ScrollView(.horizontal) {

                        LazyHStack {
                            ForEach(days.indices, id: \.self) { i in
                                CalendarView(
                                    number: days[i].number,
                                    days: days[i].weekday,
                                    color: days[i].isToday ? #colorLiteral(red: 0.9060331583, green: 0.2547450066, blue: 0.3359550834, alpha: 1) : #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),
                                    textcolor: days[i].isToday ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), proxy: proxy
                                )
                                .onTapGesture{
                                    print(days[i])
                                    // this is just for replacing the current selection
                                    for j in days.indices { days[j].isToday = false }
                                    days[i].isToday = true
                                }
                            }
                        }
                    }
                }
            }
            .padding([.trailing,.leading],3)

            Button {

            } label: {
                ZStack {
                    Circle()
                        .fill(Color.red)
                        .opacity(0.6)

                    Circle()
                        .strokeBorder(Color.red, lineWidth: 1)

                    Text("F").foregroundColor(.white)
                }.frame(width: 30, height: 30)
            }.padding([.trailing],3)
        }

        .shadow(radius: 3, x: 3, y: 3)
        .onAppear {
            getCurrentWeekdays()
        }
    }

    func getCurrentWeekdays() {
        /// from https://stackoverflow.com/a/62355272/14351818
        let dateComponents = Calendar(identifier: .gregorian).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
        let startOfWeek = Calendar(identifier: .gregorian).date(from: dateComponents)!
        let startOfWeekNoon = Calendar(identifier: .gregorian).date(bySettingHour: 12, minute: 0, second: 0, of: startOfWeek)!

        days = (0...20).map {
            let calendar = Calendar(identifier: .gregorian)
            let date = calendar.date(byAdding: .day, value: $0, to: startOfWeekNoon)!

            let numberDateFormatter = DateFormatter()
            numberDateFormatter.dateFormat = "d"
            let number = numberDateFormatter.string(from: date)

            let weekdayDateFormatter = DateFormatter()
            weekdayDateFormatter.dateFormat = "E"
            let weekday = weekdayDateFormatter.string(from: date)

            let calendarDay = CalendarDay(
                number: number,
                weekday: weekday,
                isToday: calendar.component(.day, from: Date()) == calendar.component(.day, from: date)
            )

            return calendarDay
        }

    }
}
struct CalendarView: View {
    var number : String
    var days : String
    var color : UIColor
    var textcolor : UIColor
    var proxy: GeometryProxy

    var body: some View {
        VStack{
            Text(self.number)
                .font(.system(size: 20, weight: .bold, design: .rounded))
                .foregroundColor(Color(self.textcolor))
            Text(self.days)
                .font(.headline)
                .foregroundColor(Color(self.textcolor))
        }

        .frame(width: proxy.size.width * 0.18, height:  proxy.size.width * 0.2)
        .background(Color(self.color))
        .cornerRadius(30)
    }
}


text:
Q: Inline coding in ASP.NET page hi guys i am using this code in my aspx page
<%for (int i=o;i<5;i++)
{%>
  <asp: link button id=i text=i/>

<%}%>

at it's producing five link buttons like

i i i i i

but i just want five link buttons like that

1 2 3 4 5

with id=1,2,3,4,5 respectively
how can I can implement that

A: Put a placeholder in the page where you want the links:
<asp:PlaceHolder ID="LinkContainer" runat="server" />

In the Page_Load method in code behind, you put the links in the placeholder:
for (int i = 1; i <= 5; i++) {
   LinkButton link = new LinkButton();
   link.ID = "Link" + i.ToString();
   link.Text = i.ToString();
   LinkContainer.Controls.Add(link);
}

This way the controls will be created early in the page cycle, and it's possible to hook up server side events to them if you like.
(Note that I added a prefix to the id. Having an id that is only digits can cause problems in some situations.)

A: This isn't exactly the best way to do things in ASP.Net.  Dynamic controls have many gotchas, and you just found one of them.  This code is a little better (make sure the page calls DataBind() at some point):
<%for (int i=0;i<5;i++)
{%>
  <asp:LinkButton id="<%# i%>" runat="server" text="<%#i%>" />

<%}%>

but you'll find that events and changes don't wire up the way you'd expect them to, if it works at all.  With only five of them, it's better to just list them out by hand, and things will be much easier down the road.  Or, if they came from a datasource somewhere use a repeater and create them that way.
Really, you don't want to mix code into your aspx markup at all if you can help it.  Leave it for the code behind!

A: YOu need to actually print out the value of I on the server side.
<%for (int i=o;i<5;i++) {%>
    <ASP:LinkButton Id="<%# i%>" Text="<%# i %>" />
<%}%>

A: You need to be careful how you actually render this.  Note that HTML ids that start with a number are illegal according to the specification.  I would prepend some alphabetic character to the id value to be sure that it is both legal HTML and that the control id generated is legal for ASP.NET.  It's unclear to me whether it's legal or not to use just a numeric value for a control id.  Note that ASP.NET control id characters must be alphanumeric or an underscore.
HTML Reference:

ID and NAME tokens must begin with a
  letter ([A-Za-z]) and may be followed
  by any number of letters, digits
  ([0-9]), hyphens ("-"), underscores
  ("_"), colons (":"), and periods
  (".").

ASP.NET Reference

Note: Only combinations of
  alphanumeric characters and the
  underscore character ( _ ) are valid
  values for this property. Including
  spaces or other invalid characters
  will cause an ASP.NET page parser
  error.


text:
Q: how to get motherboard serial number when /sys/class/dmi is not available on linux? I need to bind the software key with the motherboard.
Everything seems ok on systems like Slackware, Debian and Arch which run as virtual machines in VirtualBox. (/sys/class/dmi/id/product_uuid)
Now we have industry pcs, which have Arch linux and when i try to find the information about motherboard it seems to be absent. There is no folder /sys/class/dmi. I then installed dmidecode and it failed to retrieve information with error No SMBIOS nor DMI entry point found, sorry.
Is there another way of getting the information i need?
If you know another, alternate or better, way of binding SW to HW then please do tell, but our goal is to let clients upgrade RAM, HDD, NIC or VGA without having us generate software serial for the new PC layout.
EDIT1: The software is created using c++, at this point i was only thinking of how to get the information using the bash script, as i can easily run the commands from my c++ program and get the output needed, but maybe there is another way using some c++ functions?


text:
Q: Stuck at starting gradle daemon I am an Android Developer.
Yesterday I opened my current project at Android Studio
and the project could not start.
An error was shown:
Gradle sync failed: Unable to start the daemon process.
        This problem might be caused by incorrect configuration of the daemon.
        For example, an unrecognized jvm option is used.
        Please refer to the user guide chapter on the daemon at https://docs.gradle.org/4.4/userguide/gradle_daemon.html
        Please read the following process output to find out more:
        -----------------------
        Consult IDE log for more details (Help | Show Log) (4s 245ms)

*

*I already edited graddle.properties to org.gradle.jvmargs=-Xmx1024m but its still not work

*I already reinstalled my android studio with its gradle but this bug still persists

*I already deleted .gradle folder on my computer but its still stuck

*I already set build process heap size in Android studio but it still not work

*I already checked my antivirus and my firewall (even turn it off) but nothing happens

I need help here, because I can't run my project at all.
Here is the gradle log:
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Caused by: org.gradle.api.GradleException: Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at
https://docs.gradle.org/4.4/userguide/gradle_daemon.html
Please read the following process output to find out more:

and this is log from daemon log
20:37:16.805 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding loopback multicast interface Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
20:37:16.805 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding IP addresses for network interface Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
20:37:16.806 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a loopback interface? false
20:37:16.808 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a multicast interface? true
20:37:16.808 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding loopback multicast interface Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
20:37:16.814 [ERROR] [system.err]
20:37:16.814 [ERROR] [system.err] FAILURE: Build failed with an exception.
20:37:16.815 [ERROR] [system.err]
20:37:16.815 [ERROR] [system.err] * What went wrong:
20:37:16.815 [ERROR] [system.err] java.net.BindException: Address already in use: bind
20:37:16.815 [ERROR] [system.err]
20:37:16.815 [ERROR] [system.err] * Try:
20:37:16.815 [ERROR] [system.err] Run with --stacktrace option to get the
stack trace. Run with --info or --debug option to get more log output. Run
with --scan to get full insights.
20:37:16.816 [ERROR] [system.err]
20:37:16.816 [ERROR] [system.err] * Get more help at https://help.gradle.org
Daemon vm is shutting down... The daemon has exited normally or was
terminated in response to a user interrupt.

A: I resolved this by turning off Hotspot on my pc. Found the solution here

A: start your local VPN app (such as 1.1.1.1)

A: *

*Check if you have something like this in any of your gradle files:
jvmArgs('someValues')

*Go to your project config:

Go to "edit configurations". Make sure you select "app".

Check the launch flags. Delete them all >:D

*Clean and rebuild your project

*You (or a program) probably changed the jvm's default run options.
Try to change them in your JVM or reinstall java and jdk if you're desperate enough.
Let me know how it goes

A: Go into your home directory and find the .gradle folder. Under that folder, there are 2 folder that I delete to remove this issue. I delete the .gradle/daemons and the .gradle/caches directory. Once I deleted those 2 directories and restarted Intellij/Android Studio, gradle sync started working.
On mac/linux
cd ~/.gradle
rm -fr caches daemon

A: Try to do the following thing

*

*Turn off pc hotspot

*Restart your system

*Invalidate cache and restart pc


text:
Q: Sizing cache in Internal Memory I'm looking to use internal memory to store my cache files instead of external storage. The main reason is that I need my app to function even if external storage is shared with a computer.
The dev docs say "You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB.".
Is this text just too old? Devices I've seen in the last 12 months have hundreds of megabytes of internal memory (tablets can have gigabytes - and I'm not confusing different types of storages here).
Even a decent thumbnail on a large screen can easily be around 20-30kbytes and you can display 50 thumbnails on the screen at once. If you do some scrolling, you'll be using way more than 1MB.
Do you guys think I can go with let's say 10 megs (not going higher, maintaining it properly)?
Do you know about any Google App or other popular app that maintains way larger cache in internal storage than 1MB?
Edit:
I'm asking about this type of memory:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

A:
Devices I've seen in the last 12 months have hundreds of megabytes of internal memory (tablets can have gigabytes - and I'm not confusing different types of storages here).

Newer devices have more storage. Older devices have less storage. By only supporting newer Android OS updates, you will tend to have devices with more internal storage. And, starting with Android 3.0, internal and external storage work from the same space (external storage is effectively a subdirectory within internal storage) and external storage should always be available.

Do you guys think I can go with let's say 10 megs (not going higher, maintaining it properly)?

On Android 3.0 and higher, sure.
On Android 2.3 and higher, maybe.
On Android 2.2 and lower, I wouldn't.
And, in any of those cases:

*

*Allow the user to configure the cache size

*Honor ACTION_DEVICE_STORAGE_LOW broadcasts to trim your cache


text:
Q: Why isn't this a valid method to create a default struct instance in C? So suppose I have the following two files:
// main.h

struct Player {

    int health;
    int stamina;

};

// main.c

#include "main.h"
#include <stdio.h>

int main() {

    struct Player newPlayer;
    newPlayer.health = 100;
    newPlayer.stamina = 100;

    return 0;
}

This works fine.
Now suppose I have these two files:
// main.h

struct Player {

    int health;
    int stamina;

};

struct Player defaultPlayer;
defaultPlayer.health = 100;  // error here
defaultPlayer.stamina = 100; // error here

// main.c

#include "main.h"
#include <stdio.h>

int main() {

    struct Player newPlayer = defaultPlayer;
    return 0;
}

The error in question is:
Unknown type name 'defaultPlayer'
[clang: unknown_typename]

My question is: Why can't I define a default struct in the .h file?

A: You cannot assign values to members at the file scope because only declarations and definitions are allowed on the scope level.
While defaultPlayer.health = 100 is an expression.
To set default values put it into struct initializer:
struct Player defaultPlayer = {
  .health = 100,
  .stamina = 100,
};

Moreover it may be a good idea to make it const.
You can make it an extern symbol. The defaultPlayer would only be declared in main.h and defined main.c.
// main.h
extern const struct Player defaultPlayer;

//main.c
const struct Player defaultPlayer = {
  .health = 100,
  .stamina = 100,
};

Cons: the compiler cannot inline values of members for translation units other than main.c.
Or use a static object in the header.
// main.h
static const struct Player defaultPlayer = {
  .health = 100,
  .stamina = 100,
};

Cons: compiler may complain about unused variables. What can be silenced by adding a dummy function:
static inline void dummy(void) { (void)&defaultPlayer; }

The third option is to make it a macro that expands to the compound literal.
#define defaultPlayer (const struct Player){ .health = 100, .stamina = 100 }

IMO, works the best.

A: A naive try:
A header defines the interface the object will offer to other objects. Therefore it should not contain any implementation detail.
Imagine you have the following files:
/* pretty_print.h */
// header guard
void pretty_print(char* str);

/* pretty_print.c */
#include <stdio.h>
#include "pretty_print.h"
void pretty_print(char* str) {
    printf("%s", str);
}

#include "pretty_print.h"
int main() {
    pretty_print("Hey there");
}

There will be two objects generated: main.o and pretty_print.o
None of which is yet executable. Neither does main.o contain any function pretty_print.
Linking both together will provide main.o the necessary pretty_print function (as well as do some more stuff).
Now assume there is some sort of data, let's say int x in the pretty_print.h .
As main.o included the header file, there will be such an x. However, pretty_print.o will have an x as well, as it includes pretty_print.h. So there will be two x and the compiler can't know which one to choose.
But I can declare the struct, I just can't change it's values
Yes you can, but you shouldn't declare instances in headers.
To answer, why you can't change it's values, remember there is a main function. When is this "global code" in your execution path? When is it intended to be run?
Please just fix...
You can always use struct initialization in the following way:
struct foo_t {
    int x;
};
struct foo_t foo = { .x = 42 };

If you run in any further errors I assume you have to use the extern keyword with a pointer to a player-struct and initalize it with a default player in main


text:
Q: Determining selected state of jQuery Buttons I've got two radio buttons in a .net page which are being transformed to jQuery buttons a la http://jqueryui.com/demos/button/#radio
When the page is loaded I have button 2 as checked. When clicking the buttons I'm firing the postback event. Problem is you can click on that button that is selected by default on the initial load i.e. Button 2, the postback is fired but the event handler isn't called in the .net code behind because the radio button is already classed as selected (and in normal circumstances wouldn't allow the postback to fire).
To get around this I've added the e.PreventDefault() method BUT this is causing issues when Button 1 is clicked because before the click handler is called the button is set to selected. Therefore, in every case in the following code e.PreventDefault() is called:
$(document).ready(function(){
    $("[id*='rbPayable']").click(function(e){
        if ($("[id*='rbPayable']").attr("checked"))
            e.preventDefault();
        else
            setTimeout('__doPostBack(\'this.id\',\'\')', 0)
    })
    $("[id*='rbReceivable']").click(function(e){
        if ($("[id*='rbReceivable']").attr("checked"))
            e.preventDefault();
        else
            setTimeout('__doPostBack(\'this.id\',\'\')', 0)
    })
});

What is the best way for me to load the page and effectively be able to do the following:
'If rbReceivable is checked then don't do anything otherwise do a postback.'

A: here, try something like this
$(document).ready(function() {
    $('#radio').buttonset();

    // create a handle for the initially checked button.
    var checkedButton = $('.radio:checked');

    // assuming all your radio buttons have 'radio' classname
    $('.radio').click(function() {
        var button = $(this);
        if ( button[0].id == checkedButton[0].id ) {
            return false;
        } else {
            // do stuff
            checkedButton = button;
        }
    });
});

A: I fixed this another way:
$(document).ready(function(){
    if ($("[id*='rbReceivable']").attr("checked"))
    {
        $("[id*='rbPayable']").click(function(e){
            setTimeout('__doPostBack(\'this.id\',\'\')', 0)
        })
    }
    else
    {
        $("[id*='rbPayable']").click(function(e){
            setTimeout('__doPostBack(\'this.id\',\'\')', 0)
        })
    }
});

Doing this sets the click handler on the other button when the selected button is loaded as checked.