text:
Q: Could not find org.codehaus.groovy:groovy-all:2.4.12 After an update of android studio and gradle, I can not compile (in release mode) my application anymore.When I try to generate the APK, I receive this error:

Could not find org.codehaus.groovy:groovy-all:2.4.12.
  Searched in the following locations:
      file:/Users/antonioleva/Library/Android/sdk/extras/m2repository/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.pom
      file:/Users/antonioleva/Library/Android/sdk/extras/m2repository/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.jar
      file:/Users/antonioleva/Library/Android/sdk/extras/google/m2repository/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.pom
      file:/Users/antonioleva/Library/Android/sdk/extras/google/m2repository/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.jar
      file:/Users/antonioleva/Library/Android/sdk/extras/android/m2repository/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.pom
      file:/Users/antonioleva/Library/Android/sdk/extras/android/m2repository/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.jar
      https://maven.google.com/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.pom
https://maven.google.com/org/codehaus/groovy/groovy-all/2.4.12/groovy-all-2.4.12.jar
  Required by:
      project : > com.android.tools.lint:lint-gradle:26.1.3

This is my gradle:
    buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
    }
}
apply plugin: 'android'

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation('com.android.support:multidex:1.0.1') {
        exclude module: 'support-v4'
        exclude module: 'support-fragment'
        exclude module: 'internal_impl-23.0.1'

    }
    implementation('com.android.support:support-v4:23.0.1') {
        exclude module: 'support-v4'
        exclude module: 'support-fragment'
        exclude module: 'internal_impl-23.0.1'
    }

    implementation('com.android.support:appcompat-v7:23.0.1') {
        exclude module: 'support-v4'
        exclude module: 'internal_impl-23.0.1'
        exclude module: 'support-fragment'
    }
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    //implementation 'org.codehaus.groovy:groovy-all:2.4.12'
}

android {
    compileSdkVersion 23
    buildToolsVersion '27.0.3'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        multiDexEnabled true
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude '...'
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        androidTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

repositories {
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

A: I had the same problem, everything was correctly installed but not found; I also refreshed everything that was refreshable in IntelliJ; I removed all the temporary folders in the project. Everything was useless.
Then I solved the problem like that, from terminal:
gradlew build --refresh-dependencies

This solved the issue.
In extremis, you can delete the content of the global cache folder used by gradle (it was not necessary in my case); for example could be this:
C:\Users\USERNAME\.gradle\caches

Mi esperas, ke tio helpos iun, ĉar mi perdis multe da tempo.

A: Worked fine for me
build.gradle
buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url "https://jitpack.io"
        }
        google()
    }
    ...
}
...
repositories {
    google()
    jcenter()
    maven {
        url "https://jitpack.io"
    }
}

app/build.gradle
dependencies {
    implementation 'org.codehaus.groovy:groovy-all:2.4.12'
}


text:
Q: Fitting a Survival Function with OLS - What Points To Use? I'm trying to fit a survival function that is generated from discrete data. Is it correct to use Ordinary Least Squares, and if so what points do I use to do the fit?

A, B or C? Or other?
Or am I doing this completely wrong?
Thank you.
Edit: Some more info as requested. I'm comparing methods to fit power law distributions of rank-frequency data. Similar to White et al's "On estimating the exponent of power-law frequency distributions", but specifically on rank-frequency distributions, which behave slightly differently to general power laws.
I was purposefully a bit vague initially because I know that fitting OLS to a ccdf is problematic, not to mention on a log-log scale. Nevertheless the method is used often in the literature. And so I want to implement it in the best way possible, and then compare with other methods such as maximum likelihood estimation.
So, if you absolutely had to fit a ccdf using OLS how would you go about it?

