text:
Q: Which leads to faster browsing, an ad blocker or an edited hosts file? I recently came across the MVPS hosts file and became fascinated with the concept of blocking ads upstream from your browser. I don't know much about how quickly adblockers work, nor how quickly the hosts file can operate.
Would I get any noticeable speed boost by using that hosts file and disabling the adblock browser plugin?
EDIT: Just a quick update - I tried it, and it seems to be much quicker with the edited hosts file, if you can tolerate things like this:

This showed up on the Youtube homepage, I'll perform further testing to see if these are particularly prevalent.

A: Blocking via the hosts file is almost certainly going to be faster just because it's much more limited in capability -- basically, you can only block based on hostnames. Ad blocking extensions can implement fine-grained blocking based on URL paths and parameters, as well as many other properties.
Host blocking will also tend to be faster because it's implemented in the operating system using a lower-overhead language (C or C++), compared to a JavaScript-based ad blocking extension.
A reasonably powerful computer probably won't have much of a problem with a real ad blocker, but if you're on a lower-end computer, host blocking could be significantly faster. So overall, you'll just need to test both and see what works best for you.

A: While the hit in performance is negligible for most modern computers, under certain circumstances (old computers, multiple VMs) the memory hit is rather significant.
Using the Adblock Plus extension can add 60MB of memory use per Firefox process, in addition to 4MB per iframe. Under certain edge cases it can use up to 2GB of memory, which is unacceptable even for modern computers. This is not a fault of ABP's coding, and cannot be trivially fixed.
https://blog.mozilla.org/nnethercote/2014/05/14/adblock-pluss-effect-on-firefoxs-memory-usage/
This has also been confirmed by the author of Adblock Plus.
https://adblockplus.org/blog/on-the-adblock-plus-memory-consumption
The issue mentioned by the author above (Firefox duplicating memory when ABP is used) has not yet been fixed (or even assigned) as the time of writing (Oct 2014).
Anecdotal result: Disabling Adblock Plus on a VM that I am running reduced the memory consumption from ~220MB to ~140MB (assuming a freshly booted VM and Firefox browser loading the same page), which is a significant decrease. Whether it is worth it or not is completely up to your computer requirements.

A: Using Adblock has a negligible impact on startup performance. (+250 milliseconds)
Hard statistics on performance while browsing are harder to come by, but I can say anecdotally that it is considerably faster than browsing without any ad blocking method.
The hosts file is almost certainly faster seeing as it is baked into the OS and is doing something quite simple. On the other hand, Adblock probably stops more ads and requires less upkeep. If you have anything like a modern system, I don't think that the difference between the two would be noticeable to human perception. You are better off choosing based on other factors such as which one is easier to use, or blocks more ads.

A: The fastest is to redirect the domains you wish to block to a web server that will reply with a blank page, this can be done by using a DNS server on your router that will redirect bad host to a blank page and make your computer use your router's DNS server. Having a service servicing a blank page is faster than waiting for the browser to wait for your request to time out and show an error of some sort.
Using ads blocker extensions or on computer hosts file consume resources on your computer that could have been used elsewhere.


text:
Q: Concatenate on two strings, remove duplicates Suppose I have the following data:
data = data.frame(
  name=c("bob", "bob", "mary", "mary", "mary"),
  colour=c("blue", "blue", "blue", "green", "green"),
  number=c(1,1,1,2,3))

data

  name colour number
1  bob   blue      1
2  bob   blue      1
3 mary   blue      1
4 mary  green      2
5 mary  green      3

How can I concatenate the above on two columns, removing any repeated strings?
I have tried:
data <- data %>% group_by(`name`) %>%
  summarise_all(funs(paste(na.omit(.), collapse = ", ")))

But get the following which is incorrect:
  name             colour  number
1  bob         blue, blue    1, 1
2 mary blue, green, green 1, 2, 3

Expected output:
 name      colour number
1  bob        blue      1
2 mary blue, green  1,2,3