A: As stated in my comments, I typically wouldn't recommend using OLS for this type of data.
But given that you are insistent in your update on using OLS in and given that you want to use this method to seemingly compare your work with using OLS methods which, according to you is a standard approach in your field, then I'd recommend simply attempting A, B, and C, and then report all your results.  Alternatively, if you are sure you need to use OLS, and if your interest only lies in accurate prediction, I'd recommend you try all 3 methods on a training data set.  Then make your predictions on a hold-out sample and chose the method that performs best (i.e. whichever methods results in the smallest Mean Squared Predicted Error).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Golang map put if absent? I have a map of the format:
map[string]map[string]int
In this main map, I want to do something like putIfAbsent("key", new HashMap<>() as we have in Java. What is a clean and shorthand way to do it in Go?

A: You can do:
var val map[string]int
val, exists := m[key]
if !exists {
    val = make(map[string]int)
    m[key] = val
}

If you don't need the val in the code coming below this:
if _,exists := m[key]; !exists {
    m[key]=make(map[string]int)
}

A: If you don't intend to use the value right away, here you go...
m := make(map[string]map[string]int)

if _, ok := m["unknown"]; !ok {
    m["unknown"] = make(map[string]int)
}

Below is a suggestion for improvement:
To keep things clean and easy to understand, you can define your own types. For example, if your data is a mapping of "cities to persons to age", I would do it like this:
type Person map[string]int
type City map[string]Person

m := make(City)

if _, ok := m["Dhaka"]; !ok {
    m["Dhaka"] = make(Person)
}

A: func main() {
    var testMap map[int]interface{}
    testMap = make(map[int]interface{})

    var addMap map[int]string
    addMap = make(map[int]string)
    addMap[1] = "999"
    addMap[2] = "888"

    Add(testMap, 111, addMap)

    for key, val := range testMap {
        fmt.Println(key)
        for key2, val2 := range val.(map[int]string) {
            fmt.Println(key2, val2)
        }
    }
}

func Add(_testMap map[int]interface{}, _key int, _val map[int]string) {
    _, exist := _testMap[_key] // _ -> value
    if exist == false {
        //addmap
        _testMap[_key] = _val
    } else {
        //whatever wanna to do
    }
}


text:
Q: Inquiry on Dax formula on COUNTROWS or SUM for aggregation I would like to calculate the total number of student enrolled to each service provider but I do not want the same student counted double if they have enrolled difference course with the same company. Below is the sample data:

Service Provider
Course
Student name

company A
C1
Jane

company A
C4
Cherry

company A
C4
Jane

company A
C8
Kethna

company B
C2
Mic

company C
C5
Jane

I tried to use COUNTROWS but it only take 1 variable that is the table name. Using SUM or SUMX is also not possible due to not numerical value for each row.

A: Try this
Measure =
CALCULATE (
    DISTINCTCOUNT ( 'Table'[Student name] ),
    ALLEXCEPT ( 'Table', 'Table'[Service Provider] )
)


text:
Q: YouTube jsapi video card Is there a way through the JS api for YouTube embeds to make the end of a video show to users subscribe / about card. I've searched high and low and can't seem to find any ways of doing so. Any other solutions outside of the JS api? Maybe adding or replication with DOM or other method? Thanks!
EXAMPLE: https://www.dropbox.com/s/ivtcxnbszrylwzi/Screenshot%202014-04-09%2015.53.21.png

A: One possibility, if you were to use the iFrame API, would be to bind to the playerStateChange events and listen for the YT.PlayerState.ENDED event ... and when you hear it, you replace the video with your subscribe button. Some sort of setup like this:


text:
Q: What's the best way to modify a variable using a function, but inside of another function? The main problem I'm running into (specific to Python, don't mark as duplicate for another language please) is that I don't know how to modify a string variable inside a function, with a nested function, if that makes any sense. This code should do a much better job explaining what I mean.
def insideAFunction():
    variableToMod =  "test"

    def modFunc():
        if 1 > 0:
            variableToMod = "TEST"

    print("before: " + variableToMod)
    modFunc()
    print("after: " + variableToMod)

def insideAFunction2():
    variableToMod =  "test"

    def modFunc():
        global variableToMod
        if 1 > 0:
            variableToMod = "TEST"

    print("before: " + variableToMod)
    modFunc()
    print("after: " + variableToMod)

insideAFunction()
insideAFunction2()

Output:
before: test
after: test
before: test
after: test

The desired output would be:
after: TEST

I know I can get it to work by just defining variableToMod outside the insideAFunction() and make the global call like in insideAFunction2(), but I want to know if it's possible to do it completely inside the function.

A: *

*You are changing value of variableToMod in modFunc but not returning it.

*Second print variableToMod statement is still printing but it takes the variableToMod  you declared in line 2

So it will always print the same. You need to return a value from modFunc and assign it to outer variableToMod before printing. This way the result will be
before: test
after: TEST
def insideAFunction2():
    variableToMod =  "test"
def modFunc():
    if 1 > 0:
        variableToMod = "TEST"
        return variableToMod

print("before: " + variableToMod)
variableToMod = modFunc()
print("after: " + variableToMod)

A: You are probably using Python 3.x (I don't believe this is an issue in Python 2.x), which means you need to use the nonlocal keyword in your inner functions.
I'm guessing the version using global doesn't work because you've already defined a local variable with the same name, which would shadow any global variable with that name.
EDIT:
Actually, Python 2.x does have this same behavior, but it doesn't support the nonlocal statement it seems. I guess one solution might be to pass in the local() dictionary and change the entries in that inside your inner function, but I'm not sure that would work. I'd have to try it out.

A: Use return function works fine on me:
def insideAFunction():
    variableToMod =  "test"

    def modFunc():
        if 1>0:
            variableToMod = "TEST"
            return variableToMod

    print("before: " + variableToMod)
    variableToMod = modFunc()
    print("after: " + variableToMod)

insideAFunction()

the output is:
before: test
after: TEST


text:
Q: What does the noun 'foil' mean, in 'a foil for a Justice's rhetorical gambit'? Source, para 2: The importance of Stevens' good manners, by Prof Pamela Harris, 2010 Apr 26.

For the public, Justice Stevens' manners are perhaps most evident at oral argument.  Since the Justice announced his retirement, many lawyers already have commented fondly on the Justice's habit of prefacing his remarks with a request:  "May I ask you a question?"  And what follows is indeed a question"" [sic for these two quotation marks] an exceptionally hard question, usually, but an actual question, in search of an actual response, so that the advocate becomes a meaningful part of the process rather than a foil for a Justice's rhetorical gambit.  In substance as well as form, Justice Stevens' style of questioning accords real respect to the lawyers who appear before him, treating them as valued participants with something important to offer.  No wonder that so many of them speak so highly of the Justice.

I can infer that foil here is used figuratively and am guessing that it means a static sounding board or passive tool, which is how a Justice, who cares only about blazoning a rhetoric gambit, would treat an advocate?    Yet which definition applies?

A: A "foil" is something or someone whose appearance contrasts with that of something or someone else, the better to show the other thing or person off.
The "foil" is a metaphor often used when describing the role of a character in a drama.  A tired example: a  bungling, good-natured pal might be the sidekick of a slick casanova, to highlight the lover's smooth-talking ways and make him seem all the more accomplished in that domain.
So we have the expressions "a mere foil" or "merely a foil", which describe characters whose role is simply to make another character look better or to highlight that other character's personality traits.
Judge Stevens didn't ask a question of the lawyer just so the judge could then proceed to say what he wanted to say, using the lawyer as a way to broach a subject (a "rhetorical gambit") and present his own views on it; rather he was actually interested in what the lawyer had to say.


text:
Q: how to test a static library project with codeblocks and target definition I have a static library project and now i want to test some functions. To achive my goal i added a new target of type console, because when i try to "run" my library i get right the message "...select an host application to run...", then i added to this target a test file, test.c, that use some function.
From my knowledge, targets are different way to process sources file, so the release target produces a *.a file, and the debug target produces other.
// test.c
#include <stdio.h>

struct object_geometry *load_ObjModel(char *fileName);

int main()
{
    printf("Buongiorno!");
    load_ObjModel("../dado.obj");
    return 0;
}

After writing test.c, i select the last created target and during debugging something doesn't work, because i can't use the modality "go line by line", or putting breakpoint in the above code, so:

*

*how can i debug my library, without the creation fo a new project?

*what's a target in codeblocks?

*(other useful related informations are appreciated)


text:
Q: Legend with ggplot2 with geom="path" and alpha option I'm a R user from way back but struggling to get my head around ggplot2. In this example, I cannot get a legend when I use the geom="path" option also with the alpha setting. If I set geom="point" it appears fine.
tmp <- data.frame(cx=rnorm(21),cy=rnorm(21),labels=c(rep("a",7),rep("b",7),rep("c",7)))

p1 <- qplot(data=tmp,cx,cy,geom="point",colour = labels, size=I(5), alpha=I(0.5))

Then the plot of points appears fine, including a legend with the correct alpha setting showing the dots. Adding in geom="path"
p2 <- qplot(data=tmp,cx,cy,geom="path",colour = labels, size=I(5), alpha=I(0.5))

Gets me a plot with the lines joined and correctly plotted with the alpha setting, and the legend also appears but is blank - eg. no alpha colors.
Is this possible to do?
It all works fine by dropping off the alpha parameter and I get solid colors in the plot and also the legend.
Update: Thanks for your comments so far but I guess this is just me or my setup as I still have this issue. An example of what I get in the link ...

http://i.stack.imgur.com/LiEwD.jpg
And for completeness...
> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: i386-pc-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252       LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                            LC_TIME=English_United Kingdom.1252
attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base
other attached packages:
[1] scales_0.2.1  ggplot2_0.9.1
loaded via a namespace (and not attached):
[1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2       labeling_0.1       MASS_7.3-17        memoise_0.1
[7] munsell_0.3        plyr_1.7.1         proto_0.3-9.2      RColorBrewer_1.0-5 reshape2_1.2.1     stringr_0.6
[13] tools_2.15.0

A: I was finally able to reproduce what you are seeing, but only under very specific circumstances (and quite by accident that I happened to stumble across it). Given the circumstances, I'm pretty sure being on Windows (or rather, using the windows device driver) is necessary.
Using tmp, p1, p2 from the question:
dev.new()
p1
p2

The dev.new() is important so that you are starting with a fresh window (because something becomes corrupted later).  These commands give appropriate plots (don't do anything with the plot window).  Now, if you "scroll" (History -> Previous or Next) or resize window at this point, nothing is drawn in the legend boxes. Prior to doing that, can save and get the right legend. After doing that, saving (File -> Save as...), legend
boxes are blank. If you use the "scroll" option (I got it using the mouse wheel, repeatedly scrolling down, as I don't have recording on by default and therefore the Previous and Next options are grayed out), I (eventually) get the following on the console:
Error: VECTOR_ELT() can only be applied to a 'list', not a 'character'

which can be repeated some number of times before I eventually get:
Error: REAL() can only be applied to a 'numeric', not a 'character'

A workaround is to use ggsave. Since that creates a new device, you don't have to worry about the windows device getting into some broken state.
ggsave("tmp.jpg", p2)

I think the behavior I'm seeing is a bug in the windows graphics device.


text:
Q: iPhone SDK: Record time of buttons in a sequence to play back I've got an app in development where you press a button to play a sound using System beep.
Instead of recording the output, I was thinking of recording the timing of when the buttons were pressed, so when the user presses a 'Play' button, the buttons are pressed in the same timing the user has pressed them, so it acts like the iPhone has recorded the sounds, but it's just playing them in sequence. I'd like this to occur once the user has pressed a Record button.
Example:

*

*User presses record

*Timing starts

*
records timing of each button pressed and when

*Timing stops after a button has been pressed

*PLay button plays back the sequence of events

Can anybody give any ideas on coding, documents to read etc.
Thanks a lot!

A: http://pastie.org/376474
This should hopefully help you out a bit.
It works in essence, though I haven't actually tested it, so I'm not positive it works.
I assume you can read through it and find a way to fit it in your own code.
Good luck!

A: Many system time methods have a way to get the value in seconds since the epoch.
Depending on the granularity of the system clock you can just grab the system time of the start button press and grab the time again when each button is pressed.
To calculate the timing just subtract the start time from the button press time.


text:
Q: try catch block not catching limit exception after query I have a SOQL query call inside a try catch block, because I want to catch if a LimitException is thrown, but for some reason, when the exception is thrown after the query,the aura handled exception is not thrown and in my LWC, I get the original exception.
List<Producto__c> productos = new List<Producto__c>();
    try{
        productos = Database.query(queryProducto + getQueryOrder() + qryLimit);
    }catch(LimitException e){
        System.debug(LoggingLevel.WARN, 'CATCH');
        throw new AuraHandledException('La busqueda arrojó demasiados registros. Aplique más filtros');
    }

As you can see, the query IS  being executed after the exception (it seems at least), but when checking the debug logs, we never see the debug message inside the catch block.

Is it a bug? Or the exception is being thrown before the query or something like that... This never happened to me.

A: Exceptions thrown because you've exceeded a governor limit are un-catchable.
They will always cause your code to stop executing at the point where the limit is exceeded. That's how Salesforce is able to enforce governor limits.
Instead of trying to catch exceptions, it's up to us to design and write our code in a way that is unlikely to run into the limits or to check the various items that the Limits class provides to prevent executing something that would put you over a limit.
For some things, like the number of SOQL queries, it's easy to tell when you're about to go over the limit, so something like
if(Limits.getQueries() < Limits.getLimitQuery()){
    // safe to run another query
}

will work
For other things, like the number of query rows, it's harder to tell if you're going to exceed the limit. In those cases, it can be helpful to build in a safety threshold
if(Limits.getQueryRows() < Limits.getLimitQueryRows() * 0.9){
    // it's probably safe to run a query
    // ...as long as you think it won't return more than 5,000 (50,000 * 0.1) rows
}


text:
Q: Minimizing iOS Mail app breaks z-index in CSS animation Edit: I'm now confident that this is related to the z-index property of the arrows. If the z-index of the left arrow is higher than the right arrow, the left arrow image will be inserted on the right. If the z-index of the right arrow is higher or equal to the left arrow, the right arrow will be inserted on the right. I still have no idea why this is happening and why it won't just put the images where I tell it to.
Original:
I'm creating an email with a carousel of images that should slide back and forth when the user clicks on arrows to the sides or tabs at the bottom. But I'm seeing some strange behavior in the iOS native mail app and it's making me crazy. When I first receive and open the email, everything works the way it's supposed to. But if I lock my phone or even just minimize the Mail app and reopen it, the arrows will start breaking.
I insert the arrows with a content(url) property on an ::after psuedo-element. The most common error is the right-facing arrow showing up on the left side when all but the first frame is showing. But sometimes it's the first frame that has the wrong arrow and as soon as I change to another frame, the correct one comes back. I also can see the left arrow flickering in before being replaced by the right arrow. Sometimes the top half of the arrow is correct and the bottom half is wrong. It's all very hard to pin down and very frustrating.
I've seen recommendations to add -webkit-backface-visibility: hidden; (which didn't work) and -webkit-perspective: 1000; (which breaks my absolute positioning on the arrows) and -webkit-transform: translateZ(0); (which also breaks my absolute positioning) to the parent.
Here's a gif of what I'm seeing in my app: https://i.imgur.com/OjoTIk9.gifv
Here's my full HTML and CSS:

        <input id="car-cbox-support" type="checkbox" checked="" style="display:none!important">
        <input name="car-radio" type="radio" id="car1-radio-1" class="car-radio car-radio1" style="display:none!important">
        <input name="car-radio" type="radio" id="car1-radio-2" class="car-radio car-radio2" style="display:none!important">
        <input name="car-radio" type="radio" id="car1-radio-3" class="car-radio car-radio3" style="display:none!important">
        <input name="car-radio" type="radio" id="car1-radio-4" class="car-radio car-radio4" style="display:none!important">

red

blue

green

yellow

A: z-index does not work with the majority of the email clients.
E:after does not work with the majority of email clients.
webkit-animation is only going to work with IOS, Apple mail.

*

*https://www.campaignmonitor.com/css/positioning-display/z-index/

*https://www.campaignmonitor.com/css/selectors/after/

*https://www.campaignmonitor.com/css/animations/animation/
Good luck.

A: I ended up fixing it by making the following changes to the CSS:
.carousel .car-rtn {
      z-index: 200;
      width: 10%;
}

And I also got rid of the drop shadow on the .carousel .car-ltn::after class.


text:
Q: Order of $f(n) = 4n + 6n^3 - 8n^5$ If a function $$f(n) = 4n + 6n^3 - 8n^5$$ then the order of $f$ is:
The answer I have is $\log(n)$, but I'm not sure if it's right.

A: The order of a polynomial is usually its largest power. In this case, it would be 5.
If instead you are trying to find $g$ s.t.
$$
f\in O\left(g\right)\text{ as }n\rightarrow\infty,
$$
(big O notation) then $g$ can be $n^{5}$.

A: Let
$f: \mathbb{N} \to \mathbb{R}$
be the function
$$f(n) := 4n + 6n^{3} - 8n^{5}.$$
There are two possibilities:
1) $f(n) = o(n^{6}),$
for we have
$$\frac{f(n)}{n^{6}} \to 0$$
as $n \to \infty.$
2) $f(n) = O(n^{5}),$
for we have
$$\frac{f(n)}{n^{5}} < -7$$
eventually.


text:
Q: How to add validation to fields in Odoo? I have to add validation in the signup form for Odoo (which is the auth_signup_login_templates.xml file in the auth_signup module. I need to ensure that the Name contains on alphabets and are within 3 to 15 characters. Right now, by default, the code for the name is:

            Your Name
            <input type="text" name="name" t-att-value="name" id="name" class="form-control" placeholder="e.g. John Doe"
                required="required" t-att-readonly="'readonly' if only_passwords else None"
                t-att-autofocus="'autofocus' if login and not only_passwords else None" />

The xml page can be found here

A: For validations we prefer Javascript/Jquery :)
eg:
$('#name').keypress(function (e) {
    var regex = new RegExp(/^[a-zA-Z\s]+$/);
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }
    else {
        e.preventDefault();
        return false;
    }
});

but for min and max length, you can use data attributes.
eg:
<input data-rule-minlength="3" data-rule-maxlength="8" data-msg-minlength="Exactly 3 characters please" data-msg-maxlength="Exactly 8 characters please">


text:
Q: Rspec: Call a method after a failure I'm trying to find out how to call a method in a spec helper after each failure. I feel bad asking this question because it seems like it'd have been asked before, but it's sort of unGoogleable to me since all I find is detecting failures in after(:each).
Basically, I want to set up a notification to myself, something like:
def you_failed
    system "say -v Bad test failed"
end

A: You will want to create a custom formatter. Look at the Core::BaseFormatter and Core::BaseTextFormatter. You'll find a example_failed method. Override this method in your custom formatter to include the code to call when the example fails. Note this can run multiple times depending on the number of failed tests.


text:
Q: Triggering custom action in a silence mode I'm working on a setup that validate many user inputs by a custom action. The event "DoAction" of publish control are doing very good job, but I figured out that no one custom validation are triggered if I execute the setup in silence mode.
I tried InstallExecuteSequence like the Yen Tran's blog (http://yentran.org/blog/2013/09/27/wix-executing-custom-action-before-starting-windows-service/) but still not working.
<Frament>
<Binary Id="CALibrary" SourceFile="$(var.Project.Installer.CustomAction.TargetDir)CustomAction.CA.dll" />
<CustomAction Id ="ProxyCheck" BinaryKey="CALibrary" DllEntry="Proxy" Execute="immediate" Return="check" />
<CustomAction Id ="ActivationCheck" BinaryKey="CALibrary" DllEntry="Activation" Execute="immediate" Return="check" />
</Frament>

...

<Fragment>
<InstallExecuteSequence>
  <Custom Action="ActivationCheck" Before="InstallInitialize" Overridable="yes">PROXYSERVER</Custom>
</InstallExecuteSequence>

A: With Orca.exe I found that the action was not configured in InstallExecuteSequence no matter what I do. Reviewing all the files for the thousandth time, I found that I was putting the instruction of InstallExecuteSequence in a wrong place, moved into the <Product> </Product> and then everything works well.


text:
Q: what weight initialization does the mlp classifier in sklearn use? I need to know which method of weight initialization the MLPClassifier in Sklearn uses. I know there are several ways to initialize weights in a Neural Network, for example random normal or randorm uniform or glorot. However, I did not find any information on which of these methods is used in Sklean's MLPClassifier.

A: Based on the source code, parameters are initialized with the method from this paper by Glorot et al.:
def _init_coef(self, fan_in, fan_out, dtype):
    # Use the initialization method recommended by
    # Glorot et al.
    factor = 6.0
    if self.activation == "logistic":
        factor = 2.0
    init_bound = np.sqrt(factor / (fan_in + fan_out))

    # Generate weights and bias:
    coef_init = self._random_state.uniform(
        -init_bound, init_bound, (fan_in, fan_out)
    )
    intercept_init = self._random_state.uniform(-init_bound, init_bound, fan_out)
    coef_init = coef_init.astype(dtype, copy=False)
    intercept_init = intercept_init.astype(dtype, copy=False)
    return coef_init, intercept_init


text:
Q: Hapi/Joi Validation: How to process text to a specific format Is it possible to pass a string to hapi/joi and for it to process it and return a required format? For example consider the code below:
const acceptedCitiesSchema = Joi.object({
    isCapitalCity: Joi.boolean().default(true),
    cityName: Joi.string().valid('MyCity', 'YourCity').required(),
})

How can I make it that even if a user inputs 'myCity' or 'yourCity' joi automatically converts them to a format that the first word is capitalized('MyCity' and 'YourCity' respecively). And returns the desired results? Is it possible to achieve this using hapi/joi?

A: You can try the following:
const schema = Joi.object({
    isCapitalCity: Joi.boolean().default(true),
    cityName: Joi.string().valid('MyCity', 'YourCity').insensitive().required()
})

And while validating with schema, you can use the convert:true option as:
schema.validate({"cityName": "myCity"}, {"convert": true})

Alternatively, you can directly provide additional preferences to convert the Joi validated object in the schema:
const schema = Joi.object({
    isCapitalCity: Joi.boolean().default(true),
    cityName: Joi.string().valid('MyCity', 'YourCity').insensitive().prefs({convert:true}).required()
})

Here is a link to working example: https://repl.it/repls/HarmfulEvenPhases


text:
Q: Help tranformation of random variables? Let $X$ have the p.d.f $f(x)= \frac{x^2}9$ , $0 < x < 3$, $0$ otherwise, find the pdf of $Y = X^3$
I have this exercise, but I do not know how to start, how do I know if it is a one to one transformation?
Once I have the inverse, how do I obtain the jacobian of the inverse of Y? I am lost help

A: The cdf of $Y$ is
$$F_Y(y)=P(Y<y)=P(X^3<y)=P(X<\sqrt[3]y)=
\begin{cases}
0,&\text{ if } y<0\\
\int_0^{\sqrt[3]y}\frac{x^2}{9} \ dx&\text{ if } 0\le y \le 27 \\
1&\text{ otherwise}
\end{cases}.$$
Between $0$ and $27$
$$F_Y(y)=\int_0^{\sqrt[3]y}\frac{x^2}{9} \ dx=\frac1{27}\left[x^3\right]_0^{\sqrt[3]y}=\frac1{27}y.$$
It follows that $Y$ is uniformly distributed over $[0,27]$.


text:
Q: SKProductsResponse returning invalidProductIdentifiers on simulator inspite uniformity between the productId in application and iTunes Connect As a beginner whil trying in-app purchase in iOS application I followed the following steps :

*

*enabled in app purchase in capabilities.

*created provisional profile on developer account and downloaded
it.

*created iTunes Connect app submission.

*created in-app purchase products in Features sections of iTunes
Connect.

*created the same array of product identifiers. Also implemented required delegates in view controller class.
#import <UIKit/UIKit.h>
#import <StoreKit/StoreKit.h>
@interface ViewController :UIViewController<SKProductsRequestDelegate,SKPaymentTransactionObserver,SKRequestDelegate>

in viewdidload()
 productIds = [NSArray arrayWithObjects:@"pro1",@"pro2", nil];

also,
  -(void)viewWillAppear:(BOOL)animated
   {
   if([SKPaymentQueue canMakePayments]){
   SKProductsRequest *requestPro = [[SKProductsRequest alloc]initWithProductIdentifiers:[NSSet setWithArray:productIds]];
  requestPro.delegate = self;
  [requestPro start];
   }
   else{
    NSLog(@"Cannot perform In App Purchases.");
    }
    }

*but -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response implementation is returning invalid products.

Please help me in understanding whats lacking.

A: You need to test most in app purchase related functions on a real device. They don't work on the simulator!


text:
Q: How do you update an element after adding it to a database using AngularJS http calls? So currently, I have a method that adds my objects to my database. It works, and is written as such:
    var $scope.insertToDB = function(myObj){
        $http.put("my_DB_Link", myObj).then(function(success){
            console.log(success);
        },function(error){
            console.log(error);
        }
    }

I figured that updating this object would be fairly easy, but so far, I have been proven wrong. I have used GET to test to assure my data is in there, and so far it is, but with an "_id" tag added onto it. Now, I figured that I could use the same method to update the data:
    var $scope.updateObjInDB = function(myObj){
        $http.put("my_DB_Link", myObj).then(function(success){
            console.log(success);
        },function(error){
            console.log(error);
        }
    }

But, this always returns a 400 Bad Request exception. When I replace the "put" with "get" it gets the data without a problem it seems, however, it doesn't seem like you can update the object with the "put" call. Also, "post" throws a 405 Method Not Allow exception. How do I update my object using a similar method my insertToDB() function?


text:
Q: Installing PostgreSQL and pyscopg2 on Snow Leopard I'm still a complete beginner in the field of web development and I'm trying to set up the Django environment. I'm reading "the definitive guide to django" to start my practice.
I'm running Snow Leopard (10.6.2) on a macbook 2.1GHz. It came with Python 2.6.1. Since Snow Leopard cam with Python 2.6.1 preinstalled, so I didn't do any extra set up. Maybe it needs more setup, please let me know. But I've ran it, and it works.
I installed django straight right from the book. I've ran it, and so far it works.
The Database configuration is the one stifling me.
I tried installing MySQL with MySQLdb module for python, but it had complications with the difference between 32 & 64 bit architecture (either mysql had 64 and python had 32 OR vice versa; Either way, I couldn't figure it out). I've read many forums and tinkered with it for hours, still couldn't fix it and I just gave up.
So I tried the next best thing (or so I thought), Let's try to set up Postgre instead. So, I went to the official Postgre website and picked the Mac OS X installment package. I download it, extract it, and all it had was an ".app" installer and a "README". I ran the installer, blah blah blah, I followed the instruction, it did this, it did that. At the end, apparently Postgre is installed.
I didn't feel completely sure if it was installed, so I searched around the internet for some answers. Well, I found the official documentation for installing Django for Mac, but the steps to install
Postgre was completely different. Maybe the ".app" installer did most of the configuration listed in those steps, I don't know.
Then I went to the terminal and type in:
psql -V

(to check which version of Postgre I just installed)
AND
sudo -u postgres pg_ctl start

(to run the database)
'psql' or 'pg_ctl' commands could not be found. To me, this is kind of saying Postgre was not installed or there are some setup I still need to do.
So I started looking at the first steps of installing Postgre from the given instruction by Django (link above). From the instruction it says to edit the '~/.profile', even after unhiding all the files and directories, I still can't find it under my user directory.
At this point I'm just kind of frustrated and don't know where to go. I was wondering if I can get some direction/tips/howto/anythingreallyatthispoint.
I can't really install psycopg2 until I have Postgre running, but from the looks of it, it doesn't look so bad to install it (or so I hope).
Many Many thanks in advance for any help ^_^
-Tri

A: the easiest way to install these apps would be via macports (http://www.macports.org/). in my experience, the installation was fast and clean. the geodjango installation documentation has a good section on this: http://geodjango.org/docs/install.html#macports.

A: If you're just getting started, I would try sqlite first. It's file based, so there is almost no configuration. Later, if you want to upgrade to a real database, then it won't be any harder than what you're attempting now.

A: I suspect the only problem you are having is not setting path.  Add this to your ~/.bash_profile:
export PATH=/Library/PostgreSQL/8.4/bin:$PATH

Now you should be able to run the command line tools like psql.

A: I just spent a couple hours going through multiple different walkthroughs.  This was the one that eventually worked:
first install postgress with the dmg:
http://www.enterprisedb.com/products-services-training/pgdownload#osx
then follow this tutorial:
http://stubblog.wordpress.com/2009/06/07/installing-psycopg2-on-osx/
then put this in terminal export DYLD_LIBRARY_PATH=/Library/PostgreSQL/9.3/lib:$DYLD_LIBRARY_PATH
And I'm pretty sure those were the important parts of what I did..
if you get errors try sudo pip uninstall psycopg2 then sudo pip install psycopg2
if you keep getting errors about ".... something < 10.4", reinstall pip.  I think I used something like brew install python to update python... if you don't have homebrew, get it.  I'm pretty sure that's what got rid of that error.. it may have been a manual install of pip3 though.
Sorry this is all over the place, it should get you a bit closer though. At least, if you (like me) have had none of the other tutorials work.


text:
Q: Would drawing an image to a canvas be described as hotlinking if the image was from another site? If you created an image object like so:
var imageObj = new Image();
imageObj.src = urlOfImageOnAnotherWebsite;

And then drew it to a canvas on my website like so:
var canvas = document.getElementById('cnv');
var context = canvas.getContext('2d');

imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
    drawText(statusquote,date);
};

Would this be hotlinking the image? I initially am thinking no because I'm actually redrawing the image, and not hosting it.

A: Yes, the principle is the same. You are loading it from another domain.

A: Hotlinking is the act of using someone else's server and bandwidth to display content to your viewers. Since in this scenario the JavaScript still obtains the image from their site, it's hotlinking.


text:
Q: how to upload image using flutter and php in the MySQL I wanna ask how can I post an image file to the MySQL using post method? Since what I did is only upload the file pathway and not the image.
my post request:
Future addProduct() async{

var url = 'http://10.0.2.2/foodsystem/addproduct.php';

http.post(url, body: {
  "productname": controllerName.text,
  "productprice": controllerPrice.text,
  "producttype": controllerType.text,
  "product_owner": globals.userId,
  "image": _image.path,
  //"image": _image.path.split('/').last,
});

my PHP code:
<?php

  include 'conn.php';

  $product_owner = $_POST['product_owner'];
  $productname = $_POST['productname'];
  $productprice = $_POST['productprice'];
  $producttype = $_POST['producttype'];
  $image = $_POST['image'];

  //$realImage = base64_decode($image);

  $connect->query("INSERT INTO product (product_name, product_price, product_type, product_owner, image) VALUES
('".$productname."','".$productprice."','".$producttype."','".$product_owner."','".$image."')")

?>

my MySQL table

A: This is the solution that I use to upload the image to the database. Basically, I am using the image path to save into MySQL. Then the image itself I save it in the htdoc folder and it works.
Flutter code: (important library need to be imported first)
import "package:async/async.dart";

import 'package:path/path.dart';

import 'dart:io';

import 'package:http/http.dart' as http;

Future addProduct(File imageFile) async{
// ignore: deprecated_member_use
var stream= new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length= await imageFile.length();
var uri = Uri.parse("http://10.0.2.2/foodsystem/uploadg.php");

var request = new http.MultipartRequest("POST", uri);

var multipartFile = new http.MultipartFile("image", stream, length, filename: basename(imageFile.path));

request.files.add(multipartFile);
request.fields['productname'] = controllerName.text;
request.fields['productprice'] = controllerPrice.text;
request.fields['producttype'] = controllerType.text;
request.fields['product_owner'] = globals.restaurantId;

var respond = await request.send();
if(respond.statusCode==200){
  print("Image Uploaded");
}else{
  print("Upload Failed");
}

PHP code:
<?php

  include 'conn.php';

  $image = $_FILES['image']['name'];
  $product_owner = $_POST['product_owner'];
  $productname = $_POST['productname'];
  $productprice = $_POST['productprice'];
  $producttype = $_POST['producttype'];

  $imagePath = "uploads/".$image;

  move_uploaded_file($_FILES['image']['tmp_name'],$imagePath);
  $connect->query("INSERT INTO product (product_name, product_price, product_type, product_owner, image) VALUES ('".$productname."','".$productprice."','".$producttype."','".$product_owner."','".$image."')");
//$connect->query("INSERT INTO product (product_name,image) VALUES ('".$productname."','".$image."')");

?>

Result in MySQL:

Result in htdoc folder:

A: You are actually correct about storing path of the image into MySQL instead of the actual image data. MySQL is not built to store image data.
You can send image data to the backend with the way they describe here:
How to upload images and file to a server in Flutter?
Then once you receive the image data, you can store the image in a directory in the server. What you save in MySQL should only be a image path within the server or a URL to the image.

A: You can actually store image in MySQL . It's primitive type is BLOB. it's useful if image size is less, as image can loaded  fast. If image size is large then time to load it would be large hence it's not recommended to do so. Storing image path is still a better option.

A: Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.
A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.
Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.
You'll need to save as a blob, LONGBLOB datatype in mysql will work.
CREATE TABLE 'test'.'pic' (
    'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    'caption' VARCHAR(45) NOT NULL,
    'img' LONGBLOB NOT NULL,
  PRIMARY KEY ('idpic')
)

its a bad practice but it can be done. Not sure if this code would scale well, though.
  $data = file_get_contents($_FILES['photo']['tmp_name']);


text:
Q: When listing remote tags in git, what does "^{}" signify? When I do git ls-remote --tags to list remote tags, I'm getting a response like this:
45d3d8f01f5e07a0e2728012b3d50989e5971cb2        refs/tags/v1.4.6.7
c742bfaa5d2140bbbed5bb9202b30cabcb9eb531        refs/tags/v1.4.6.7^{}
a745b6d8997803e1af823582885ab17f0dba2d8e        refs/tags/v1.4.6.8
b867af5cb9469f6cfc139d355a5e7e4fc9b55a12        refs/tags/v1.4.6.8^{}

What does the ^{} signify (and should I be concerned)?

A: What you're seeing is an "annotated" tag and the commit it points to (^ means first immediate parent, in this case). e.g. in your case c742bfaa5d2140bbbed5bb9202b30cabcb9eb531 is the parent of refs/tags/v1.4.6.7.
Here's a complete example:
zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest
$ git init
Initialized empty Git repository in D:/dev/git/reftest/.git/

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ touch test

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git add-commit -m "hej"
[master (root-commit) d792079] hej
 1 file changed, 1 insertion(+)
 create mode 100644 test

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git clone --bare . /d/dev/git/reftest_bare
Cloning into bare repository 'D:/dev/git/reftest_bare'...
done.

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git remote add origin ../reftest_bare/

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git fetch origin
From ../reftest_bare
 * [new branch]      master     -> origin/master

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git branch -u origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git tag -a 1.0 -m "test"

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git push
Everything up-to-date

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git push --tags
Enumerating objects: 1, done.
Counting objects: 100% (1/1), done.
Writing objects: 100% (1/1), 158 bytes | 158.00 KiB/s, done.
Total 1 (delta 0), reused 0 (delta 0)
To ../reftest_bare/
 * [new tag]         1.0 -> 1.0

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git ls-remote --tags
From ../reftest_bare/
79d1f428cb16028a2f8b0e0599231eae2ba76b0b        refs/tags/1.0
d7920790cb316067be54ec15e4a7d27265c08fc4        refs/tags/1.0^{}

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git show 79d1f428cb16028a2f8b0e0599231eae2ba76b0b
tag 1.0
Tagger: Martin Kjeldsen <>
Date:   Thu Oct 8 20:28:14 2020 +0200

test

commit d7920790cb316067be54ec15e4a7d27265c08fc4 (HEAD -> master, tag: 1.0,     origin/master)
Author: Martin Kjeldsen <>
Date:   Thu Oct 8 20:27:12 2020 +0200

Notice how d7920790cb316067be54ec15e4a7d27265c08fc4 is the commit pointed to by the tag 1.0 and how it is represented in the remote tag list as per your question. And if i were to simply push a light-weight tag, test, it stands alone in the remote tag list since it is not referenced by a real git object.
zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git tag test

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git push origin test
Total 0 (delta 0), reused 0 (delta 0)
To ../reftest_bare/
 * [new tag]         test -> test

zrrbite@ZRRBITE MINGW64 /d/dev/git/reftest (master)
$ git ls-remote --tags
From ../reftest_bare/
79d1f428cb16028a2f8b0e0599231eae2ba76b0b        refs/tags/1.0
d7920790cb316067be54ec15e4a7d27265c08fc4        refs/tags/1.0^{}
d7920790cb316067be54ec15e4a7d27265c08fc4        refs/tags/test


text:
Q: codeigniter session user_data being reset I am using Codeigniter database session. I have a search navigation on the header of my page which contains a search from and to date and a text field.
I also have pagination on the page. I am using a custom controller (MY_Controller) and I am setting the from and to dates here. See below.
public function __construct()
{
    parent::__construct();

    $this->load->model('News_model');

    $this->set_dates();
}

function set_dates()
{
    if (empty($this->input->post('from_date')))
    {
        $this->session->set_userdata('sel_from_date', date('Y-m-d'));
    }
    else
    {
        if($_SERVER['REQUEST_METHOD'] == "POST")
        {
            $this->session->set_userdata('sel_from_date', $this->input->post('from_date'));
        }
    }

    if (empty($this->input->post('to_date')))
    {
        $this->session->set_userdata('sel_to_date', date('Y-m-d'));
    }
    else
    {
        if($_SERVER['REQUEST_METHOD'] == "POST")
        {
            $this->session->set_userdata('sel_to_date', $this->input->post('to_date'));
        }
    }
}

This works fine even when I enter dates in the from and/or to fields and click submit, the correct dates stay in the search fields.
However when I click on the link for the next page (in pagination) which basically adds another segment to the URL (i.e. mysite/news/politics/1) and loads the page, the dates in the session user_data are reset. I thought maybe the logic above for blank input dates was being executed again in this instance but that is not the case.
HTML:

                        From Date:

                            <input type="text" placeholder="From Date" class="form-control" name="from_date" id="from_date" width=10" value="<?php echo $this->session->userdata('sel_from_date'); ?>" />

                        To Date:

                            <input type="text" placeholder="To Date" class="form-control" name="to_date" id="to_date" value="<?php echo $this->session->userdata('sel_to_date'); ?>" />

                        <input type="text" class="form-control" placeholder="Search">
                        <button type="submit" class="btn btn-default" name="go" id="go">Go</button>

A: Check whether the session variable 'sel_from_date' is already set .
If yes don't set it again. Try below in your controller:
if($this->session->userdata('sel_from_date') != '')
{
  // Do not set the session variable 'sel_from_date'
}
else
{
   // Execute the function $this->set_dates()
 }

A: I resolved the issues with the following code.
if (empty($this->input->post('from_date')) && !$this->session->userdata('sel_from_date'))
    {
....
}


text:
Q: "Interested" is to "interesting" as "curious" is to what? I can't find any perfect matches in dictionaries. Does there exist such a word at all?

A: Interested is your feeling and interesting is the property of the thing that interests you. Curious refers to both the feeling of the person and the property of the thing, so your answer is: curious.


text:
Q: How to break coupling between bean and validator with Bean Validation (JSR303)? I would like to extract DTO from my application to provided them as jar to tiers applications.
But I used Bean Validation, so DTOs are annotated with custom constraints.
And this custom annotations have dependency (link) on validation implementation.
@AuthorisedUser
public class UserDTO implements Serializable {
    // ...
}

@Constraint(validatedBy = { AuthorisedUserValidator.class })
public @interface AuthorisedUser { ... }

Thus, my DTO module depends annotations, which depends on Validator, which depends on DAO and then the full core application comes.
Is there a way to break this dependence cycle?
What's the good practices to provide DTO jar without dependencies (or only to bean validation API)?
Thanks

A: General Rule of dependencies should be like this.
  Domain objects and DTOs should not depend on any other modules.
  Then DAOs come. They should depend only on the domain objects/DTOs.
  Then comes Service layer, which depends on on the DAO layer. This is where you write your DB related validations.
  Now UI layer uses Service API, On UI layer you usually run the UI validations.
In your specific case you AuthorisedUserValidator class should validate only DTO classe.

A: You just can provide a JAR with your DTOs without providing the Bean Validation JAR or a JAR containing your custom constraint annotations. The DTO classes can still be loaded and used also if they are annotated with annotations whose type is not present (of course you can't make use of Bean Validation in this case).

A: *

*Remove the constraints annotations and create your plain DTO jar

*Bundle your custom constraints and implementations into a separate jar

*In the service layer (or where ever you want to have the validation), add Bean Validation, Hibernate Validator, you custom constraints and use XML to configure the constraints

If your biggest concern is breaking the cycle, your best bet is using XML configuration.


text:
Q: Need to show a message on Prestashop product page if the price entered is wrong I have a website in Presta where user can enter custom price, there is a mix/max price from backend, now e.g. the max price is $50, i dont want people to add more than $50, currently they can, i checked with the developer of site, he says PS 1.7 loads product page content via ajax and he can not do this.
I was suggesting like we check price in validation and do some code there.
how can i do this in presta, any clue!

A: You can modify the template of your product page, using the min/max feature of an input type number in HTML5 :
<input type="number" name="price" min="1" max="50">

A: This solution is with html5, look documentation here : https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/number
Regards


text:
Q: View in browser link - search results Why is the 'View in browser'link appearing In my search results? OWA is installed in the farm but isn't associated with the web application in question. The office web apps feature is deactivated at site collection level and the 'open in client app' feature is activated. Link is appearing for Word, Excel and PowerPoint documents.
When a user clicks on this link to open a document, it screen sits for a while and then displays an error saying it could open the file.  If I associate the equivalent service app in configure service associations it works but I don't want to. Can I just get rid of the link or why is it rendering?

A: When installing Office Web Applications it changes the Visualization of the Federated Location to include this link.
You can either change the default:

*

*go into Central Admin | Manage Service Applications | Search Service Application | Federated Location

*click Local Search Results

*Expand Display Information

*In Core Search Results Display Metadata

*Edit the XSL

*Remove the following section:
<xsl:call-template name="ViewInBrowser">
  <xsl:with-param name="browserlink" select="serverredirectedurl" />
  <xsl:with-param name="currentId" select="$currentId" />
</xsl:call-template>

*Go into the search result page of the search center of web application where you want the link to display

*Put page in edit mode

*Select Edit Web Part on Search Core Results

*Expand Display Properties

*Deselect Use Location Visualization

*Click XLS Editor to edit the XSLT and put the section back below this section:
<xsl:call-template name="DisplayCollapsingStatusLink">
  <xsl:with-param name="status" select="collapsingstatus"/>
  <xsl:with-param name="workid" select="workid"/>
  <xsl:with-param name="id" select="concat($currentId,'_CS')"/>
</xsl:call-template>

Or can use the last steps described above to remove it from Search Centers of web applications where you don't want it


text:
Q: Disk Utility Disk Verification I ran the "Verify Disk" tool in disk utility on my main disk called Macintosh HD, and it came up with this log:
Verifying volume "Macintosh HD"
Checking storage systemChecking volume.
disk0s2: Scan for Volume Headers
disk0s2: Scan for Disk Labels
Logical Volume Group 4D3DFAA4-7124-4F3F-A19D-D06A1784AB17 spans 1 device
Logical Volume Group has a 16 MB Metadata Volume with double redundancy
Start scanning metadata for a valid checkpoint
Load and verify Segment Headers
Load and verify Checkpoint Payload
Load and verify Transaction Segment
Load and verify Transaction Segment
Incorporate 1 newer non-checkpoint transactions
Load and verify Virtual Address Table
Load and verify Segment Usage Table
Load and verify Metadata Superblock
Load and verify Logical Volumes B-Trees
Logical Volume Group contains 1 Logical Volumes
Load and verify E7324686-925A-48BF-8150-A982F1572F20
Load and verify 82E44F05-FEF5-49A9-B3C6-1911EE30BB49
Load and verify Freespace Summary
Load and verify Block Accounting
Load and verify Segment Cleaning
Newest transaction commit checkpoint is valid
The volume 4D3DFAA4-7124-4F3F-A19D-D06A1784AB17 appears to be OK.
Checking file systemPerforming live verification.
Checking Journaled HFS Plus volume.
Checking extents overflow file.
Checking catalog file.
Checking multi-linked files.
Checking catalog hierarchy.
Checking extended attributes file.
Checking volume bitmap.
**Volume bitmap needs minor repair for orphaned blocks**
Checking volume information.
**Invalid volume free block count**
(It should be 85129597 instead of 81974060)
**The volume Macintosh HD was found corrupt and needs to be repaired.
Error: This disk needs to be repaired using the Recovery HD. Restart your computer,                 holding down the Command key and the R key until you see the Apple logo. When the Mac OS X Utilities window appears, choose Disk Utility.**

Do I need to follow the instructions at the bottom of the log? Is it necessary or can I forgo it? Thanks

A: It's not absolutely required, but I'd say it's strongly recommended.  The type of volume corruption it reported isn't as serious as most other types, but my recommendation is the same: don't mess around, fix it now.

A: File system corruption
In an edge case (say, a hard disk drive with a defective sector used by a critical part of the file system structure (extents overflow B-tree, catalog B-tree, attributes B-tree and more)):

*

*a repair by fsck_hfs might do more harm than good, because drive-controlled reallocation of blocks may result in dataloss.

If you're lucky – most people are – then fsck_hfs without attention to media is the simplest and most appropriate course of action. So at the file system level (HFS Plus, in this case JHFS+) the recommended action is almost indisputable.
Storage system corruption
As Core Storage is closed source with too little information published by Apple, it's less clear what should be done about newer non-checkpoint transactions:

*

*What's the significance of non-checkpoint transactions in Core Storage?
Hint: with Disk Utility, apparently OK is not always OK.


text:
Q: java.lang.NullPointerException: Firebase Okay, I'll try to explain my mistake slowly, point by point.

*

*I have a mobile app made according to your tutorial. I watched the video and did it. Then I corrected and improved the errors.

*Completed the functionality of writing to the question, by analogy to your tutorial.
Everything seems to be working fine, there are no questions. Everything works..I collected a working APK.
I thought it was cool.

*There was a lot of extra stuff in my database: Testuser1, testuser2, and so on. I went to delete all of them. Deleted it first in the Real-time database, then in the Firestore. However, while deleting I accidentally touched something message in the document.

*Now I get an error in a new app, working earlier than the APK and the version from a week ago.

*Error: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
 firebaseRecyclerAdapter1.startListening();
I have been struggling with the problem for at least 2 days, I wrote to many thematic communities, technical support all without success. The error is not in my java code, but in my misklik in Firebase. I want to create a missing document in my case.
I have already tried to recreate applications, pass debag, etc., but all to no avail.
My data structure is Firebase Realtime Database:
[![My data structure is Firebase Realtime Database:][1]][1]
Just in case, here is the code for my simplified activity:
public class MessageActivity extends AppCompatActivity {

    private static final int PICK_IMAGE = 1;
    RecyclerView recyclerView;
    ImageView imageView;
    ImageButton sendbtn, cambtn, back;
    TextView username, typingtv;
    EditText messageEt;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference rootref1, rootref2, typingref;
    MessageMember messageMember;
    Boolean typingchecker = false;
    String receiver_name, receiver_uid, sender_uid, url;
    Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            url = bundle.getString("u");
            receiver_name = bundle.getString("n");
            receiver_uid = bundle.getString("ruid");
            sender_uid = bundle.getString("suid");
        } else {
            Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
        }

        messageMember = new MessageMember();
        recyclerView = findViewById(R.id.rv_message);
        cambtn = findViewById(R.id.cam_sendmessage);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(MessageActivity.this));
        imageView = findViewById(R.id.iv_message);
        messageEt = findViewById(R.id.messageet);
        sendbtn = findViewById(R.id.imageButtonsend);
        username = findViewById(R.id.username_messageTv);

        Picasso.get().load(url).into(imageView);
        username.setText(receiver_name);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {
            sender_uid = user.getUid();
            if (receiver_uid != null && sender_uid != null) {

                rootref1 = database.getReference("Message").child(sender_uid); //getReference("Message")
                rootref2 = database.getReference("Message").child(receiver_uid); //getReference("Message")

            }

        }

        sendbtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View view) {
                SendMessage();
            }
        });

        cambtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, PICK_IMAGE);
            }
        });

        messageEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {  }

            @Override
            public void afterTextChanged(Editable editable) { }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE || resultCode == RESULT_OK ||
                data != null || data.getData() != null) {
            uri = data.getData();

            String url = uri.toString();
            Intent intent = new Intent(MessageActivity.this, SendImage.class);
            intent.putExtra("u", url);
            intent.putExtra("n", receiver_name);
            intent.putExtra("ruid", receiver_uid);
            intent.putExtra("suid", sender_uid);
            startActivity(intent);

        } else {
            Toast.makeText(this, "no file selected", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

        if (rootref1 != null) {
            FirebaseRecyclerOptions<MessageMember> options1 =
                    new FirebaseRecyclerOptions.Builder<MessageMember>()
                            .setQuery(rootref1, MessageMember.class)
                            .build();

            FirebaseRecyclerAdapter<MessageMember, MessageViewHolder> firebaseRecyclerAdapter1 =
                    new FirebaseRecyclerAdapter<MessageMember, MessageViewHolder>(options1) {
                        @Override
                        protected void onBindViewHolder(@NonNull MessageViewHolder holder, int position, @NonNull MessageMember model) {

                            holder.Setmessage(getApplication(), model.getMessage(), model.getTime(), model.getDate(), model.getType(),
                                    model.getSenderuid(), model.getReceiveruid(), model.getSendername(), model.getAudio(), model.getImage());

                        }

                        @NonNull
                        @Override
                        public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                            View view = LayoutInflater.from(parent.getContext())
                                    .inflate(R.layout.message_layout, parent, false);

                            return new MessageViewHolder(view);
                        }
                    };

            firebaseRecyclerAdapter1.startListening();
           recyclerView.setAdapter(firebaseRecyclerAdapter1);

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void SendMessage() {

        String message = messageEt.getText().toString();

        Calendar cdate = Calendar.getInstance();
        SimpleDateFormat currentdate = new SimpleDateFormat("dd-MMMM-yyyy");
        final String savedate = currentdate.format(cdate.getTime());

        Calendar ctime = Calendar.getInstance();
        SimpleDateFormat currenttime = new SimpleDateFormat("HH:mm:ss");
        final String savetime = currenttime.format(ctime.getTime());

        String time = savedate + ":" + savetime;

        if (message.isEmpty()) {
            Toast.makeText(this, "Unable to send empty message", Toast.LENGTH_SHORT).show();
        } else {
            messageMember.setDate(savedate);
            messageMember.setTime(savetime);
            messageMember.setMessage(message);
            messageMember.setReceiveruid(receiver_uid);
            messageMember.setSenderuid(sender_uid);
            messageMember.setType("t");

            String id = rootref1.push().getKey();
            rootref1.child(id).setValue(messageMember);

            String id1 = rootref2.push().getKey();
            rootref2.child(id1).setValue(messageMember);

            messageEt.setText("");

        }
    }
}

A: It seems like rootref1 may not yet be initialized when you call this in onStart:
FirebaseRecyclerOptions<MessageMember> options1 =
        new FirebaseRecyclerOptions.Builder<MessageMember>()
                .setQuery(rootref1,MessageMember.class)
                .build();

That seems to happen because you only conditionally initialize it in onCreate with:
if (user != null) {
    sender_uid = user.getUid();
    if ( receiver_uid != null && sender_uid != null) {

        rootref1 = database.getReference("Message").child(sender_uid).child(receiver_uid);;
        rootref2 = database.getReference("Message").child(receiver_uid).child(sender_uid);;

    }
}

My best guess is that you only want to initialize the adapter and start the listener if there is a user, so in onStart you'll also want to check if user != null or if rootref1 is initialized:
if (rootref1 != null) {
    FirebaseRecyclerOptions<MessageMember> options1 =
            new FirebaseRecyclerOptions.Builder<MessageMember>()
                    .setQuery(rootref1,MessageMember.class)
                    .build();
    ...

A: SOLVED. Having solved the problem, I have prepared a couple of answers for people with a similar problem. My solutions have been working for more than 2 weeks at the time of writing the answer.
1 is the simplest, it can work. Delete the Firebase database in real time. Create the JSON file again and attach it to the application again. It helped me, but only for a while.
2-Perform a thorough debugging, especially check the data transfer to Firebase. Getting information from the user. Getting information in FB


text:
Q: How to create popup same as wordpress popup feature I wants to include a popup window which is same like wordpress popup.
Like if we click on the wordpress editor's link button it will open a popup window.
I wants to create same like that.

A: That's called Thickbox. Since you give no clue what you want to use it for, you'll have to figure out the rest for yourself...


text:
Q: is it possible to make a DB act like a clone? i have a db (let's call it A)
i need the informations to be in multiple DB's (B, C, D needs EXACTLY the same informations)
can i make something that will auto-update all of them every (X) hours?

#

i need this in order to sync 2 joomla components using IIS 7 / php.
Tryed (works nice the first time, but then if one is changed it goes fked up because there's no Primary in this component):

#

Getting my data
$mysqli = @new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_WORLD);

/* Vérification de la connexion */
if (mysqli_connect_errno()) {
    die("&error=".mysqli_connect_error()."&");
    exit();
}

$query = "  SELECT  table_name
            FROM    information_schema.tables
            WHERE   table_name LIKE '%XXXXXXX%'";

$arrTableList   = array();
$allInArray     = array();
if ($result = $mysqli->query($query)) {

    /* Récupère un tableau d'objets */
    while ($obj = $result->fetch_object()) {
        $arrTableList[] = $obj->table_name;
    }

    /* free result set */
    $result->close();
}

foreach($arrTableList as $key => $value){

    $query = "  SELECT  *
                FROM    $value";

    if ($result = $mysqli->query($query)) {

        /* Récupère un tableau d'objets */
        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $allInArray[$value][] = $row;
        }

        /* free result set */
        $result->close();
    }

}

the insertion function
function toSwich($newDb, $tmpTag){
    global $mysqli;
    global $allInArray;
    global $tag1;

    $mysqli->select_db($newDb);

    foreach($allInArray as $table => $tableArrayData){

        $table  =   str_replace ($tag1, $tmpTag, $table);
        foreach($tableArrayData as $uselessKey => $valueArray){
            $keyList    = "";
            $valueList  = "";
            $query = "SELECT COUNT(*) FROM $table WHERE ";
            foreach($valueArray as $key => $value){
                $key        =    $mysqli->real_escape_string($key);
                $value      =    $mysqli->real_escape_string($value);

                $keyList    .=  $key . ",";
                $valueList  .=  "'" . $value . "',";

                $query      .=  " $key = '$value' AND";
            }

            $query      =   substr($query,0,-3);
            $valueList  =   substr($valueList,0,-1);
            $keyList    =   substr($keyList,0,-1);

            if(!$result = $mysqli->query($query)){
                print_r($mysqli->error);
                echo "
";
                print_r($query);
                echo "
";
                exit();

            }
            $row = $result->fetch_row();
            if((int)$row[0] == 0){
                if(!$mysqli->real_query("INSERT INTO $table ($keyList) VALUES ($valueList)")){
                    print_r($mysqli->error);
                    exit();
                }
            }
        }
    }

}

A: Configure a Master-Slave replication schema, I'll keep the databases synced constantly
Here its an example how to configure replication: 3 Jump Steps to Configure Master Slave Replication in Mysql


text:
Q: How does the resistance force on a rolling ball depend on the ball radius? A billiard ball set gently rolling on a billiard table slows and stops, because it is decelerated by resistance forces at the contact between the ball and table.
I expect the magnitude of the resistance force will depend on the ball radius, but what is the exponent on the radius in the equation that describes the force?
The exponent is ~3 if determined by the ball volume, ~2 if determined by the surface of the ball or contact area, and ~1 if determined by the ball perimeter.  It would be ~0 if the resistance is independent of ball radius.
There may be an empirical constant of proportionality in the equation, but what I would like to know is how I could use physical reasoning to fix the exponent on the radius to an integer, and then fit this model to my experiment.
ADDENDUM: After reading some of the references suggested in the comments, I saw that my question was more naive than I realized.  The subject of rolling resistance is large, complex, and with significant engineering applications.  My requirements for an answer are likely more modest than what I now think might be offered here. Really, what I would like is a bit more understanding of the primary cause of rolling resistance, the underlying physics, and enough mathematics to be able to relate this to what I currently know about mechanics.  Clearly experimentation is necessary to really understand this accurately, but some theoretical background would be useful for experimental design or explaining it to students.

A: Here is my answer to my own question, based upon what I learned from the suggestions in comments.
The primary cause of the rolling resistance experienced by a billiard ball rolling across a billiard table is the transfer of (kinetic) energy from the ball to the table through hysteresis at the ball-table contact.  A billiard table top consists of a cloth tightly stretched over a rigid base.  To an approximation, the table-cloth-ball contact possesses characteristics of a linear viscoelastic material.  As the ball rolls along the surface, its weight deforms the composite material (the ball and table-base deform little, the cloth much more,) the material rebounds upon unloading, but there is some dissipation of energy as heat (again mostly in the cloth.)  As the ball loses kinetic energy, it slows.
If F is the rolling resistance force slowing the ball and N is the weight of the ball, a rolling resistance coefficient, C, can be defined as:
$$F=C\;N$$
The following is presented here and elsewhere as a physical formula for the rolling friction of a slow rigid wheel on a perfectly elastic surface, but I've so far been unable to derive it (or locate the original source.)  Where z is the sinkage depth and R is the ball radius.
$$C = (\frac{z}{2 R})^\frac{1}{2} $$
The classical solution for the contact between a sphere and half-space gives the relation of sinkage depth to load (ball weight,) ball radius, and an effective modulus, E.
$$ N = \frac{4}{3} E\, R^\frac{1}{2}\; z^\frac{3}{2} $$
Expressing the ball weight using radius and ball density, this analysis suggests that F may be proportional to $R^\frac{1}{3}$.  So the exponent is not really close to any of the integer values I guessed at in the original question.
Some values for the physical properties of balls and tables can be found here: Physics of Pool and Billiards


text:
Q: Find a point n distance away from a specified point in a given direction I'm waaay over my head here. Basically, I have a point (x, y) and a direction in degrees; I need to find a point that in n distance away from the given point in the specified direction.
I've tried looking up similar issues but everything is beyond my level of comprehension. Could somebody try to explain how I'd go about calculating this in as simple of terms as possible?
Thanks

A: Let your point $(x, y)$ be $A$.
You gotta find the point a distance $n$ away at a given angle. Let $B(x_1,y_1)$ be your required point.. The easiest way to solve this, is to break it into components along the x and y axes.
By simple trigonometry:

$x_1 = x + n\cos\theta$
$y_1 = y + n\sin\theta$
Where $\theta$ is the angle given to you.

A: If $\theta$ is the angle between the direction and the positive direction of the $x$ axis, and $x_{new},y_{new}$ be the coordinates of the point you are looking for then:
$x_{new}=x+n\cos(\theta)\\y_{new}=y+n\sin(\theta)$


text:
Q: Behavior of SIO_FLUSH When SIO_FLUSH socket ioctl is used in a Windows environment (in user space), I am confused as to what happens.  Does this: (1) completely discard the data from the TCP/IP send queue into a black hole, or (2) push the queued send data across the connection until the buffer is empty, or (3) something else?  Thanks!

A: With Windows, you can never be sure.
However, this(search for SIOFLUSH) says it discards the send queue associated with the socket. This is what I also expect when I use SIO_FLUSH


text:
Q: Create separate column based on email address, using Excel or SQL I have a column in Excel with the following
Employee
Mickey D. Mouse mickey@disney.com

I want it to look like
Employee || Email
Mickey D. Mouse || mickey@disney.com

In Excel, if I use Text to Column it looks like this
Mickey || D. || Mouse || mickey@disney.com

So how can I separate on JUST the email, and leave the name in ONE column?
Please provide help in either Excel or SQL.

A: In Excel, assuming that your complete data is consistent as depicted in your question, you can use below approach.
Assuming that source data is in cell A1 then formula in cell C1 would be
=TRIM(RIGHT(SUBSTITUTE(A1," ",REPT(" ",99)),99))
And then to get the rest in B1 following can be implemented
=TRIM(SUBSTITUTE(A1,C1,""))

A: OK I just got the email out with this from https://www.extendoffice.com/documents/excel/1272-excel-extract-email-address.html
=IFERROR(TRIM(RIGHT(SUBSTITUTE(LEFT(AL2,FIND(" ",AL2&" ",FIND("@",AL2))-1)," ",REPT(" ",LEN(AL2))),LEN(AL2))),0)

And extracted the name with
=IF(J2=0, (LEFT(H2, SUM(LEN(H2)-LEN(J2)))), (LEFT(H2, SUM(LEN(H2)-LEN(J2)-1))))


text:
Q: Automatically deleting objects older than n days in Amazon S3 (How ?) I am storing many images in Amazon S3,
using a ruby lib (http://amazon.rubyforge.org/)
I don't care the photos older than 1 week, then to free the space in S3 I have to delete those photos.
I know there is a method to delete the object in a certain bucket:
S3Object.delete 'photo-1.jpg', 'photos'

Is there a way to automatically delete the image older than a week ?
If it does Not exist, I'll have to write a daemon to do that :-(
Thank you

UPDATE: now it is possible, check the Roberto's answer.

A: You can use the Amazon S3 Object Expiration policy
Amazon S3 - Object Expiration | AWS Blog

If you use S3 to store log files or other files that have a limited
  lifetime, you probably had to build some sort of mechanism in-house to
  track object ages and to initiate a bulk deletion process from time to
  time. Although our new Multi-Object deletion function will help you to
  make this process faster and easier, we want to go ever farther.
S3's new Object Expiration function allows you to define rules to
  schedule the removal of your objects after a pre-defined time period.
  The rules are specified in the Lifecycle Configuration policy that you
  apply to a bucket. You can update this policy through the S3 API or
  from the AWS Management Console.

Object Expiration | AWS S3 Documentation

Some objects that you store in an Amazon S3 bucket might have a
  well-defined lifetime. For example, you might be uploading periodic
  logs to your bucket, but you might need to retain those logs for a
  specific amount of time. You can use using the Object Lifecycle
  Management to specify a lifetime for objects in your bucket; when the
  lifetime of an object expires, Amazon S3 queues the objects for
  deletion.

Ps: Click on the links for more information.

A: If you have access to a local database, it's easy to simply log each image (you may be doing this already depending on your application), and then you can perform a simple query to retrieve the entire list and delete them each. This is much faster than querying S3 directly, but does require local storage of some kind.

A: Unfortunately, Amazon doesn't offer an API for automatic deletion based on a specific set of criteria.
You'll need to write a daemon that goes through all of the photos and and selects just those that meet your criteria, and then delete them one by one.


text:
Q: Dropdown menu list folders I need to make a dropdown menu for a website i'm working on and in that dropdown i would like to list all files in a directory but due to my lack of web development knowledge i'm struggling a little to be able to figure it out.
Any help would be greatly appreciated!
EDIT
<form>
<select name="menu">
<option value="http://www.msn.com/">MSN</option>
<option value="http://www.google.com/">Google</option>
</select>
<input type="button" onClick="location=this.form.menu.options[this.form.menu.selectedIndex].value;" value="GO">
</form>

That's about the extent to which i know how to make a dropdown menu

A: Look at PHP's scandir function. Loop through the result and echo your HTML code, one <option> tag per loop iteration.
Something like this:
echo "<select name='files'>";
$files = array_map("htmlspecialchars", scandir("path/to/your/files"));
foreach ($files as $file)
    echo "<option value='$file'>$file</option>";
echo "</select>";

A: You could do something like this:
<select>
<?php
  $source_dir = '/var/www/whatever';
  $dir_handle = opendir($source_dir);
  foreach (glob('*', GLOB_ONLYDIR) as $dir_name) {
?>
  <option value="<?= htmlentities($dir_name) ?>">
    <?= htmlentities($dir_name) ?>
  </option>
<?php } ?>
</select>

If you want to sort, filter, or whatever, just manipulate the array returned by glob() however you want.  Alternatively, you can use readdir() calls followed by is_dir() calls.  There are a bunch of different ways to do it, it just boils down to your specific need.


text:
Q: xcode Tools: Memory Leaks In the Memory Leaks tool in XCode 7 what do those crosses in the timeline represent (and the grey shape with the minus)? I could not find this in the documentation and they appear regularly on the timeline.

I get a long lists of leaked object (this is a big project developed in the last years). Should this list be always empty, or it's normal to get some leaks in a running app, or does this implies that it's bad written code?

A: I can answer the first question. The Leaks instrument checks for memory leaks every 10 seconds initially. If the Leaks instrument finds new leaks since the last check, it shows a red symbol with an X in it (the red crosses). The gray symbol with a minus sign means the Leaks instrument has found memory leaks, but no new leaks since the last check.
The goal is to get the Leaks instrument to show a green symbol with a checkmark. That means no leaks were found.
Summary
Green: no leaks
Gray: no new leaks
Red: new leaks

A:
Just to have an idea: should this list be always empty, or it's normal
  to get some leaks in a running app, or does this implies that it's bad
  written code

No, it is not a normal thing and surely this is an ugly code with these many leaks.
If you are dealing with this application now, you should try to reduce to ZERO leaks, or minimise to an acceptable state(here I mean if some leaks are from some 3rd party libraries).
Even I worked on a project that is in production from a decade with 2K classes, that doesn't have any leaks, but ever release we find some and remove it, otherwise the client will not accept the code.


text:
Q: Invalid href passed to router error after fresh installed create-next-app After installed nextjs app on my local machine using create-next-app I get this error in console Invalid href passed to router.
Does anyone know how to solve it?
I try to use to attribute instead of href attribute in Link component's but it doesn't help.

A: Yes, nextjs throws that error. Don't use the  component at all if linking to an external source, for external links you can use  tag. In your case we can conditionally render either a plain anchor tag or use the link component if the prop matches an internal route.
For example:
Link.indexOf('http') == 0 ? return(regular link) : return(<Link>...</Link>)

A: "External URLs, and any links that don't require a route navigation using /pages, don't need to be handled with Link; use the anchor tag for such cases instead."
Given in the docs: https://nextjs.org/docs/api-reference/next/link

A: Removing the protocol http or https from the external url fixes this issue
example
https://stackoverflow.com/ should be //stackoverflow.com/

A: The problem was nextjs doesn't work with external links that's why console throw's error.
When I remove all external link's and instead add internal link's everything worked fine.

A: You have to set parameter prefetch={false}
<Link key={index} href={value} prefetch={false}>

                    {icon}

            </Link>

A: According to this document https://github.com/vercel/next.js/blob/master/errors/invalid-href-passed.md
Possible Ways to Fix It
Look for any usage of next/link or next/router that is being passed a non-internal href and replace them with either an anchor tag () or window.location.href = YOUR_HREF.


text:
Q: Uploading a file on Angular 5 and send it to Java Spring Back End I have a problem on my app. I upload a file on Angular 5 but I can't give to my Java Spring Back end in order to insert it to a database.
I receive a 500 error when I try to send the frmData to Java Controller.
Does any one has a solution? Here is my code :
my component .html :
<ng-container>
  <input type="file" id="uploadFile" multiple
         (change)="getFileDetails($event.target.file)">
</ng-container>

my component .ts :
getFileDetails (e) {
  //console.log (e.target.files);
  for (var i = 0; i < e.target.files.length; i++) {
    this.myFiles.push(e.target.files[i]);
  }
}

addFollowUp1() {
  const frmData = new FormData();

  for (var i = 0; i < this.myFiles.length; i++) {
    frmData.append("file", this.myFiles[i]);
  }

  this.followUpService.addFollowUpAttachment(frmData).subscribe();
}

And my Service.ts :
public addFollowUpAttachment(file: FormData): Observable<any> {
  return this.http.post('/SV-AUD/api/attachment/addAttachment', file );
}

On java Back-end here is the controller :
@Controller
@RequestMapping("/attachment")
public class AttachmentController {

  @Autowired
  private AttachmentService attachmentService;

  @RequestMapping(value = "/addAttachment", method = RequestMethod.POST)
  @ResponseBody
  public void addFollowUpAttachment(@RequestParam("file") MultipartFile files) throws ApcException {
    System.out.println("test");
    attachmentService.addFollowUpAttachment(files);
  }
}

Thanks !

A: I've found the problem , instead of $event.target.file I used only $event , now I finally get an error from the java backend xD
<ng-container>
  <input type="file" id="uploadFile" multiple (change)="getFileDetails($event)">
</ng-container>


text:
Q: Protractor not finding element I'm having trouble getting protractor to behave as expected when testing my angular app. My spec file looks like this:
describe('app login', function() {
   it('should allow admin user to log in', function() {
       browser.get('http://localhost:3008');

    //we can find the log in link
    expect(element(by.id('login-link')).getText()).toContain('Log in');

    //open login dialog
    element(by.id('login-link')).click();
    browser.ignoreSynchronization = true;
    browser.sleep(1000);

    //enter credentials
    element(by.id('login-username')).sendKeys('User1');
    element(by.id('login-password')).sendKeys('Password1');
    browser.sleep(1000);

    //log in
    var el = element(by.id('login-btn'));
    //WORKS IF BELOW LINE IS COMMENTED OUT
    el.click();
    browser.sleep(1000);

    //display confirms login
    expect(element(by.id('user-display')).getText()).toContain('User1');

  });
});

Note that I was getting synchronization errors at the start which is why I have the ignoreSynchronization flag set to true and all those browser.sleeps.
Now here's the thing: The test will go through fine if I remove the el.click() statement (and the final expect call). However, once that line is included, I get NoSuchElementError: No element found using locator: By.id("login-username"). Notice that this element is not the one I am actually trying to click, which is part of the bizarreness.

A: let me start by breaking down your question in 3 parts.
Let's take it a step at a time:
1)ignoreSynchronization flag set to true: It instructs protractor to not wait for Angular promises. This is used when you are i)testing scenarios around waiting for $http or $timeout to resolve ii)testing against a non-angular site. These are the times when you should set ignoreSynchronization setting to true. Ask yourself is it needed for your test pre-requisite? Going by your explanation above, I believe you can set it to false and continue your testing safely. By setting this to true when it is not needed you are instructing protractor to not attempt to synchronize with the page before performing actions. This can be harmful because Protractor will not wait until $timeouts and $http calls have been processed, which can cause tests to become flaky. more on: https://github.com/angular/protractor/blob/9891d430aff477c5feb80ae01b48356866820132/lib/protractor.js#L158
You can do away with unnecessary browser.sleep() once you set this flag to False.
2)Protractor not finding element: There are various reasons for which an element is not detected by Protractor:
-Element does not fit it the display window.
-Element is not visible, but present.
-Asynchronous task not handled properly.
-Another element is overlayed on the other element
I suggest you try out:

*

*Handling all your asynchronous event using either promises, async/await or callbacks.

describe('app login', function() {
  it('should allow admin user to log in', async() => {
    await browser.get('http://localhost:3008');

    //we can find the log in link
    expect(await element(by.id('login-link')).getText()).toContain('Log in');

    //open login dialog
    await element(by.id('login-link')).click();
    //try putting this setting in your protractor.conf file instead of describe
    //block
    //browser.ignoreSynchronization = false;

    //enter credentials
    await element(by.id('login-username')).sendKeys('User1');
    await element(by.id('login-password')).sendKeys('Password1');

    //log in
    var el = element(by.id('login-btn'));
    //WORKS IF BELOW LINE IS COMMENTED OUT
    await el.click();

    //display confirms login
    expect(await element(by.id('user-display')).getText()).toContain('User1');

    });
});

More info on how to change your code: https://jasmine.github.io/tutorials/async
3)Excessive use of browser.sleep(1000);: In your code, using sleep() renders it fragile and will sometimes fail if the system runs slower than normal. It is an invitation to making your test fail flaky, often in non-reproducible scenarios. So unless you want to spend your time in futile debugging, stop using it.
Instead use these wait strategies: explicit waits, waitforAngular; to make sure your asynchronous events are completed before going to the next step. Incase you need to know more on this, leave a comment below, otherwise I am keeping this answer strictly to the question you have asked.
Ask away!