A: A data.table oneliner..
sample data
library(data.table)
DT <-fread("
  name colour number
            bob   blue      1
            bob   blue      1
           mary   blue      1
           mary  green      2
           mary  green      3")

code
cols <- c("colour", "number")
DT[, lapply(.SD, function(x) { paste0( unique(x), collapse = ",") }),
   by = ,(name), .SDcols = cols][]

output
#    name     colour number
# 1:  bob       blue      1
# 2: mary blue,green  1,2,3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Projective Varieties - Question 4.21 W. Fulton Problem - Need to show that if two varieties satisfy $V\subset W \subset \mathbb{P}^n$ and $V$ is a hypersurface, then $W=V$ or $W=\mathbb{P}^n$.
Observation - The analog for affine varieties is valid. However, I am not able to take this case to the projective level. If you have another idea that gets the result, it will help a lot too.
Help me please! thanks.

A: Take $V$ to be the hypersurface determined by the irreducible form $f$ and $W$ the variety defined by a homogeneous prime ideal $I(W) =\frak{p}$. By the projective nullstellensatz, we see that the following inclusions hold. $$0 \subset \mathfrak{p} \subset(f)$$
Now, assume $W \neq \mathbb{P}^n$ and suppose $g \in \mathfrak{p}$ is a nonzero form of minimal degree. Then, $g \in (f)$ so we may write $g = g_0f$ for some other form $g_0$. Since $\mathfrak{p}$ is prime, we must have $g_0 \in \mathfrak{p}$ or $f \in \mathfrak{p}$. If $g_0 \in \mathfrak{p}$, however, this would contradict the minimality of the degree of $g$. Hence, $f \in \mathfrak{p}$, so that $\mathfrak{p} = (f)$. The projective nullstellensatz then implies $V = W$.


text:
Q: How to execute mvn with multiline script? I'm writing test cases using JMeter in a maven project. I'd like to provide shell and batch script examples for every test case, so others can try these tests out easily. On the other hand, these scripts are examples about how to one can configure test cases via parameters. The importance of being multiline formatted os being able understand easily the script parameteres, especially when I'll have scripts with 10+ parameters.
An mvn command executing the script in batch format looks like below. The batch format works like charm.
mvn clean verify -DjMeterScript=JMXFileName.jmx ^
  -Djmeter.url=test.environment.url ^
  -Djmeter.port=6080 ^
  -Djmeter.protocol=http ^
  -Djmeter.debugMode=1 ^
  -Djmeter.viaFiddler=1 ^

However, the shell format doesn't work. According to internet ultimate knowledge a multiline shell scripts should be formatted like below.
mvn clean verify -DjMeterScript=JMXFileName.jmx \
  -Djmeter.url=test.environment.url \
  -Djmeter.port=6080 \
  -Djmeter.protocol=http \
  -Djmeter.debugMode=1 \
  -Djmeter.viaFiddler=1 \

When I execute the script with ./shellScriptName.sh where the script contains the example above, I'm getting the error below.
The question is how to format a shell script properly which calls maven?
Update - it happens only on Windows 10 - WSL with Hyper:

*

*Git bash on Windows 10 works fine

*Macbook Pro also works fine

*with any linux it works fine

Error message:
[ERROR] Unknown lifecycle phase "
[ERROR] ". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException

A: I had the same problem and you should use ^ symbol to break lines but also contain all arguments with dot in quotation marks. I think you don't have to add ^ symbol in last line.
So in your case it should look like this:
mvn clean verify -DjMeterScript="JMXFileName.jmx" ^
  -D"jmeter.url"="test.environment.url ^
  -D"jmeter.port"=6080 ^
  -D"jmeter.protocol"=http ^
  -D"jmeter.debugMode"=1 ^
  -D"jmeter.viaFiddler"=1


text:
Q: Generic Date Parsing Library from unstructured text Can somebody suggest any Library in Java which is capable of parsing Date/Time Calendar Event from Unstructured Data.
Example

*

*Starts 10pm Tonight! Sunday feb 10th => 10/Feb/2013 10pm

*tomorrow (feb 10th) => 10/Feb/2013

*Sunday Feb 10\r\nwith daily screenings till Feb 16th

and so on
The input data comes from user, so he may enter data in any random format.
I started of identifying all the possible token and do a regex match to phrase all tokens.
I wonder if someone can suggest some Library in Java, which might actually help in parsing.
I ran through other post on SO, but they seem to suggest techniques, i wonder if somebody has a library.
Thanks

A: You could take some of the trunk source from Apache openLNP (natural language processing) at http://opennlp.apache.org/ or just set up a callable RESTful web service by implementing openNLP on your server.  Benefit of implementing the OOB openNLP is you have entity extractors through the nameFinder interface for dates, times, organizations, locations, and people.  You would also be able to build an example file of more typical context for the items of interest indicating their appropriate entity type and train the NLP model against it to gain a better hit rate for your context.  I have a working example of a C# NLP in the apps section of my portfolio at http://www.augmentedintel.com/apps/csharpnlp/extract-names-from-text.aspx.

A: UTAH (https://github.com/sonalake/utah-parser) is able to handle generic parsing of unstructured text into maps. Once you've done that you should be able to throw that into a formatter.


text:
Q: How to emulate the live lyrics animated gradient in swiftui? It's probably very complicated but would appreciate if someone could lead me in the right direction. I would like to create a flowing gradient animation like the one in the music app. I want to use it to change colours depending on lights for a smart home app. I am familiar with using LinearGradient and animating the start and end points, but this is obviously a lot more complicated but hopefully someone knows what I can do.
I found a MPUGradientView header that includes CAGradientLayer so I'm not sure if its combining gradients to somehow create the effect.
Thanks!

A: Not exactly reproducing the screenshot you were asking for, but it should get you started.
Inspired from here: https://nerdyak.tech/development/2019/09/30/animating-gradients-swiftui.html
struct MainView: View {

@State var gradient = [Color.red, Color.purple, Color.orange]

@State var startPoint = UnitPoint(x: 0, y: 0)
@State var endPoint = UnitPoint(x: 0, y: 2)

var body: some View {
    ZStack {
        LinearGradient(gradient: Gradient(colors: self.gradient), startPoint: self.startPoint, endPoint: self.endPoint)
            .overlay(
                Text("Hello world")
        )
    }
    .edgesIgnoringSafeArea(.all)
    .onAppear {
        withAnimation(Animation.easeInOut(duration: 6).repeatForever(autoreverses: true)) {
            self.startPoint = UnitPoint(x: 1, y: -1)
            self.endPoint = UnitPoint(x: 0, y: 1)
        }
    }
}}

A: I have ended up getting something quite close in mostly SwiftUI but it requires an image.
Here is a preview of what it looks like:
https://twitter.com/priva2804/status/1284439692352434178?s=21
Here is the gist:
https://gist.github.com/Priva28/22fbae9dbe04a08fadf748793dd23d00


text:
Q: Error When Parsing Data: Undefined variable: mystudents I do parsing data from my command, before this, it gets that data. When I want to do it again, it becomes an error.
I got:
 Undefined variable: mystudents (View: /home/john/Documents/api4/api4/resources/views/emails/welcome.blade.php)`enter code here`

this is my code on  command:
  foreach ($student as $mystudent) {

        $user = User::find($mystudent->user_id);
       Mail::to($user)->send(new WelcomeMail($mystudent));
   }

    Mail::to($user)->send(new WelcomeMail($student));
    echo "check email";

this is my code on view
@foreach ($mystudents as $student)

            {{ $student->student_id }}
            {{ $student->name }}
            {{ $student->email }}
            {{ $student->phone }}

I'm not sure that my code was correct. Hopefully, you help me, sir.

A: You are running a foreach loop in your command, as well as in your view.
Also, you are calling the Mail send method two times.
I think you only need a foreach once, in your command:
foreach ($student as $mystudent) {
    $user = User::find($mystudent->user_id);
    Mail::to($user)->send(new WelcomeMail($user));
}

The code in your view can be something like this:

    {{ $user->student_id }}
    {{ $user->name }}
    {{ $user->email }}
    {{ $user->phone }}


text:
Q: NHibernate Session in WPF MVVM I am using WPF with NHibernate currently using single session with mutiple thread that is causing so many error same as this link. So now i have to start and close the session as soon as i am done. But the problem will be be lazy data. I am confuse how will i fetch them with MVVM as below :-
class Product
{

public virtual string name{get;set;}
public virtual Session session{get;set;} // Lazy
public virtual Categories cate{get;set;} //Lazy
public virtual Warehose warehouse{get;set;} //Lazy

  public virtual string NAME
        {
            get { return Name; }
            set
            {
                Name = value;
                OnPropertyChanged("NAME");
            }
        }

 public virtual string TerminalName
        {
            get { return session.terminal.terminalName; }
            set
            {
                session.terminal.terminalName= value;
                OnPropertyChanged("TerminalName");
            }
        }

 public virtual string CateName
        {
            get { return session.cate.catename; }
            set
            {
                session.cate.catename= value;
                OnPropertyChanged("CateName");
            }
        }

 public virtual string UserName
        {
            get { return session.user.username; }
            set
            {
                session.user.username= value;
                OnPropertyChanged("UserName");
            }
        }

}

class Categories {
public virtual string catename{set;get;}
}

class Warehose {
public virtual string warename{set;get;}
}

class Session{
public virtual People user{get;set;} //Lazy
public virtual Terminal terminal{get;set;} //Lazy
//... other properties
}

Class People{
public virtual string username{set;get;}
}

Class Terminal{
public virtual string terminalName{set;get;}
}

I will fetch the data from database in a list and giving it to DataGrid as itemsource as below
<DataGrid Name="saleDataGrid"
<DataGrid.Columns >
 <DataGridTextColumn Binding="{Binding NAME}" FontSize="12"
  CanUserResize="False" Width="70" Header="Code"/>

 <DataGridTextColumn Binding="{Binding TerminalName}" FontSize="12"
 Header="Desciption" Width="120" CanUserResize="False"/>

 <DataGridTextColumn Binding="{Binding CateName}" FontSize="12"
  Header="Price" Width="50" CanUserResize="False"/>

 <DataGridTextColumn Binding="{Binding UserName}" FontSize="12"
 CanUserResize="False" Width="45" Header="QTY"/>
</DataGrid.Columns>
</DataGrid>

So when i will close the connection and when DataGrid display that time i am getting lazy exception because session is closed. I don`t know what should i do.
Can any one please recommend  to get lazy data witth MVVM if session is closed.  I  don't want use eager loading as a solution for this.
Please let me know you need more information.
Thanks
Anchit

A: For the most part, you have three options, and they are independent from ORM you use, because ORMs behave very similar:

*

*let the session/context object live as long, as view model lives;

*build model ("M" in MVVM) in the manner, which allows you to fetch data lazily, when you need them (with creation of new session/context object every time). This turns off ORM's lazy loading, since model is managing lazy loading by itself;

*throw away lazy loading and load everything you need for the view model.

A: One way to deal with this is to set your session context status to 'thread_static' when you create your session factory,
If Fluent NHibernate
public class NHibernateConfig
{
    public static Configuration Configure()
    {
        var cfg = Fluently.Configure()
            .Database(...)
            .Mappings(...)
            .ExposeConfiguration(x => x.SetProperty("current_session_context_class", "thread_static"))
            .BuildConfiguration();
        return cfg;
     }
}

If XML file
<props>
...
  <prop key="hibernate.current_session_context_class ">thread</prop>
...
</props>

which will keep the session per thread and you won't have to deal with the issues sharing same session across multiple threads.
However keeping a session open for a very long time is not a great idea, so may be when you initiate a new View, you could create a new session and close it when exiting the view, where it would not affect lazy loading.


text:
Q: Rows not ordered properly with group by SELECT userid,SUBSTRING_INDEX(SUBSTRING_INDEX(data, '\"!', -1), '!\"', 1)+0 AS num
FROM table
WHERE type=2
ORDER BY num DESC LIMIT 5

This picks up the number between !x! in a string and tries to return the number and order the rows by that number. It works fine.
However, I don't know how to return unique user ids.
Adding ORDER BY userid returns the rows without ordering by num:
SELECT userid,SUBSTRING_INDEX(SUBSTRING_INDEX(data, '\"!', -1), '!\"', 1)+0 AS num
FROM table
WHERE type=2
GROUP BY userid
ORDER BY num DESC LIMIT 5

Distinct doesn't work either:
SELECT DISTINCT(userid),SUBSTRING_INDEX(SUBSTRING_INDEX(data, '\"!', -1), '!\"', 1)+0 AS num
FROM table
WHERE type=2
ORDER BY num DESC LIMIT 5

I am out of ideas..
Example:
id    userid     data
1       56       !100!
2       22       !90!
3       56       !200!

Result should be:
userid      num
56          200
22          90

A: SELECT userid,MAX(num) num FROM
(SELECT userid,SUBSTRING_INDEX(SUBSTRING_INDEX(data, '\"!', -1), '!\"', 1)+0 AS num
FROM table
WHERE type=2) A
GROUP BY userid;


text:
Q: D3 Graph working in chromium, but not in other browsers I'm trying to access dates and some values in d3 js. Shared my fiddle, can any one help me out in correcting my code and can any one tell me the mistake as well.
<!DOCTYPE html>
<html>
<head>
 <title>trial</title>
    <link rel="stylesheet" href="css/style.css">
     <body>
     <svg id="visualisation" width="1000" height="500"></svg>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js' ></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.12/d3.min.js"></script>

     <script src="js/index.js"></script>
     </body>
</html>

https://jsfiddle.net/c6jf5yg0/6/
Observation: The attribute id is not computing properly in the broswers.
 thanks in advance

A: Path element attribute value has NaN firefox is the first root cause.
<path d="MNaN,20LNaN,240.23584905660306LNaN,480" stroke="blue" stroke-width="2" fill="none"/>

Why it is updating NaN?
In extent function of X Range like below.
d3.extent(lineData, function(d) {
 return new Date(d.x);
  // new Date("2016-01-08 03:01:19.418110");
  // Firefox output Date {Invalid Date}
  // Chrome it works.
})

How to Fix this issue ?

Update your lineData like below. by adding T in between date and time.

var lineData = [{
            "x": "2016-01-08T03:01:19.418110",
            "y": 0.8076999999999999
        }, {
            "x": "2016-01-08T05:10:19.838509",
            "y": 0.692666666666667
        }, {
            "x": "2016-01-08T09:54:13.022163",
            "y": 0.5674333333333333
        }];

Working Screenshot:

A: Add the "T" in between date and time and that is ECMA Specification
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2
Working Demo:

        InitChart();

        function InitChart() {

        var lineData = [{
                    "x": "2016-01-08T03:01:19.418110",
                    "y": 0.8076999999999999
                }, {
                    "x": "2016-01-08T05:10:19.838509",
                    "y": 0.692666666666667
                }, {
                    "x": "2016-01-08T09:54:13.022163",
                    "y": 0.5674333333333333
                }];

            var vis = d3.select("#visualisation"),
                WIDTH = 1000,
                HEIGHT = 500,
                MARGINS = {
                    top: 20,
                    right: 20,
                    bottom: 20,
                    left: 50
                },

                xRange = d3.time.scale()
                .range([MARGINS.left, WIDTH - MARGINS.right])
                .domain(d3.extent(lineData, function(d) {
                    return new Date(d.x);
                })),

                yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function(d) {
                        return d.y;
                    }),
                    d3.max(lineData, function(d) {
                        return d.y;
                    })
                ]),

                xAxis = d3.svg.axis()
                .scale(xRange)
                .tickSize(5)
                .tickSubdivide(true)
                .tickFormat(d3.time.format('%X')),

                yAxis = d3.svg.axis()
                .scale(yRange)
                .tickSize(5)
                .orient("left")
                .tickSubdivide(true);

            vis.append("svg:g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
                .call(xAxis);

            vis.append("svg:g")
                .attr("class", "y axis")
                .attr("transform", "translate(" + (MARGINS.left) + ",0)")
                .call(yAxis);

            var lineFunc = d3.svg.line()
                .x(function(d) {
                    return xRange(new Date(d.x));
                })
                .y(function(d) {
                    return yRange(d.y);
                })
                .interpolate('linear');

            vis.append("svg:path")
                .attr("d", lineFunc(lineData))
                .attr("stroke", "blue")
                .attr("stroke-width", 2)
                .attr("fill", "none");

        }
<!DOCTYPE html>
<html>
<head>
<title>trial</title>
<body>
    <svg id="visualisation" width="1000" height="500"></svg>
    <script src="http://d3js.org/d3.v3.min.js"></script>
</body>
</html>


text:
Q: Cant access files on Azure Blob Storage from within Canvas App I am trying to secure my blob storage so that only requests coming from within my canvas app are accepted by ABS. From within the storage accounts networking tab I have choosen Allow access from: Selected networks and have added the IP addresses outlined here for my region, which is Australia.

But I still get a AuthorizationFailure error when trying to access a document through a shared link created by ABS from within my cavas app.
When I allow All networks everything works fine.
Can anyone assist me with this?


text:
Q: how to orderby() count without group in laravel I have Users table which has under_reference column that represents by whom this user was referred.
I want to order user by having highest under_reference count. How to order by counting under reference
$data['user'] = User::orderBy('id','DESC')->get();

A: $data['user'] = User::select(DB::raw('count(*) as total'))
  ->groupBy('under_reference')
  ->orderBy('under_reference','DESC')
  ->get();

Here is the query that can help you. You can get the total users referred by a person and orderBy reference.

A: Use Group By for this situation, and sort from it. Here's an example.
$query = [
        'name',
        'email',
        // store count of under_reference as total
        DB::raw('count(under_reference) as total')
    ];

$sorted = User::groupBy('name', 'email')
        ->select($query)
        ->orderBy('total', 'desc') // remember total before, sort it by desc or asc
        ->get();

You can refer from laravel documentation here on raw expressions
The name and email is just an examaple, as you didn't show us what your table's column looks like. But you should get a pretty rough idea

A: You can try in this way also worked.
$data['user'] = DB::select('SELECT *` FROM `user` ORDER BY
CAST(`under_reference` AS decimal) DESC');

You can cast the DB column varchar to decimal in query.

A: Try this:
$user_info = DB::table('users')
->select('under_reference',DB::raw('count(under_reference) as ur'))
->groupBy('under_reference')
->orderBy('ur','DESC')
->get();

A: i created another column totalref with Integer . i coded logic to update this column also with referral bonus and then orderby totalref. and it worked like magic


text:
Q: Filebeat running on a windows machine, harvester not reading file - also not connecting to Kafka Filebeat running on a windows machine. Harvester not reading file and not connecting to kafka.

A: Issue solved. I didnt mention the filename extension. after that it worked. Thanks.


text:
Q: Configuration of Dynatrace in Gradle Kotlin DSL I have an Android project, using a Gradle build configuration written in the kotlin-dsl and trying to apply Dynatrace:
buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath("com.dynatrace.tools:android:7.2.4.1262")
  }
}

// I apply the plugin
apply(plugin = "com.dynatrace.tools.android")

Everything runs smoothly until I try to use the dynatrace configuration block, which is never resolved:
dynatrace {
    defaultConfig {
       ....
    }
}

This is the environment I am working with:

*

*Gradle: 5.1.1

*Android Gradle plugin: 3.4.1

*Dynatrace version: 7.2.4.1262

I am following Dynatrace's own instructions, and even though they don't mention how to perform the configuration with the kotlin-dsl, they have just added support for it.
Any help would be appreciated.

A: I have tried it with the apply DSL and it didn't work. I got it working applying the plugin via plugins DSL.
Top level build.gradle.kts:
buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.5.0-beta01")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.31")
        classpath("com.dynatrace.tools:android:7.2.4.1262")
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

App build.gradle.kts:
plugins {
    id("com.android.application")
    kotlin("android")
    id("com.dynatrace.tools.android")
    ...
}

android {
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
}

dynatrace {
    defaultConfig {
        ...
    }
}

dependencies {
    ...
}

A: I had the same problem trying to migrate my build.gradle to KTS (with dynatrace configuration on it).
I had some problems finding the right documentation in Dynatrace website, but at the end I found it (https://www.dynatrace.com/support/help/how-to-use-dynatrace/real-user-monitoring/setup-and-configuration/mobile-apps/instrument-android-app/instrumentation-via-plugin/instrumentation-via-plugin/#tabgroup-android-gradle-plugin--groovy)
The solution in my case, within the Top level build.gradle.kts:
buildscript {
  repositories {
        google()
        mavenCentral()
  }
  dependencies {
    classpath("com.dynatrace.tools.android:gradle-plugin:8.207.1.1004")
  }
}

apply(plugin = "com.dynatrace.instrumentation")
configure<com.dynatrace.tools.android.dsl.DynatraceExtension> {
    configurations {
        create("prod") {
            variantFilter("[rR]elease")
            autoStart {
                applicationId("xxx")
                beaconUrl("yyy")
            }
            userOptIn(true)
            userActions.timeout(5000)
        }
        create("debug") {
            autoStart {
                applicationId("aaa")
                beaconUrl("bbb")
            }
            userOptIn(true)
            userActions.timeout(5000)
        }
    }
}


text: Q: How to keep audio playing when switching users in Windows? It seems that Windows automatically stops my audio play when switching to another user. Is there any way where I can keep audio playing when windows switch to another user?


text:
Q: A (probably) simple explanation - constructor definition and argument(s) I've seen this question asked a few times and can't seem to get my head around why this isn't working.  Please help a noob (and be gentle!). I'm simply trying to create a class to accept the name of a COM port and then start a serial object on that port. I keep getting a "Conex does not contain a constructor that accepts 1 argument" error, though it seems to me that's all it contains. Thoughts?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace Conex_Commands
{

    public class Conex
    {
        string NewLine = "\r";
        int BaudRate = 921600, DataBits = 8, ReadTimeout = 100, WriteTimeout = 100;
        Parity Parity = Parity.None;
        StopBits StopBits = StopBits.One;

        public Conex(string PortName)
        {
            SerialPort Serial = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
            Serial.ReadTimeout = ReadTimeout;
            Serial.WriteTimeout = WriteTimeout;
            Serial.NewLine = NewLine;
        }

    }

}

The calling code contained in my main is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Conex_Commands;

namespace Tester
{
    class Program
    {
        static void Main(string[] args)
        {

            Conex abc = new Conex("COM5");
         }
    }
}

A: Is this just for debugging purposes?
My VS2010 code shows no errors with this code.
It is, however, useless as written because as soon as you call the constructor for Conex, the SerialPort goes back out of scope.
Instead, bring your Serial object outside of the constructor:
public class Conex {
  string NewLine = "\r";
  int BaudRate = 921600, DataBits = 8, ReadTimeout = 100, WriteTimeout = 100;
  Parity Parity = Parity.None;
  StopBits StopBits = StopBits.One;
  SerialPort Serial;

  public Conex(string PortName) {
    Serial = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
    Serial.ReadTimeout = ReadTimeout;
    Serial.WriteTimeout = WriteTimeout;
    Serial.NewLine = NewLine;
  }

  public void Open() {
    Serial.Open();
  }

  public void Close() {
    Serial.Close();
  }

}

Now, from within your Main routine, you can actually attempt to Open and Close the connection (which threw an Exception on my PC, because it has no "COM5" port):
static void Main(string[] args) {
  Conex abc = new Conex("COM5");
  abc.Open();
  abc.Close();
}


text:
Q: cardview in flutter layout I want the code to design a cardview in flutter with all properties:

A: See
https://api.flutter.dev/flutter/material/Card-class.html
https://api.flutter.dev/flutter/widgets/Row-class.html
https://api.flutter.dev/flutter/material/CircleAvatar-class.html
Then post code for what you have attempted if you still have questions.

A: Padding(
        padding: EdgeInsets.all(20),
              child: Card(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
          elevation: 5,
          color: Colors.white,
          child: Row(children: [

            Padding(
              padding: EdgeInsets.all(10),
                          child: Card(
                  shape: CircleBorder(),
                  elevation: 10,
                  color: Colors.white,
                  child: Icon(Icons.account_circle, color: Colors.black, size: 100)),
            ),

            Padding(
              padding: EdgeInsets.all(10),
                          child: Card(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20)),
                      elevation: 10,
                  color: Colors.green[400],
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('@anonymous',
                        style: TextStyle(
                            color: Colors.black, fontWeight: FontWeight.bold)),
                  )),
            )
          ])),
      )

A: You can modify and add relevant fields as your requirement !
return Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
        color: Colors.white,
        child: Row(children: [
          SizedBox(
            width: 30,
          ),
          Card(
              shape: CircleBorder(),
              color: Colors.white,
              child: Icon(Icons.account_circle, color: Colors.black, size: 50)),
          SizedBox(
            width: 30,
          ),
          Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
              color: Colors.green[800],
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text('@anonymous',
                    style: TextStyle(
                        color: Colors.black, fontWeight: FontWeight.bold)),
              ))
        ]));


text:
Q: fullCalendar('getView').visStart return undefined I'm trying to get the start, end date of fullCalendar. If I use the the fullcalendar.min.js version the value is read correctly but If I import the normal version fullcalendar.js this code:
 $('#calendar').fullCalendar('getView').visStart,
 $('#calendar').fullCalendar('getView').visEnd;

return me undefined. Someone had the same problem? Maybe with the normal version of fullcalendar change something? I don't know.
Anyway in the min version all working well but I need to use the normal version for import some class.
This is a preview:
min version (all working well):

full version (bug)

Also the CSS are broken.


text:
Q: How to print intercept and slope of a simple linear regression in Python with scikit-learn? I am trying to predict car prices (by machine learning) with a simple linear regression (only one independent variable). The variables are "highway miles per gallon"
0      27
1      27
2      26
3      30
4      22
       ..
200    28
201    25
202    23
203    27
204    25
Name: highway-mpg, Length: 205, dtype: int64

and "price":
0      13495.0
1      16500.0
2      16500.0
3      13950.0
4      17450.0
        ...
200    16845.0
201    19045.0
202    21485.0
203    22470.0
204    22625.0
Name: price, Length: 205, dtype: float64

With the following code:
from sklearn.linear_model import LinearRegression

x = df["highway-mpg"]
y = df["price"]
lm = LinearRegression()

lm.fit([x],[y])
Yhat = lm.predict([x])

print(Yhat)
print(lm.intercept_)
print(lm.coef_)

However, the intercept and slope coefficient print commands give me the following output:
[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

Why doesn't it print the intercept and slope coefficient? The "Yhat" print command does print out the predicted values in an array properly, but somehow the other print commands do not print my desired output...

A: Essentially, what caused the strange looking coef_ and intercept_ was the fact that your data had 205 features and 205 targets with only 1 sample. Definitely not what you wanted!
You probably want 1 feature, 205 samples, and 1 target. To do this, you need to reshape your data:
from sklearn.linear_model import LinearRegression
import numpy as np

mpg = np.array([27, 27, 26, 30, 22, 28, 25, 23, 27, 25]).reshape(-1, 1)
price = np.array([13495.0, 16500.0, 16500.0, 13950.0, 17450.0, 16845.0, 19045.0, 21485.0, 22470.0, 22625.0])

lm = LinearRegression()
lm.fit(mpg, price)

print(lm.intercept_)
print(lm.coef_)

I used the arrays there for testing, but obviously use the data from your dataframe.
P.S. If you omit the resize, you get an error message like this:
ValueError: Expected 2D array, got 1D array instead:
array=[27 27 26 30 22 28 25 23 27 25].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

^ It tells you what to do!


text:
Q: Можно ли изменить стилем принудительно установленный цвет в TextBlock Здравствуйте!
Подскажите пожалуйста, можно ли изменить стилем принудительно установленный цвет в TextBlock
Есть такой код:
<Window>
    <Grid>
        <ListView x:Name="listView">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="300" Header="С Заданным цветом">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Display}" Foreground="Black"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