A: You have to wait until your element appear completely by using:
browser.driver.wait(function() {
            return element(by.css(YourElement'/login-username)).isDisplayed().then(function(IsVisible) {
                return IsVisible;
            });
        }, 10000);

Or
browser.driver.wait(function() {
            return element(by.css(YourElement'/login-username)).isPresent().then(function(IsVisible) {
                return IsVisible;
            });
        }, 10000);

Or you want to verify the used selector if its correct or not by using GoogleChrome console by typing: document.querySelector('Your CSS Selector').

A: You can try the following:

    let EC: any = protractor.ExpectedConditions;
    return browser.wait(EC.visibilityOf($('#login-username')), 6000);

I ran into the same problems while testing my login page, where protractor was searching for elements before they were rendered. Using the protractor's expected conditions tells the framework to wait for a particular condition to happen (with a time-out limit, of course) of an element before proceeding.

A: In case your error might be linked to the display size of your testing window, you may want to maximize your driver's visibility upon starting the test suit.
To do this, you can include the following lines of code into your protractor.conf.js file:
onPrepare() {
    browser.driver.manage().window().maximize();
}


text:
Q: Setting module page as home page in Orchard I have a module in which I created a custom page with controller and some logic. Works fine. I need that page to function as home page for my site. I found some topics about implementing IHomePageProvider, but that seems to be impossible because I can't find the definition of IHomePageProvider in the Orchard core. So I know there are some topics on this subject, but I didn't manage to find a solution that way, so therefore this question.