Каким образом можно изменить его, не убирая параметр Foreground="Black" ?


text:
Q: ASP.NET MVC3 DropDownListFor Enum Hi I'm fairly new to MVC3 and I'm trying to do something that I think must be fairly common, but can't quite get it.
I have a model I wish store the value for enum DayOfWeek in:
public class Booking
{
    public int ID { get; set; }
    public int Day { get; set; }
    ....
}

I've made it an int to store in the database.
I want to edit in the View as a DropDownList:
    <div class="editor-field">
        @Html.DropDownListFor(model => model.Booking.Day, new SelectList(Enum.GetValues(typeof(DayOfWeek))))
        @Html.ValidationMessageFor(model => model.Booking.Day)
    </div>

However I get the error: "The field day must be a number".
I know I'm missing something, and probably something simple, can anyone help?

A: Add a SelectList property to your viewmodel and populate as per @Brandon's answer here.
Then you will change your code to:
@Html.DropDownListFor(model => model.Booking.Day, Model.SelectListProperty)

(where SelectListProperty is the name of your property on your viewmodel)

A: You can also change your model class using DayOfWeek:
public class Booking
{
    public int ID { get; set; }
    public DayOfWeek Day { get; set; }
}


text:
Q: Neo4J Cypher Pattern syntax I am learning Neo4J, and while reading the book "Graph Databases" by O'Reilly, I came across a graph pattern which describes three friends, represented as nodes and the relationship direction between them signifying who is whose friend.
Here's the diagram -
From the diagram, I can understand that - b knows a, c knows a and c knows b
But the Cypher query pattern isn't clear to me -
(a)-[:KNOWS]->(b)-[:KNOWS]->(c), (a)-[:KNOWS]->(c)

On the next section, where they describe the syntax, they mention -

Using ASCII characters to represent nodes and relationships, we draw
  the data we're interested in. We use parantheses to draw nodes, and
  pairs of dashes and greater-than and less-than sign to draw
  relationships(- -> and <- -). The < and > signs indicate relationship
  direction.

If this is the case, (a)-[:KNOWS]->(b)-[:KNOWS]->(c) signifies that a KNOWS b and b KNOWS c, and (a)-[:KNOWS]->(c) signifies that a KNOWS c. Isn't this the opposite of what the arrows in the diagram depict?

A: That seems to be a mistake in the book. The shown diagram is expressed by
(a)<-[:KNOWS]-(b)<-[:KNOWS]-(c), (c)-[:KNOWS]->(a)

or
(a)<-[:KNOWS]-(b)<-[:KNOWS]-(c)-[:KNOWS]->(a)


text:
Q: How do you override a command in bash but make it handle existing parameters? I want to override the docker command so that when I do docker ps or docker service ls exactly it will render in the format I want.
I started with this
docker() {
  if [ "$*" == 'ps' ]
  then
    command docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}"
  else
    eval "command docker $*"
    # eval "command docker $@"
    # command docker $*
    # command docker $@
    # command docker "$*"
  fi
}

However when I did it this does not work
docker service ls --format="table {{.Name}}\t{{.Image}}\t{{.Replicas}}\t{{.Ports}}"

But
command docker service ls --format="table {{.Name}}\t{{.Image}}\t{{.Replicas}}\t{{.Ports}}"

It appears to be because of the " characters being processed.

A: Use "$@" rather than $* to ensure that arguments are re-quoted.
docker() {
  if [ "$*" = 'ps' ]
  then
    command docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}"
  else
    command docker "$@"
  fi
}


text:
Q: Evitar la repetición del fondo gradient Estoy tratando de colocar un un fondo a mi página web ¿Cómo evito la repetición del fondo gradient, en mi página? ya que lo que deseo es que los colores se vean uniformes y no con saltos.

  <title>Ejemplo</title>

El lenguaje HTML es tan sencillo que prácticamente se entiende sin estudiar el significado de sus etiquetas principales.

A: La solución va a depender de cómo quieras resolver el problema: ¿quieres que se repita una sola vez ocupando toda la ventana o sólo el tamaño específico del contenedor?
El principal problema es que estás definiendo todo como background, entonces el navegador tomará la última que sea válida y la aplicará, ignorando entonces el background: no-repeat que tienes al principio. La solución es simple: mueve esa regla al final, y hazla más específica (background-repeat: no-repeat).

  <title>Ejemplo</title>

El lenguaje HTML es tan sencillo que prácticamente se entiende sin estudiar el significado de sus etiquetas principales.

Si en cambio lo que quieres es que sólo se repita una vez y ocupe todo el alto/ancho del contenedor, podrías hacerlo usando la propiedad background-attachment y asignándole el valor fixed (aunque se verá estirado):

  <title>Ejemplo</title>

El lenguaje HTML es tan sencillo que prácticamente se entiende sin estudiar el significado de sus etiquetas principales.

A: Yo creo que primero debes corregir el CSS:

html {
    height: 100%; /*Asignar un alto al html de 100%*/
}
body {
    height: 100%; /*Tambien al Body 100%*/
    margin: 0;
    background-repeat: no-repeat; /*Evita que se repita*/
    background-attachment: fixed;
     background: rgba(226,226,226,1);
background: -moz-linear-gradient(top, rgba(226,226,226,1) 0%, rgba(219,219,219,1) 50%, rgba(209,209,209,1) 51%, rgba(254,254,254,1) 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(226,226,226,1)), color-stop(50%, rgba(219,219,219,1)), color-stop(51%, rgba(209,209,209,1)), color-stop(100%, rgba(254,254,254,1)));
background: -webkit-linear-gradient(top, rgba(226,226,226,1) 0%, rgba(219,219,219,1) 50%, rgba(209,209,209,1) 51%, rgba(254,254,254,1) 100%);
background: -o-linear-gradient(top, rgba(226,226,226,1) 0%, rgba(219,219,219,1) 50%, rgba(209,209,209,1) 51%, rgba(254,254,254,1) 100%);
background: -ms-linear-gradient(top, rgba(226,226,226,1) 0%, rgba(219,219,219,1) 50%, rgba(209,209,209,1) 51%, rgba(254,254,254,1) 100%);
background: linear-gradient(to bottom, rgba(226,226,226,1) 0%, rgba(219,219,219,1) 50%, rgba(209,209,209,1) 51%, rgba(254,254,254,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e2e2e2', endColorstr='#fefefe', GradientType=0 );
    }

Yo me apoye del sitio: Generador Gradientes CSS para el Gradiente


text:
Q: How to fix cyclic dependency between java modules? I'm refactoring the code so it uses modules . The problem I'm facing is, I got cyclic dependency between modules: convertersapp, validatorsapp and modelapp. There are 6 modules namely:
1. convertersapp
2. exceptionsapp
3. mainapp
4. modelapp
5. serviceapp
6. validatorapp

My current approach - module-info. java files for every modules are:
1. convertersapp: module convertersapp {
  requires modelapp;
  requires gson;
  requires exceptionspp;
  requires validatorapp;
  exports converters.others to serviceapp;
  exports converters.json to modelapp;
}

2. exceptionsapp: module exceptionspp {
  exports exceptions to convertersapp, mainapp,serviceapp, modelapp;
}

3. mainapp: module mainapp {
  requires serviceapp;
  requires exceptionspp;
  requires modelapp;
}

4. modelapp: module modelapp {
  exports model to mainapp, validatorapp,convertersapp, serviceapp;
  exports model.sorting to mainapp,serviceapp;
  requires gson;
  requires exceptionspp;
  requires convertersapp;
}

5. servicapp: module serviceapp {
  exports service to mainapp;
  requires modelapp;
  requires exceptionspp;
  requires convertersapp;
}

6. validatorapp:

  module validatorapp {
  exports validator to convertersapp;
  requires modelapp;
}

A: A cyclic dependency hierarchy should be avoided because it is difficult to understand and it is furthermore unclear in which order the modules should be build (A before B before C before A ...).
Common strategies:

*

*Merge all three modules to one

*Build a common utility module that is used by the others, but which itself does not use others.

*Move some classes to avoid the cyclicity.

A: A corner case, nevertheless worth to look for:
Because I was lazy, I copied the module-info.java file from the 'parent' module to the child, and just added the dependency to that 'parent', ending up with a module info file in the 'child' as below:
module com.pany.parent
{
    requires transitive com.pany.parent;
}

Gradle just complained about a cyclic dependency involving the module com.pany.parent …
Of course this was alone my fault, but after several hours working on the migration to Jigsaw, you sometimes don't see the forest because of so many trees …


text:
Q: TeamCity won't build with NUnit class library I have a .NET solution set up that has the main ASP MVC project and then a class library project that has had NUnit added to it for unit tests.
When I build the solution in TeamCity the main project builds fine but then when the test project builds I get these errors
error BC30002: Type 'TestFixture' is not defined.
error BC30002: Type 'Test' is not defined.
error BC30389: 'System.Diagnostics.Assert' is not accessible in this context because it is 'Friend'.

I assume it can't find the NUnit.dll or something but the dll is in the solution packages folder.  I've tried doing package restore first in case it was that but it still did the same.
Update
Ok, just to test it I added Moq to the project to see if it would pick up the references. It did and worked fine, it seems to be only problem when I try to use NUnit functions.  I could disable it from building but surely the NUnit tests won't be picked up in Team City?
Thanks!

A: Finally fixed the issue and it was my own stupid mistake. Thanks to DevOps for suggesting going through the MSBuild logs, it helped my track down the problem.
The actual DLL wasn't getting checked in to source control because the dev machine that added the test project had a global ignore file to ignore all DLL's. So I thought it was there but it was just the .xml file and I mis read it.
Anyway it now builds and runs the tests.
Thanks for the help everyone


text:
Q: How to find the cause of an exception I am trying to debug a crash whenever an iOS document provider extension is started. As it is a extension I am not able to debug it correctly, and this error log is the best i was able to get out of the device. How can i see what is throwing the exception (or what the assertion is) when none of the methods that get called are mine.
Incident Identifier: 0B4EA724-9AFB-4EE3-B752-7E1FDF3B9A75
CrashReporter Key:   ac4cdaa3c5ddd65a3bffef5cc28903f683f0309d
Hardware Model:      iPad3,1
Process:             FileProvider [1100]
Path:                /private/var/containers/Bundle/Application/CEDD148D-420D-4BE8-ABF8-8E83F6385ABC/Privat.app/PlugIns/FileProvider.appex/FileProvider
Identifier:          com.privat.cloud.FileProvider
Version:             1 (2.5.6)
Code Type:           ARM (Native)
Parent Process:      launchd [1]

Date/Time:           2017-02-09 15:19:03.03 +0100
Launch Time:         2017-02-09 15:19:02.02 +0100
OS Version:          iOS 9.3.5 (13G36)
Report Version:      105

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Filtered syslog:
None found

Last Exception Backtrace:
0   CoreFoundation                  0x22673916 __exceptionPreprocess + 122
1   libobjc.A.dylib                 0x21e0ee12 objc_exception_throw + 34
2   CoreFoundation                  0x226737ec +[NSException raise:format:arguments:] + 100
3   Foundation                      0x22e57524 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 88
4   UIKit                           0x26fc83e0 -[UIDocumentPickerExtensionViewController _prepareWithExtensionInfo:completionHandler:] + 504
5   CoreFoundation                  0x226784c0 __invoking___ + 64
6   CoreFoundation                  0x2259e878 -[NSInvocation invoke] + 288
7   CoreFoundation                  0x225a22f2 -[NSInvocation invokeWithTarget:] + 46
8   UIKit                           0x27489390 -[_UIViewServiceImplicitAnimationDecodingProxy forwardInvocation:] + 252
9   CoreFoundation                  0x22676d7e ___forwarding___ + 346
10  CoreFoundation                  0x225a2234 _CF_forwarding_prep_0 + 20
11  CoreFoundation                  0x226784c0 __invoking___ + 64
12  CoreFoundation                  0x2259e878 -[NSInvocation invoke] + 288
13  CoreFoundation                  0x225a22f2 -[NSInvocation invokeWithTarget:] + 46
14  UIKit                           0x27408b32 -[_UIQueueingProxy forwardInvocation:] + 370
15  CoreFoundation                  0x22676d7e ___forwarding___ + 346
16  CoreFoundation                  0x225a2234 _CF_forwarding_prep_0 + 20
17  CoreFoundation                  0x226784c0 __invoking___ + 64
18  CoreFoundation                  0x2259e878 -[NSInvocation invoke] + 288
19  CoreFoundation                  0x225a22f2 -[NSInvocation invokeWithTarget:] + 46
20  CoreFoundation                  0x22676d7e ___forwarding___ + 346
21  CoreFoundation                  0x225a2234 _CF_forwarding_prep_0 + 20
22  CoreFoundation                  0x226784c0 __invoking___ + 64
23  CoreFoundation                  0x2259e878 -[NSInvocation invoke] + 288
24  CoreFoundation                  0x225a22f2 -[NSInvocation invokeWithTarget:] + 46
25  CoreFoundation                  0x22676d7e ___forwarding___ + 346
26  CoreFoundation                  0x225a2234 _CF_forwarding_prep_0 + 20
27  CoreFoundation                  0x226784c0 __invoking___ + 64
28  CoreFoundation                  0x2259e878 -[NSInvocation invoke] + 288
29  FrontBoardServices              0x23d16c02 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 14
30  FrontBoardServices              0x23d16ab4 -[FBSSerialQueue _performNext] + 220
31  FrontBoardServices              0x23d16db4 -[FBSSerialQueue _performNextFromRunLoopSource] + 44
32  CoreFoundation                  0x22635dfa __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 10
33  CoreFoundation                  0x226359e8 __CFRunLoopDoSources0 + 448
34  CoreFoundation                  0x22633d56 __CFRunLoopRun + 790
35  CoreFoundation                  0x22583224 CFRunLoopRunSpecific + 516
36  CoreFoundation                  0x22583010 CFRunLoopRunInMode + 104
37  GraphicsServices                0x23b73ac4 GSEventRunModal + 156
38  UIKit                           0x26c57184 UIApplicationMain + 140
39  libxpc.dylib                    0x223cd07c _xpc_objc_main + 700
40  libxpc.dylib                    0x223ce730 xpc_main + 164
41  Foundation                      0x22f74790 -[NSXPCListener resume] + 160
42  PlugInKit                       0x28afe128 -[PKService run] + 504
43  PlugInKit                       0x28afddf6 +[PKService main] + 54
44  PlugInKit                       0x28afe15c +[PKService _defaultRun:arguments:] + 16
45  libextension.dylib              0x22db37c8 NSExtensionMain + 44
46  libdyld.dylib                   0x2222b86e tlv_get_addr + 42

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x222fec5c __pthread_kill + 8
1   libsystem_pthread.dylib         0x223a8732 pthread_kill + 62
2   libsystem_c.dylib               0x222930ac abort + 108
3   libc++abi.dylib                 0x21deaae4 __cxa_bad_cast + 0
4   libc++abi.dylib                 0x21e0369e default_terminate_handler() + 266
5   libobjc.A.dylib                 0x21e0f0b0 _objc_terminate() + 192
6   libc++abi.dylib                 0x21e00e16 std::__terminate(void (*)()) + 78
7   libc++abi.dylib                 0x21e008f8 __cxa_increment_exception_refcount + 0
8   libobjc.A.dylib                 0x21e0ef5e objc_exception_rethrow + 42
9   CoreFoundation                  0x225832ae CFRunLoopRunSpecific + 654
10  CoreFoundation                  0x22583014 CFRunLoopRunInMode + 108
11  GraphicsServices                0x23b73ac8 GSEventRunModal + 160
12  UIKit                           0x26c57188 UIApplicationMain + 144
13  libxpc.dylib                    0x223cd080 _xpc_objc_main + 704
14  libxpc.dylib                    0x223ce734 xpc_main + 168
15  Foundation                      0x22f74794 service_connection_handler + 0
16  PlugInKit                       0x28afe12c -[PKService run] + 508
17  PlugInKit                       0x28afddfa +[PKService main] + 58
18  PlugInKit                       0x28afe160 +[PKService _defaultRun:arguments:] + 20
19  libextension.dylib              0x22db37cc NSExtensionMain + 48
20  libdyld.dylib                   0x2222b872 start + 2

Thread 1:
0   libsystem_kernel.dylib          0x222ff864 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x223a5b34 _pthread_wqthread + 1036
2   libsystem_pthread.dylib         0x223a5718 start_wqthread + 8

Thread 2 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 2:
0   libsystem_kernel.dylib          0x223002f8 kevent_qos + 24
1   libdispatch.dylib               0x221f5d60 _dispatch_mgr_invoke + 256
2   libdispatch.dylib               0x221f5abe _dispatch_mgr_thread$VARIANT$mp + 38

Thread 3:
0   libsystem_kernel.dylib          0x222ff864 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x223a5b34 _pthread_wqthread + 1036
2   libsystem_pthread.dylib         0x223a5718 start_wqthread + 8

Thread 4:
0   libsystem_kernel.dylib          0x222ff864 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x223a5b34 _pthread_wqthread + 1036
2   libsystem_pthread.dylib         0x223a5718 start_wqthread + 8

Thread 5:
0   libsystem_kernel.dylib          0x222ff864 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x223a5b34 _pthread_wqthread + 1036
2   libsystem_pthread.dylib         0x223a5718 start_wqthread + 8

Thread 6 name:  com.apple.coremedia.player.async
Thread 6:
0   libsystem_kernel.dylib          0x222ea920 semaphore_wait_trap + 8
1   libdispatch.dylib               0x221f294a _dispatch_semaphore_wait_slow + 190
2   MediaToolbox                    0x279571ec fpa_AsyncMovieControlThread + 1916
3   CoreMedia                       0x2462b9b8 figThreadMain + 208
4   libsystem_pthread.dylib         0x223a785a _pthread_body + 138
5   libsystem_pthread.dylib         0x223a77ce _pthread_start + 110
6   libsystem_pthread.dylib         0x223a5724 thread_start + 8

Thread 0 crashed with ARM Thread State (32-bit):
    r0: 0x00000000    r1: 0x00000000      r2: 0x00000000      r3: 0x00000000
    r4: 0x00000006    r5: 0x395c3000      r6: 0x38803304      r7: 0x0037e378
    r8: 0x14582d00    r9: 0x21e048fd     r10: 0x3428ff05     r11: 0x14582d24
    ip: 0x00000148    sp: 0x0037e36c      lr: 0x223a8733      pc: 0x222fec5c
  cpsr: 0x00000010

If i setup a global exception breakpoint i get this, and it is not helpful:
libobjc.A.dylib`objc_exception_throw:
->  0x23c5edf0 <+0>:   push   {r4, r5, r6, r7, lr}
    0x23c5edf2 <+2>:   add    r7, sp, #0xc
    0x23c5edf4 <+4>:   .long  0x0d00e92d                ; unknown opcode
    0x23c5edf8 <+8>:   .long  0x6dfaf5ad                ; unknown opcode
    0x23c5edfc <+12>:  mov    r5, r0
    0x23c5edfe <+14>:  movs   r0, #0x10
    0x23c5ee00 <+16>:  bl     0x23c5027c                ; __cxa_allocate_exception


text:
Q: ASP.NET wrong model type I'm working on a website and I'm struggling with the Models I pass to my Views. I ended up testing if it worked in the most basic way to be sure I hadn't done something obviously wrong. Still doesn't work :
My Controller :
public class HomeController : Controller
{
    public ActionResult Test()
    {
        List<Model_Test> model = new List<Model_Test>
                {
                new Model_Test{Name = "Henri", Age = 24, City = "Paris"},
                new Model_Test{Name = "Jacob", Age = 18, City = "Caen"},
                new Model_Test{Name = "Patrick", Age = 57, City = "Lille"},
                new Model_Test{Name = "Youri", Age = 13, City = "Bordeaux"},
                };
        return View(model);
    }
}

My Model :
public class Model_Test
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

And my View is the view I created by right-clicking the ActionResult Test(). I set it to List with Model-test as a Model.
@model IEnumerable<AVdevWebsite.Models.Model_Test>
Yet I can't display my small List since I get this error :

The model item passed into the dictionary is of type "System.Collections.Generic.List"1[AVdevWebsite.Models.Model_Test]", but this dictionary requires a model item of type "AVdevWebsite.Models.Model_User".

Thank you !
Edit :
Main View :

                        using (Html.BeginForm())
                        {
                            @model AVdevWebsite.Models.Model_User

                            @Html.AntiForgeryToken()

Se Connecter

                                                @if (Session[ErrorAlerts.ERRORALERT] != null)
                                                {

@Session[ErrorAlerts.ERRORALERT]

                                                }

                                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                                                @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "sr-only" })
                                                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control", @placeholder = "Identifiant" } })
                                                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })

                                                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "sr-only" })
                                                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @placeholder = "Mot de Passe" } })
                                                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                                                <button class="btn btn-lg btn-primary" type="submit">Login</button>
                                                Invité

                        }

And here is the partial View :
@model IEnumerable<AVdevWebsite.Models.Model_Test>

@{
    ViewBag.Title = "Test_ManageUsers";
}

Test_ManageUsers

    @Html.ActionLink("Create New", "Create")

    ...

The error was due to the Main View asking for a @model.

A: I'm having a little trouble understanding how all these particular pieces fit together, so I'll try to offer some general MVC tips.
MVC works on the premise of the View dictating the layout/presentation specifics of the requested information, the Model represents the data requested, and the Controller does the work of constructing the Model and providing it to the View to generate the response.
Structurally, Views can be treated as components, and the "final" view can be created from multiple view components.  Views are generally coded against specific Model types, though, so nesting view components together can become kind of complicated pretty quickly.
There are a couple of ways that I know of to handle this situation as I understand it.
1) through complex Model objects.  You can define the Model to be whatever you need it to be, and you need to make sure your Model has all the "stuff" your View needs.  If the view has partial views nested within it, then a complex primary model can be designed to hold all the model information needed by the sub-views components.
In that case, your models might look something like this (NOTE: Model_Test has a Model_User property named User):
public class Model_User
{
    // Properties go here...
}

public class Model_Test
{
    public Model_User User { get; set; }

    // Properties go here...
}

your User view might look this this:
@model WebApplication1.Models.Model_User

@*View stuff goes here*@

and your Test view might look like this:
@model WebApplication1.Models.Model_Test

Test

@Html.Partial("User", Model.User)

In order to support that, your controller would need to create the User_Model as part of the process of creating the Test_Model:
    public ActionResult Test()
    {
        // Build user model here
        var userModel = new Model_User();

        // Build test model so that it contains the user model
        var model = new Model_Test();
        model.User = userModel;

        return View(model);
    }

2) Alternatively you can delegate responsibility of handling the model-building to the Controller by way of a separate action method.  That way, the primary model doesn't necessarily have to have all the sub-view "stuff" contained within it, it can call out to the appropriate controller action and let it handle that.
In this case, your primary model is less complex; it can be stream-lined more in line with the view(s) it directly supports, but the draw back can be hidden complexity and repetition of server operations.
For this approach, your code might look something like the following:
For this, the models can be kept more simple (NOTE: Model_Test doesn't have to know anything about Model_User in this case)
public class Model_User
{
    // Properties go here...
}

public class Model_Test
{
    // Properties go here...
}

The controller would have a new action that generates the partial view for User (and handles building the supporting model)
public ActionResult User()
{
    // Build user model here
    var model = new Model_User();
    return PartialView(model);
}

public ActionResult Test()
{
    // Build test model here.  Model doesn't have to "know" anything about user details
    var model = new Model_Test();
    return View(model);
}

The Test view relies on the Controller to do that work by way of that Action:
@model WebApplication1.Models.Model_Test

Test

@Html.Action("User")


text:
Q: Shell script 'not an identifier error' I have a script that should connect to oracle and run a query.
When I run the script I get the following error.
ORACLE_HOME=/app/oracle/product/10.2.0
export ORACLE_HOME
atm_test.sh: ORACLE_HOME^M: is not an identifier

My script looks like this.
ORACLE_HOME=/app/oracle/product/10.2.0; export ORACLE_HOME
ORACLE_SID=sid; export ORACLE_SID
PATH=/usr/bin:/usr/sfw/bin:/app/oracle/product/10.2.0/bin; export PATH
...

In the shell when I echo $ORACLE_HOME it outputs /app/oracle/product/10.2.0
So I don't know what the issue could be.

A: Your script has Windows-style line endings.  Run it through dos2unix or a similar tool.  (Note that, unlike most filters, dos2unix overwrites the input file, so be careful.)
Are you using Cygwin?


text:
Q: Edit Single Row And Refresh Just That Row In Datagridview I have 10000 rows in my datagridview,now when i edit one of the rows,i should refresh all the rows with select stored procedure that i wrote.
How do you suggest to me to refresh(select) just that edited row?

A: Since you already added the new values, it might not be needed to refresh your whole grid, only refresh it when you need another record, or update that row and get the index and reload only that row using the index that you already have


text:
Q: ImageViewer Together with TextView PREV and NEXT so I made an ImageViewer on my app, that uses counting to go through all the pictures. By using the next and prev button. Now I'm trying to add a textview to go with it. So I made another textview under it, and tried this code:
   View.OnClickListener nButtonChangeImageListener = new View.OnClickListener() {

        public void onClick(View view) {
            //Increase Counter to move to next Image
            currentImage--;
            currentImage = (currentImage + images.length) % images.length;

            imageView.setImageResource(images[currentImage]);
            if(currentImage == img1){
                textView4.setText("My Awesome Text");
            }

        }
    };

UPDATE: I tried this, but yeah still wouldn't work.
View.OnClickListener nButtonChangeImageListener = new View.OnClickListener() {
public void onClick(View view) {
    //Increase Counter to move to next Image
    currentImage--;
    currentImage = (currentImage + images.length) % images.length;
     String img1 = "img1";
    String comparable = imageView.toString();
    imageView.setImageResource(images[currentImage]);
    if(comparable == img1){
        textView4.setText("My Awesome Text");
    }

}

};
This is the listener for my next and prev button. I figured out that using the if statement, if(currentImage == img1) I could match the textview to its own image. Let's say for img1 I'll set it to "Awesome text"
Unfortunately, it won't work, I thought of making currentImage as a string but it's not allowed. What's another approach to this? or perhaps what did I do wrong on the snippet?

A: This is one possible solution where you keep your text references in an array of the same lenght as the image array:
  View.OnClickListener buttonChangeImageListener = new View.OnClickListener() {

    public void onClick(View view) {
        //Increase Counter to move to next Image and Text
        current++;
        current = current % images.length;

        imageView.setImageResource(images[current]);
        textView4.setText(texts[current]);

    }
};

EDIT:
One way to define texts array is:
String []texts = {"Text1","Text2",...,"TextN"};

So the array will have as many strings as there are pictures.
The other way is to define strings in Resorces (like you did with pictures). Add a new file under res/values and call it for example texts.xml.
texts.xml would look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="text1">This is text 1</string>
    <string name="text2">This is text 2</string>
     ....
    <string name="textN">This is text N</string>
</resources>

Then in your code
int [] texts = {R.string.text1, R.string.text2,...,R.string.textN} ;

To get texts:
textView4.setText(getResources().getString(texts[current]));

A: It seems that you are quite in a trouble eh. Try to think out of the box young'un!
I bet you're using an integer in order to go through your list. Like that currentImage set to 0.
So here's another appraoch so listen,
set another integer, let's say:
private int currentText = 0;

then:
  View.OnClickListener bButtonChangeImageListener = new View.OnClickListener() {

        public void onClick(View view) {
            //Increase Counter to move to next Image
            currentImage++;
            currentText++;
            currentImage = currentImage % images.length;

            imageView.setImageResource(images[currentImage]);
            if (currentText == 1)
            {
                textView4.setText("AwesomeText");
            }
            if (currentText == 2)
            {
                textView4.setText("AwesomeText1");
            }

            if (currentText == 0)
            {
                textView4.setText("AwesomeText2");
            }

        }
    };

    View.OnClickListener nButtonChangeImageListener = new View.OnClickListener() {

        public void onClick(View view) {
            //Increase Counter to move to next Image
            currentImage--;
            currentText--;
            currentImage = (currentImage + images.length) % images.length;

            if (currentText == 1)
            {
                textView4.setText("AwesomeText");
            }
            if (currentText == 2)
            {
                textView4.setText("AwesomeText1");
            }

            if (currentText == 0)
            {
                textView4.setText("AwesomeText2");
            }

        }
    };

Well something along those lines!


text:
Q: What is the real world use of BeanPostProcessor in spring? I am aware of the bean post processor and it's working but I am not sure how it will helps us in real world application. what should be there inside the below define method in real application could it be
1 Some configuration Code?
2 Some validation code for bean ?

 public class MyBeanInitProcessor implements BeanPostProcessor{

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException {
            System.out.println("before initialization: "+beanName);
            return bean;
        }

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName)
                throws BeansException {
            System.out.println("after initialization: "+beanName);
            return bean;
        }
    }

A: In most real-world applications, you won't be interacting with them directly. Spring provides 28 implementations out of the box that handle standard functions like autowiring and applying AOP advice. You use them indirectly by using the standard Spring features such as applying validation annotations on a method parameter, which applies MethodValidationPostProcessor, or making method calls @Async, which applies AsyncAnnotationBeanPostProcessor.

A: BeanPostProcessor is a means of running a bit of code each time a bean is initialized.

*

*Say you had an algorithm to process an undetermined number of Customer objects.

*Say each Customer was a bean, and (as you may find in a LinkedList) each bean could tell if there was a bean following it, or not.

*Say further that you need an event to be thrown when the last bean in that list was initialized.

You could do that, if you added code in postProcessAfterInitialization(). Knowing Spring, there are better ways, no doubt. Still, to me, this would be a case where BeanPostProcessor could be helpful.


text:
Q: How WordPress manages its session? I'm curious to know, how WordPress manages its session state.
I have searched for session_start(), but its not there. I'm not sure, if it stores session into DB or any other technique.


text:
Q: UIwebview: Know where the user is in the webcontent Suppose I wish to load a UIWebview with a webpage that contains content(similar to that in a book) in the form of different chapters (say chapter 1,2,3,4) and I want to place a favorite chapter functionality.
My question is ,if on the UIWebview, the user is scrolling between chapters, how would I know where the user is finally , so that I can mark the chapter as favorite.?
Is there a way to know what the content is at content offset of webview's scrollview ?

A: implement UIWebViewDelegate and define your object as web view  delegate . define this method, which will inform you whenever you load the page from url. you can book save it then load the webview with this url later to bring the user next time directly to this page.
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
         NSLog(@"can load this URL :%@",request.URL.absoluteString);

         //return FALSE; //to stop loading
         return YES;
    }

   - (void)webViewDidStartLoad:(UIWebView *)webView{
      NSLog(@"starts to load URL :%@",webView.request.URL.absoluteString);
   }

   - (void)webViewDidFinishLoad:(UIWebView *)webView{
      NSLog(@"Loaded URL :%@",webView.request.URL.absoluteString);
   }


text:
Q: centering a background image, seems so much harder than it should be okay its been about an hour of googling and at this point im probably overthinking it.
HTML

CSS
img {
background-position: center center;
}

all the above code does is places the img in the upper left corner.
ive also tried, fixed, static, relative, absolute on the img tag and it changes nothing.
am i targeting the wrong spot by using img in the css?

A: Right now you're positioning background image in CSS, which should be defined also in CSS, but you're using a IMG tag.

Your text here

A: First off, why not define the image as a background in CSS instead of using the img tag? Also you have some syntax nesting errors, be careful to close tags appropriately.
HTML

CSS
.container-fluid {
   background:url('background-image.jpeg') center;
   min-height:500px /* adding height to see the div, otherwise it won't show up */
}

Make sure the image path is correct in relation to the CSS file

A: Try wrapping it with an element that uses text-align: center;. Example:
HTML

CSS
.center-me {
    text-align: center;
}

Or you could add text-align: center; to container-fluid, but that will probably affect other things in that container:
.container-fluid {
    text-align: center;
}


text:
Q: C# Morse decoder I have school project to write program which should translate text to morse code and also morse code to string. Down here is my code which translates just text to morse, but I have no idea how to translate morse code to text. Any ideas? I tried to solve it using for cycles but it didn't work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace morse
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] text = { ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
            string[] TranslatedMorse = { "    |", " . - |", " - . . . |", " - . - . |", " - . . |", " . |", " . . - . |"
                    , " - - . |", " . . . . |", " . . |", " . - - - |", " - . - |", " . - . . |", " - - |",
                " - . |", " - - - |", " . - - . |", " - - . - |", " . - . |", " . . . |", " _ |", " . . - |",
                " . . . - |", " . - - |", " - . . - |", " - . - - |", " - - . . |", " . - - - - |",
                " . . - - - |", " . . . - - |", " . . . . - |", " . . . . . |", " - . . . . |", " - - . . . |",
                " - - - . . |", " - - - - . |", " - - - - - |" };
            Console.WriteLine("Choose translation:");
            Console.WriteLine("[1] String to Morse");
            Console.WriteLine("[2] Morse to String");
            int.TryParse(Console.ReadLine(), out int selection);
            Console.WriteLine($"You've choosen: [{selection}]");
            string ToTranslate = "";
            string TranslatedText = "";
            if (selection == 1)
            {
                Console.WriteLine("Enter text:");
                ToTranslate = Console.ReadLine();
                ToTranslate = ToTranslate.ToLower();
                for (int i = 0; i < ToTranslate.Length; i++)
                {
                    for (int j = 0; j < 37; j++)
                    {
                        if (ToTranslate[i] == text[j])
                        {
                            TranslatedText += TranslatedMorse[j];
                            break;
                        }
                    }
                }
                Console.WriteLine($"Translated text: {TranslatedText}");

            }
            else if (selection == 2)
            {
                Console.WriteLine("Enter morse code using '.' or '-', split each letter by space, whole words split by two spaces");
                ToTranslate = Console.ReadLine();
                //This I need to solve.
            }
            else
            {
                Console.WriteLine("Nothing selected, program will shut down");
                System.Environment.Exit(1);
            }
        }
    }
}

A: Take your morse string and use the Split function to separate the string into an array of strings using the | delimiter. Then you can check each element to find the corresponding letter.
Though on StackOverflow they expect you to make a bigger effort before asking. It helps to break the problem up into very small pieces rather than looking at the whole problem of translating from x to y. In other words, see how would you do it as a human being before you code it and then try to do that in code. Also if teachers aren't a help you might consider working in teams with other students to make more progress (it's also more fun).


text:
Q: Maxwell's demon - Landauer's principle and it's incompatibility with the 1st law of thermodynamics Let's recapitulate and state both the Maxwell's demon and the official most-widely accepted solution to the paradox, namely Landauer's principle:

*

*The Maxwell demon paradox:
A demon just by observing But Never Touching -hence no energy is transferred- the molecules of two chamber of gas separated by a door, opening and closing the door between the two sides at the right moments can create a temparature difference, therefore creating an entropy decrease, which can be used to do useful work, thus violating the Second Law of Thermodaynamics.

*Landauer's principle the officially accepted solution to the paradox:
Not when the Demon acquires the information about the molecules of the gas, but when erases the accumulated information the Demon's memory offsets the created entropy decrease and amount of work extracted by an amount of dissipated heat-energy at least as much as much useful work was done by the action of the demon. Therefore the dissipated heat to the environment offsets the entropy decrease created by the action of the demon, thus the Second Law of Thermodynamics is preserved.
The problem:
This is a so horribly shallow superficial explanation, that barely stands until said.
Because let's see:

*

*It is not mandatory to extract the created temperature difference into useful work, we can decide to stop the demon to do it's job, keep the information in the memory, and just to let the two sides to come back to thermal equilibrium, and
because we settled on the conditions that the Demon doesn't exchange any energy with the molecules, the total energy is the same constant all the time, but if we now ask the Demon to erase it's memory, still has to dissipate heat-energy to the environment, because this is also settled in Landauer's erasure principle, but in this way energy is created on the top of already total constant energy, so the Conservation of Law of Energy (1st law of thermodynamics) is violated.
Of course with this example can be seen that by applying Landauer's principle, and dissipate heat on erasure the 1st Law of Thermodyanics - the conservation of energy - is violated all the time, no matter what order the things are done.

I'm waiting for answers please.
Thank you

A: I think, from the wording of the question, that you might not have understood the idea of Landauer's principle quite right. The principle asserts that if a system goes from one of two macroscopically distinct initial states to one and the same final state, by interacting with an environment which goes from its initial state to a final state described by the same set of macroscopic parameters (e.g. volume, temperature) in either case, then it must be that the entropy of the final state of the environment has gone up (because its macrostate now includes twice as many microstates as it did initially). Landauer then points out that in order to cause such a change in a thermal environment at finite temperature, one must supply not only entropy but also energy to the environment.
This principle does not assert that such an energy supplied to the environment is simply conjured up from nowhere, in violation of the first law. Rather, it has to be extracted from the system which is interacting with the environment. In the case of the Maxwell daemon, although no energy transfer is needed in order for the daemon to acquire information about microstates of a system, an energy transfer is required during the memory erasure. There is no contradiction between these two statements; they are two different processes.


text:
Q: Were there any contemporary sources (prior to RotJ) that confirmed that Darth Vader was telling the truth to Luke? It struck me that the average movie viewer (upon hearing the famous "No, I am your father" line) might have disbelieved it and it's not until Return of the Jedi, three years later, that we see Yoda confirming that Vader was telling the truth.
Before then, was it commonly accepted as fact that Vader was Luke's father? Or was it more a sense of "I can't wait until the sequel so that we can find out if Vader was telling the truth or not!" Or a more dismissive "Wow, I can't believe Vader lied like that to try and fool Luke"?
Obviously different moviegoers will have had different reactions, but was there any clear intention revealed by the creators or studio that confirms that Vader was really Luke's father, as opposed to simply Vader saying that he was Luke's father?

A: Lucas claimed (in an interview published in Empire Magazine Issue #156 (June 2002) that he intended for the audience to be unaware whether Vader was telling the truth until they watched the third film.

Lucas claims he had the notion in mind from the start, but the idea
  didn't appear until the second draft of Empire, and in the first there
  is the contradictory appearance of a different father (a ghostly
  presence like Kenobi). Lucas also wrestled with the idea of keeping
  schtum on Luke's parentage until the end of the third film, but
  eventually found the perfect moment. "I conceived it so that you would
  not know if Vader was lying or telling the truth," Lucas said. "You
  have to have an escape hatch for kids psychologically so they can deny
  it."

Note also that Luke, in the film's official novelisation (published in 1980) has much the same concerns to begin with, that Vader might be lying. By the end of the book/film he's pretty much accepted that Vader is his father and is more concerned with why Ben didn't tell him.

Luke's mind whirled with those words. Everything was finally beginning to coalesce in his brain. Or was it? He wondered if Vader were telling him the truth—if the training of Yoda, the teaching of saintly old Ben, his own strivings for good and his abhorrence of evil, if everything he had fought for were no more than a lie.
He didn't want to believe Vader, tried convincing himself that it was Vader who lied to him — but somehow he could feel the truth in the Dark Lord's words. But, if Darth Vader did speak the truth, why, he wondered, had Ben Kenobi lied to him? Why? His mind screamed louder than any wind the Dark Lord could ever summon against him.


text:
Q: running system commands on linux using python? I'm wondering if someone can either direct me to a example or help me with my code for running commands on linux(centos).  Basically, I am assuming I have a basic fresh server and want to configure it.  I thought I could list the commands I need to run and it would work but I'm getting errors. The errors are related to nothing to make(when making thift).
I think this is because(I'm just assuming here) that python is just sending the code to run and then sending another and another and not waiting for each command to finish running(after the script fails, I check and the thrift package is downloaded and successfully uncompressed).
Here's the code:
#python command list to setup new server
import commands
commands_to_run = ['yum -y install pypy autocon automake libtool flex boost-devel gcc-c++  byacc svn openssl-devel make  java-1.6.0-openjdk git wget', 'service mysqld start',
                'wget http://www.quickprepaidcard.com/apache//thrift/0.8.0/thrift-0.8.0.tar.gz', 'tar zxvf thrift-0.8.0.tar.gz',
                'cd thrift-0.8.0', './configure', 'make', 'make install' ]

for x in commands_to_run:
    print commands.getstatusoutput(x)

Any suggestions on how to get this to work?  If my approach is totally wrong then let me know(I know I can use a bash script but I'm trying to improve my python skills).

A: Since commands has been deprecated for a long time, you should really be using subprocess, specifically subprocess.check_output. Also, cd thrift-0.8.0 only affects the subprocess, and not yours. You can either call os.chdir or pass the cwd argument to subprocess functions:
import subprocess, os
commands_to_run = [['yum', '-y', 'install',
                    'pypy', 'python', 'MySQL-python', 'mysqld', 'mysql-server',
                    'autocon', 'automake', 'libtool', 'flex', 'boost-devel',
                    'gcc-c++', 'perl-ExtUtils-MakeMaker', 'byacc', 'svn',
                    'openssl-devel', 'make', 'java-1.6.0-openjdk', 'git', 'wget'],
                   ['service', 'mysqld', 'start'],
                   ['wget', 'http://www.quickprepaidcard.com/apache//thrift/0.8.0/thrift-0.8.0.tar.gz'],
                   ['tar', 'zxvf', 'thrift-0.8.0.tar.gz']]
install_commands = [['./configure'], ['make'], ['make', 'install']]

for x in commands_to_run:
    print subprocess.check_output(x)

os.chdir('thrift-0.8.0')

for cmd in install_commands:
    print subprocess.check_output(cmd)

Since CentOS maintains ancient versions of Python, you may want to use this backport instead.
Note that if you want to print the output out anyways, you can just call the subprocess with check_call, since the subprocess inherits your stdout,stderr, and stdin by default.


text:
Q: How to access sprite sheet as3 I am new to Action script 3, please tell me how to access each image inside sprite sheet to the class As3 or any other reference project also kindly provide me.
Also step by step process to access these images inside my custom class.
Thanks in Advance.

A: There's a bit of work involved when it comes to sprite sheets.
There are frameworks and libraries that help you do this.
It also depends on what technique you use to display things (regular DisplayObjects, blitting, starling, ...)
You should have the sprite sheet as a BitmapData object, by either loading it with a Loader or embedding it. (how this works is not within the scope of your question, I assume)
From there, the code does what you would normally do with such a sheet: cut it into pieces.
To do this you create a second BitmapData object, this will be your character or whatever.
This is the BitmapData that you actually display. Do this for example with the help of an Bitmap object.
What you do now is to use copyPixels() to copy portions of your sprite sheet to your character BitmapData. This methods takes a rectangle (among other things) as a parameter that specifies what portion of the source BitmapData (that's the sprite sheet) should be copied.
What you now have to do is change what sections are copied depending on what you want to achieve.
Maybe there's a sequence in your sheet, so you would have to move the rectangle object in order to copy different "frames" of the animation.
As mentioned, there are other ways to display this data, but in essence it all boils down to copying pixels from the sheet and throwing them at something that an display them.
And the copyPixels() method does that.

A: Try using Starling, instead classic Flash
look this link:
http://wiki.starling-framework.org/manual/movie_clips
// Embed the Atlas XML
[Embed(source="atlas.xml", mimeType="application/octet-stream")]
public static const AtlasXml:Class;

// Embed the Atlas Texture:
[Embed(source="atlas.png")]
public static const AtlasTexture:Class;

// create atlas
var texture:Texture = Texture.fromBitmap(new AtlasTexture());
var xml:XML = XML(new AtlasXml());
var atlas:TextureAtlas = new TextureAtlas(texture, xml);

// create movie clip
var movie:MovieClip = new MovieClip(atlas.getTextures("flight_"), 10);
movie.loop = false; // default: true
addChild(movie);

// control playback
movie.play();
movie.pause();
movie.stop();

// important: add movie to juggler
Starling.juggler.add(movie);


text:
Q: Why is this object not garbage collected In the following code segment, I am wondering why testvectors is not collected after the function call. I see memory usage go up to 270Mb and then stay there forever.
This function is directly called from Main.
private static void increaseMemoryUsage()
{
    List<List<float>> testvectors = new List<List<float>>();
    int vectorNum = 250 * 250;
    Random rand = new Random();

    for (int i = 0; i < vectorNum; i++)
    {
        List<Single> vec = new List<Single>();

        for (int j = 0; j < 1000; j++)
                {
            vec.Add((Single)rand.NextDouble());
        }
        testvectors.Add(vec);
    }
}

A: Don't confuse garbage collection with reference counting. The memory is freed when the runtime decides, not always when it's no longer referenced. To quote:

Garbage collection occurs when one of the following conditions is
  true:
The system has low physical memory.
The memory that is used by allocated objects on the managed heap
  surpasses an acceptable threshold. This means that a threshold of
  acceptable memory usage has been exceeded on the managed heap. This
  threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you do not have
  to call this method, because the garbage collector runs continuously.
  This method is primarily used for unique situations and testing.

Read this if you're interested:
http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx

A: The GC can run when it wants. And that can be much later. There is no obligation to free some memory directly after the last reference goes away. Your array will get collected on the next Gen2 collection.
Unless you keep allocating memory, it will likely never run after the function returns.
You can manually trigger a GC with GC.Collect(), but that's generally discouraged.

A: I observe the opposite when I run this:
 class Program
    {
        static void Main(string[] args)
        {
            increaseMemoryUsage();

            Console.WriteLine("Hit enter to force GC");
            Console.ReadLine();

            GC.Collect();

            Console.ReadLine();
        }

        private static void increaseMemoryUsage()
        {
            var testvectors = new List<List<float>>();
            const int vectorNum = 250 * 250;
            var rand = new Random();

            for (var i = 0; i < vectorNum; i++)
            {
                var vec = new List<Single>();

                for (var j = 0; j < 1000; j++)
                    vec.Add((Single)rand.NextDouble());

                testvectors.Add(vec);
            }
        }
    }

A: Most likely, your testvectors is getting promoted to the Large Object Heap (LOH) and then it is not collected during the Gen0 collection.
Good link here.

A: Garbage collection is non-deterministic. It's up to GC to decide when is a good moment to do it.

A: Try to add GC.GetTotalMemory(true) before and after increaseMemoryUsage() method usage and compare numbers.


text:
Q: How to activate the cursor for a fabric js IText? I'd like to be able to add text to the canvas and have it go directly into editing text mode where the cursor is visible and you can start typing.
So far I've got this code that adds the text and sets it as active, but I'm not sure on how to go to the edit text mode.  Any ideas?  Thanks!
    var fabicText = new fabric.IText('Click to change Text', { left: 100, top: 100 });
   fabicText.set({ fill: getSelectedColorText() });
   _fabicCanvas.add(fabicText);

  _fabicCanvas.setActiveObject(fabicText);

A: You have to use enterEditing() method and then set focus on hiddenTextArea like this
fabicText.enterEditing();
fabicText.hiddenTextarea.focus();

var _fabicCanvas;

$(function () {
    _fabicCanvas = window._canvas = new fabric.Canvas('canvas');
    var fabicText = new fabric.IText('Click to change Text', {
        left: 100,
        top: 100
    });
    _fabicCanvas.add(fabicText);
    fabicText.set({ fill: 'blue' });
    _fabicCanvas.setActiveObject(fabicText);
    fabicText.enterEditing()
    fabicText.hiddenTextarea.focus();

});
<script src="https://rawgit.com/kangax/fabric.js/v1.4.5/dist/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400" class="canvas"></canvas>

A: For Android, the only thing works
  Text.on('selected', function () {
    setTimeout(() => {
      Text.enterEditing();
      Text.hiddenTextarea.focus();
    }, 100);
  });


text:
Q: Distributed Lock Service Which distributed lock service would you use?
Requirements are:

*

*A mutual exclusion (lock) that can be seen from different processes/machines

*lock...release semantics

*Automatic lock release after a certain timeout - if lock holder dies, it will automatically be freed after X seconds

*Java implementation

*Nice to have: .Net implementation

*If it's free: Deadlock detection / mitigation

*Easy deployment, see note below.

I'm not interested in answers like "it can be done over a database", or "it can be done over JavaSpaces" - I know. I'm interested in a ready, out-of-the-box, proven implementation.

A: I recommend to use Redisson it's a Redis based on In-Memory Data Grid. It implements familiar Java data structures including distributed java.util.Lock and java.util.concurrent.ReentrantReadWriteLock objects. Including ability to setup leaseTime. Lock usage example:
Redisson redisson = Redisson.create(config);

Lock lock = redisson.getLock("anyLock");
try {
   // unlock automatically after 10 seconds of hold
   lock.lock(10, TimeUnit.SECONDS);

} finally {
   lock.unlock();
}

...

redisson.shutdown();

Supports cloud vendors like Azure and AWS.

A: A newer kid on the block is hazelcast. I've been playing with it and it is amazingly simple to use and configure.
As far as I can see there shouldn't be any conflict between Gigaspaces and hazelcast as hazelcast doesn't have any dependencies i.e. no jgroups.jar etc
Hazelcast:

*

*A mutual exclusion (lock), yep implementation of java.util.concurrency.locks.Lock

*Automatic lock release after a certain timeout, yep all locks are released if a member leaves the cluster

*Java implementation, yep

*Nice to have: .Net implementation, nope is a pure java solution, might be possible to port to j#

*If it's free: Deadlock detection / mitigation, nope no effort is made my Hazelcast to handle this

*Easy deployment, it's a single jar with a single config file, deployed as part of your application, no additional processes are required

A: ZooKeeper became a de facto standard in distributed locking with the help of Apache Curator framework. Check out the locks in recipes for more information.

A: Check out Apache's Zookeeper (A Hadoop sub-project) - it offers distributed synchronization.  The documentation isn't great, but what there is makes it look an interesting product - checkout the recipes for ideas on how to use Zookeeper.
It is lower-level than you'd probably want and it does require additional deployment as it recommends dedicated servers.
You can model different locking strategies and it does offer a solution for a lock holder dying (ephemeral nodes).

A: Teracotta, including the Open Source edition, has distributed locking semantics by using either synchronized or the java.util.concurrent.ReentrantReadWriteLock - the latter apparently fitting your requirements.

Update
Since the question now added the requirement of 'mixing' with GigaSpaces, I'm going to say don't mix them. It's just going to add more complexity to your technological stack, and the effort of:

*

*integrating, in terms of both code and infrastructure;

*managing synchronisation between them;

*learning/tuning/debugging Teracotta.

will be better spent creating or implementing a locking solution based on GigaSpaces.

A: Oracle Coherence, which is very stable and mature, includes mutual exclusion support:
  cache.lock(key, -1);
    try {
      // .. add your critical code here
    } finally {
      cache.unlock(key);
    }

Locks survive server failures, rolling re-starts, etc.
For the sake of full disclosure, I work at Oracle. The opinions and views expressed in this post are my own, and do not necessarily reflect the opinions or views of my employer.