A: That is because it was removed at the same time as the routable part. This is now done using Alias.

A: When working with Orchard Core (Orchard 2) there is setting with Home Route, which you can specify.
You can set it in your recipe.json file:
{
  "name": "settings",
  "HomeRoute": {
    "Action": "Index",
    "Controller": "ControllerName",
    "Area": "AreaName"
  }
}

or probablly later:
RouteValueDictionary newHomeRouteValue = ...;

var site = await _siteService.GetSiteSettingsAsync();
site.HomeRoute = newHomeRouteValue;
await _siteService.UpdateSiteSettingsAsync(site);

A: You can define a home Route and Controller associated with this route. Take a look how it's accomplished in the CulturePicker module: HomeRoutes and LocalizableHomeController


text:
Q: How to get steam avatar with steamworks in c#? I'm programming in c# .NET I'm not using Unity and I want by means of steamworks collect and put player's avatar in picturebox. I did SOMETHING, but don't know what's next. I'm new in steamworks and I can't using it correctly.
var avatarInt = SteamFriends.GetMediumFriendAvatar(SteamUser.GetSteamID());
uint Width, Height;
SteamUtils.GetImageSize(avatarInt, out Width, out Height);
var abc_test = (SteamUser.GetSteamID().ToString());
byte[] avatarstream = new byte[4 * (int)Width * (int)Height];
SteamUtils.GetImageRGBA(avatarInt, avatarstream, 4 * (int)Width * (int)Height);

Earlier I  did something similar with player's nick.
nick_steam.Text = SteamFriends.GetPersonaName();

A: From the Steamworks github:
https://github.com/rlabrecque/Steamworks.NET-Test/blob/master/Assets/Scripts/SteamUtilsTest.cs
public static Texture2D GetSteamImageAsTexture2D(int iImage) {
    Texture2D ret = null;
    uint ImageWidth;
    uint ImageHeight;
    bool bIsValid = SteamUtils.GetImageSize(iImage, out ImageWidth, out ImageHeight);

    if (bIsValid) {
        byte[] Image = new byte[ImageWidth * ImageHeight * 4];

        bIsValid = SteamUtils.GetImageRGBA(iImage, Image, (int)(ImageWidth * ImageHeight * 4));
        if (bIsValid) {
            ret = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
            ret.LoadRawTextureData(Image);
            ret.Apply();
        }
    }

    return ret;
}