text:
Q: How to get data from two tables but with where clause on the second (FOREIGN KEY) table? [LINQ] I have two tables, like this:

I want to select the Table2 where the city is "DDD" but also I want to include the Table1. The expected output would be like this:

I'm working with EF Core Web API using LINQ. I've tried some solutions like this:
public async Task<IEnumerable<Rha>> GetSubRHAByAssign(string assign)
        {
            var result = await _db.Rhas.Select(x => new { Rha = x, Things = x.SubRhas.Where(p=> p.Assign == assign) }).AsNoTracking().ToListAsync();
            return result;
        }

But it gives me an error: Unable to cast object of type 'System.Collections.Generic.List`1[<>f__AnonymousType11`2[GesitAPI.Models.Rha,System.Collections.Generic.IEnumerable`1[GesitAPI.Models.SubRha]]]' to type 'System.Collections.Generic.IList`1[GesitAPI.Models.Rha]'.
I'm using an interface like this:
Task<IEnumerable<Rha>> GetSubRHAByAssign(string assign);

Also, as you can see my real problem is different from the example. Here I have two tables: RHA and SubRHA. The main problem is still the same, I want to get SubRHA based on Assign but I want to include RHA too. RHA is the main table, SubRHA is the table with foreign key from RHA table.
I've tried to use JOIN, but still gives me same error. Any idea?

A: try to modify your select as following
var result = await _db.Rhas.Include("SubRhas").Where(x=>x.SubRhas.Assign.Contains(assign)).ToListAsync();

A: I have found my own solution. I use this query:
var result = await _db.Rhas.Include(c => c.SubRhas.Where(o => o.Assign == assign))
                                       .ThenInclude(o => o.SubRhaevidences)
                                       .Where(x => x.SubRhas.Any())
                                       .AsNoTracking()
                                       .ToListAsync();

So it will get SubRhas with condition, but my problem is even though I have put the where condition inside SubRhas, the query still return another data that has no relation to SubRhas. That's why I add another condition on the first table to get the data where SubRhas is not empty.


text:
Q: Google Drive API with files.get migrating to HTTP "webViewLink" - how to bypass 100mb virus page? Google released this blog post which says:

If you authorize download requests to the Drive API using the access
token in a query parameter, you will need to migrate your requests to
authenticate using an HTTP header instead. Starting January 1, 2020,
download calls to files.get, revisions.get and files.export endpoints
which authenticate using the access token in the query parameter will
no longer be supported, which means you'll need to update your
authentication method.

and then says:

For file downloads, redirect to the webContentLink which will instruct
the browser to download the content. If the application wants to
display the file to the user, they can simply redirect to the
alternateLink in v2 or webViewLink in v3.

however if we use webContentLink then we will hit the 100mb virus page mentioned here.
I can see that the migration has been delayed, however sooner or later this will happen, and we want to future-proof the application.
How will we be able to download content without hitting the 100mb virus limit, after this change is implemented?

A:
If you authorize download requests to the Drive API using the access token in a query parameter, you will need to migrate your requests to authenticate using an HTTP header instead.

Example query param:
GET https://www.googleapis.com/drive/v3/files/[FILEID]?access_token=[YOUR_ACCESS_TOKEN] HTTP/1.1
Accept: application/json

Example requests header:
GET https://www.googleapis.com/drive/v3/files/[FILEID] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json

Assuming that you can do the http header option then you should not have any issues with the download as mentioned.  The issues with download only come into play if you cant add the authorization header.   In which case i think you would need to go with option number two and export the files directly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set div outerwidth using css I wonder if there is way to set outerwidth of a div using css to ignore padding and borders.
When I set a div to be 50% width, padding and border will be added to the width. How can I solve that without javascript or jQuery.outerWidth() ?
Don't want to use an extra element

A: Nest another div inside yours, and apply the paddings/borders to the nested one:

  ....

Unfortunately, there is no purely CSS way to achieve that (or at least I'm not aware of one).

A:
I'm wonder if there is way to set outerwidth of a div using css to ignore padding and borders.

You can use box-sizing: border-box to make padding and border be counted inside width:
div {
    box-sizing: border-box;
}

See: http://jsfiddle.net/thirtydot/6xx3h/
Browser support: http://caniuse.com/css3-boxsizing
The spec: http://www.w3.org/TR/css3-ui/#box-sizing

A: I am assuming you don't want to add more elements and answer your question slightly differently.

*

*The browser, not the style-sheet, determines the actual size of relative measurements such as em and %.

*There is no common/standard mechanism to feed calculated data from the browser's internal layout engine back into a stylesheet (this could be a dangerous looping problem).

Truly, the only way to do this is to:

*

*Use fixed width sizes and add pixel calculations into your style.

*Use JavaScript or related framework to achieve the results.

A: I would simply add a div inside that div if possible.

   //Content

.outerwidth { width: 50%; }
.inner { padding: 20px; }

A: you could split the 50% value assigned to the width as this:
width: 46%;

margin: 0 1%; // 0 top/bottom and 1% each for left and right

padding: 0 1%; // same as above

you can recalculate the percentages to suit your needs, as long as the total is 50% you should be fine.
I would avoid using js to fix small cosmetic issues as this would not work with js off and would add extra workload to your client's browser - think of mobile and you will see why performance counts!


text:
Q: NameError in PostsController#index I have used 4 important gems
gem 'activeadmin'
gem 'devise'
gem 'cancancan', '~> 2.0'
gem 'friendly_id', '~> 5.2.4'

I have 2 main Controller "User" and "Post" and registered in active_admin(rails generate active_admin:resource User and rails generate active_admin:resource Post).I have used cancancan for the authorization.
I have defined the ability in
ability.rb
    if user.admin?
        can :manage, :all
    else
        can :read, Posts
    end

ApplicationController.rb
class ApplicationController < ActionController::Base
    protect_from_forgery

  rescue_from CanCan::AccessDenied do |exception|
    respond_to do |format|
      format.json { head :forbidden, content_type: 'text/html' }
      format.html { redirect_to main_app.root_url, notice: exception.message }
      format.js   { head :forbidden, content_type: 'text/html' }
    end
  end
    def current_ability
      @current_ability ||= AccountAbility.new(current_admin_user)
    end
end

schema.rb
ActiveRecord::Schema.define(version: 2019_02_14_200911) do

  create_table "active_admin_comments", force: :cascade do |t|
    t.string "namespace"
    t.text "body"
    t.string "resource_type"
    t.integer "resource_id"
    t.string "author_type"
    t.integer "author_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id"
    t.index ["namespace"], name: "index_active_admin_comments_on_namespace"
    t.index ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id"
  end

  create_table "admin_users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "admin", default: true
    t.index ["email"], name: "index_admin_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true
  end

  create_table "categories", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "published_at"
    t.integer "user_id"
    t.integer "category_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.index ["category_id"], name: "index_posts_on_category_id"
    t.index ["slug"], name: "index_posts_on_slug", unique: true
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.boolean "admin", default: false
    t.index ["slug"], name: "index_users_on_slug", unique: true
  end

end

Goal
My goal is: 1. Only Admin can post,add user, add category basically manage all.
2. guest User can only read.
So I used cancancan gem to do authorization. But I am getting error:
uninitialized constant ApplicationController::AccountAbility
Extracted source (around line #12):
  end
    def current_ability
      @current_ability ||= AccountAbility.new(current_admin_user)
    end
end

And I have uploaded on git if you need any further information.
It will be great if you can help me. Thanks in advance.

A: The NameError is because your model is named Ability, not AccountAbility, so change your current_ability method to:
def current_ability
  @current_ability ||= Ability.new(current_admin_user)
end


text:
Q: The failure of product lemma for Sacks forcing I am reading Jörg Brendle's Bogota note, and the author claimed that Sacks forcing with countable support product does not satisfy a product lemma. Especially, he mentioned that if $\mathbb{S}_I$, $|I|$-many countable support product of Sacks forcing $\mathbb{S}$, adds $|I|$ Sacks reals $\langle s_i\mid i\in I\rangle$ and $i\neq j$, then $s_j$ is not $\mathbb{S}$-generic over $V[s_i]$.
Let me take $I=2$ for simplicity. One subtle point of the claim is that $\mathbb{S}$ need not be absolute between $V$ and $V[s_0]$. In fact, the product lemma for general forcing shows that $s_1$ would be $\mathbb{S}^V$-generic over $V[s_0]$. Hence I think the author intends to claim that $s_1$ is not $\mathbb{S}^{V[s_0]}$-generic over $V[s_0]$.
However, $\mathbb{S}^V\neq\mathbb{S}^{V[s_0]}$ does not automatically mean $s_1$ is not $\mathbb{S}^{V[s_0]}$-generic over $V[s_0]$. My question is:

How to prove $s_1$ is not $\mathbb{S}^{V[s_0]}$-generic over $V[s_0]$?

I am new at Sacks forcing, so I have no idea how to start. I would appreciate your help!

A: The point is that in the two-step iteration $s_1$ codes $s_0$ over the ground model in the sense that there is a Borel function $f \colon 2^\omega \to 2^\omega$ in $V$ so that $f(s_1) = s_0$. This can't happen in the product (for example $s_1$ is not a minimal real over $V$).
I don't know if there is a simple way to see this but I will sketch how I would prove it (if you want me to add details I can do that).
Lemma 1. Sacks forcing has the continuous reading of names, i.e. whenever $\dot y$ is an $\mathbb{S}$-name for an element of an arbitrary Polish space $X$ and $p \in \mathbb{S}$, then there is $q \leq p$ and a continuous function $g \colon [q] \to X$ so that $q \Vdash g(\dot s_0) = \dot y$.
This is usually formulated with $X = \omega^\omega$ but it doesn't make a difference since every Polish space is the continuous image of $\omega^\omega$. Also $[q]$ is the set of branches through $q$ and $\dot s_0$ is a name for the Sacks real that is added by $\mathbb{S}$.
Now a condition in the two-step iteration is a pair $(p,\dot q)$ where $p$ is a perfect tree and $\dot q$ is a $\mathbb{S}$-name for a perfect tree. Thus $\dot q$ is a name for an element of the Polish space $X$ of perfect trees and we find $p' \leq p$, $g \colon [p'] \to X$ interpreting $\dot q$, in the sense that $p' \Vdash g(\dot s_0) = \dot q$.
Now consider the following lemma.
Lemma 2. There is a continuous function $g' \colon [p'] \to X$ so that for every $x \in [p']$, $$g'(x) \subseteq g(x)$$ and for every $x\neq y \in [p']$, $$[g'(x)] \cap [g'(y)] = \emptyset.$$
Now we can define a name $\dot q'$ so that $p' \Vdash \dot q' = g'(\dot s_0)$. The point is that now we can read off $s_0$ from $s_1$. Define $f(x) = y$ if $y \in [p']$ and $x \in [g'(y)]$, and else $f(x) = 0$. Then $f$ is a Borel function in $V$ and $f(s_1) = s_0$.


text:
Q: TypeScript - A function that returns a portion of the input I'm new to Typescript and I want to write a function that returns the object it receives but with less info.
Let's say I have a Type like that:

type movie = {id: number, title:string, url:string, rating:number}

so I need a function that will receive an array of movies and return it only with id and title.
so if the input is:

[{id:1, title:Wonder Woman, url: www, rating:5},{id:2, title: Super
  Man, url:www2, rating:7}]

I need the output to be like that:

[{id:1, title:Wonder Woman},{id:2, title: Super Man}]

Is there an easy way to do that?

A: You can signal to TS that you're working with part of a type (called a Partial) by using Partial<...>
type Movie = { id: string | number, name: string, url: string }

const movies: Movie[] = [
  { id: 1, name: "Movie A", url: "http://www.google.com" },
  { id: 2, name: "Movie B", url: "http://www.google.com" }
]

function stripUrl ({ id, name }: Movie): Partial<Movie> {
  return { id, name }
}

const mMovies = movies.map(stripUrl)


text:
Q: how get value select tag Example problem http://plnkr.co/edit/nqgujfj7msKoJ4Tm3Tlz?p=preview
The universal loade xls files
steps:

*

*load xls file

*set select value according to col data and again load

Why , on second step function changeSelect return undefined, or how on second step get value all select's user-selected!?

A: Short answer: You are asking for $scope.myOpt from a scope that is an ancestor of the scope that actually contains myOpt.
Long answer: This code:

    ...

            <select ng-change="changeSelect();" ng-model="myOpt" ng-options="..."></select>

Creates the following scope hierarchy:
$rootScope
    MainCtrl scope <- myOpt is read here
        1st ng-repeat scope
            2nd ng-repeat scope <- myOpt is set here

According to JS prototypical inheritance, the ancestor scope cannot see the variable.
For your case I'd suggest passing myOpt to the changeSelect():
<select ng-change="changeSelect(myOpt)" ng-model="myOpt" ng-options="..."></select>

And:
$scope.changeSelect = function(x) {
    console.log(x); // or whatever
};


text:
Q: Calculating with JSON array data Stuck once again today, but i am trying to calculate with specific values from a JSON array. I can't seem to isolate the appropriate data. Can someone help me with this?
This is my JSON response:
[{"employee":[{"firstname":"Harry","birthdate":"1965-10-05","age":50}]},{"employee":[{"firstname":"Pete","birthdate":"1985-10-09","age":30}]}]

I'd like to get all the ages and add them for further use (for example average age). Help would be appreciated :)

A: Here is a working example for you:
var jsonData = [{"employee":[{"firstname":"Harry","birthdate":"1965-10-05","age":50}]},{"employee":[{"firstname":"Pete","birthdate":"1985-10-09","age":30}]}];

var sumOfAges = 0;
for(var i = 0; i<jsonData.length; i++){
    sumOfAges += jsonData[i]["employee"][0].age;
}
console.log(sumOfAges);
var averageAge = sumOfAges / jsonData.length;
console.log(averageAge);

you can find the fiddle here:
http://jsfiddle.net/La9rzh8t/1/

A: Using Array#reduce and JSON#parse we can quite easily sum all ages of each employee in your data.
Here is a JSFiddle which uses the below function:
function sumAllAges(data) {
    return data.reduce(function(total, obj) {
        total += obj.employee[0].age;
        return total;
    }, 0);
}


text:
Q: Vue 3: How to combine multiple ref How to combine multiple ref value in one:
        const variable1 = ref(false);
        const variable2 = ref('');
        const variable3 = ref(false);
        const variable4 = ref(false);
        const variable5 = ref(false);
        const variable6 = ref(false);

A: Have you checked reactive (ref. https://vuejs.org/guide/essentials/reactivity-fundamentals.html#declaring-reactive-state)?
const myReactiveVar = reactive({
       variable1 : false,
       variable2 : '',
       variable3 : false,
       variable4 : false,
       variable5 : false,
       variable6 : false,
});

changing any field trigger your watchers or computed values

A: You can use an object instead:
// Creation
const myValues = ref({
  someVar: true,
  otherValue: false
})

// In code somewhere
myValues.value.someVar = false

Instead you could also use reactive. Replacing the object isn't possibel then though.


text:
Q: Concatenate unwantedly applies max character width I am trying to print some mixed text and variables, all on one line. c() unwantedly forces all character fields to be the width of the largest field, i.e. 12 chars in this case. How to just get simple concatenation?
> print(c('Splitting col',i,'x<', xsplitval),quote=FALSE)
[1] Splitting col 9             x<            6.7

(I already checked all the SO questions, and all the R documentation, on print, options, format, and R mailing-lists, and Google, etc.)

A: You probably want to use paste:
i <- 9
xsplitval <- 6.7

paste('Splitting col',i,'x<', xsplitval, sep="")
[1] "Splitting col9x<6.7"

A: Another option is to use the sprintf function, which allows some number formatting:
i <- 9
xsplitval <- 6.7
sprintf("Splitting col %i, x<%3.1f", i, xsplitval)

A: I suggest the concatenate and print function, cat, for this purpose.  Another option is message, which sends the output to stderr.
> i <- 9
> xsplitval <- 6.7
> cat('Splitting col ',i,' x<', xsplitval, '\n', sep="")
Splitting col 9 x<6.7
> message('Splitting col ',i,' x<', xsplitval, sep="")
Splitting col 9 x<6.7

c is the function for combining values into a vector; it lines up the result into equally spaced columns to make looking at resulting vector easier.
> c('Splitting col ',i,' x<', xsplitval)
[1] "Splitting col " "9"              " x<"            "6.7"

paste concatenates character vectors together, and sprintf is like the C function, but both return character vectors, which are output (by default) with quotes and with numbers giving the index that each line of output starts with, so you may want to wrap them in cat or message.
> s1 <- paste('Splitting col ',i,' x<', xsplitval, sep=""); s1
[1] "Splitting col 9 x<6.7"
> cat(s1,'\n')
Splitting col 9 x<6.7

> s2 <- sprintf("Splitting col %i, x<%3.1f", i, xsplitval); s2
[1] "Splitting col 9, x<6.7"
> cat(s2,'\n')
Splitting col 9, x<6.7


text:
Q: Uncle Bob's Clean Architecture - Dealing with anemic interactors, tiering, and front-end MVVM Background
In Uncle Bob's Clean Architecture, use case interactors are responsible for the orchestration of business objects to accomplish some user goal.
As an easy example, an e-commerce application might have a use case to purchase items in a shopping cart: the interactor receives a request (DTO) to make a purchase, then the interactor might query various output ports (gateways) for instance to check inventory/availability, check to see if a payment can be made, and if so, persist a change to the inventory service, ending with a response (another DTO) indicating the success/failure of the interaction (the user-interface layers then presents this information to the user).
In trying to apply the principles of Clean Architecture to my applications, I continually run into the question of whether the use case interactor and gateways should be implemented on a front-end, back-end, or both. Consider the scenario for a mobile phone app that communicates with a web app - in a scenario like this, I've tended to notice that implementing use case interactors in the front-end lead them to be very anemic. That is, they only relay requests from the user-interface (typically a function call made on a view-model) to an output port (gateway interface). The gateway is good as it provides some level of abstraction about how communication with the back-end occurs (HTTP, sockets, IPC, RPC, etc), a detail that Uncle Bob stresses to be kept open for as long as possible. But I question the value of a use case interactor that merely relays requests - after all, why shouldn't a view-model depend directly on the output port? This is especially the case when the critical business rules must guarded by executing on an external device (e.g. web server, hardware, etc.) to prevent bad or unauthorized requests.
My typical attempt usually ends up as below. The output port provides a separation from the specific mechanism for sending a request. The only problem is that the use case interactor seems very anemic as mentioned since it merely relays a request to the gateway because the interesting business logic occurs on the external device or web app.

Consequently, I'm wondering if I should go with the following approach instead, but I'm not sure what the advantages/disadvantages of removing the use case interactor - it seems improper to depend from one adapter directly to another another adapter (albeit via an abstraction).

Now, in this circumstance, I do not care how external server, hardware, or web app are implemented so long as I obey it's API contract.
Though, supposing I was responsible for implementing the external application, is this where the use case interactor starts to be useful as now I have critical business rules and user flows that require orchestration?
My current conclusion is that it would seem that in a front-end/back-end system, the front-end would only be interested in use case interactors insofar-as the interesting business rules occur only within that tier (i.e. the front-end). If there are interesting business rules that cannot be fully executed in the front-end, perhaps due to security/authorization requirements, then we'll have to move that use-case interactor to the back-end tier instead and can simply have a view-model depend directly on the output port as in the second diagram.
Question
Does anyone have an expert opinion regarding tiering, MVVM, and Clean Architecture who can show me where I might be going astray? I'm hoping to understand:

*

*Is it useful (perhaps for maintainability reasons) in having use case interactors that only relay to a gateway (because the sophisticated business logic occurs on a different tier).

*What harms, if any, are there in depending directly from a view-model (an entry-point adapter) to an exit-point adapter via some output port interface?

A: A mobile e-commerce app that talks to a web service is unlikely to have much business logic in the app itself. In this case, it would be overkill to apply clean architecture independently to the app. Rather, you could consider the app to be the outermost layer of your overall architecture, which talks to the web service, which in turn talks to the interactors that contain the real business logic.
All you need in the app is the MVVM portion. The "model" is likely just the DTOs returned by the web service, and the view-model can handle presentation logic and interactions with the web service gateway.

A: I have never tried to strictly apply Clean Architecture, nor do I think Uncle Bob intended it as a strict rule book. Don't write code that you don't need yet.
In the case your use case would have no logic on its own, I would just leave it out, like you described. This doesn't feel like a violation of any Clean Architecture. You could see it like you Output port and Input port become the same and your interactor just fizzles away.
If your future requirements change, you can always create an interactor that implements the existing interface both as input and output port.
E.g.: You might have a view to subscribe to a newsletter entering an email address. You there is an API call to make that request and the backend will check the validity of the email and return either success or why it failed (maybe there was no "@" in the string, or the provider is blacklisted).
Your interface is just a method "set_password" taking a string, return null or an error string.
As a future requirement you want the validation to be client-side for simple validations. So you create an interactor that knows the api-controller and implements "set_password" by implementing the syntax check and return an error message on failure and delegate to the api-controller on success.
In any case, you want to make sure that the methods making the web API calls are not doing much more, because making web API calls is hard to test. (See humble object pattern).


text:
Q: Salesforce android SDK ...forcedroid is not recognized I am new to the salesforce android sdk.I am trying to create a hybrid app , i have installed forcedroid package ,jdk 1.7 ,ant1.9.3,node.js,salesforce mobile sdk but I'm getting error like "forcedroid is not recognised as a internal or external comand,operable program or batch file" in the command prompt .Please help me

A: forcedroid is not added in your path. Usually if you install using npm, it will be added automatically. Please add it to path environment variable.

A: When you install forcedroid via npm it is set on the path variables of your system; Windows in my example. But for me it didn't!
Here is what I fixed it:
Tldr; By adding it manually to path variables.
Typically forcedroid or any repo is installed inside the npm directory wherever it is located.
default location for Windows is:
C:\Users\YOUR_USER_NAME\AppData\Roaming\npm\forcedroid

Here forcedroid is the file name.
So go to your Environment Variables and under 'Path' (where you typically setup all your cmd paths), You add a new one
C:\Users\YOUR_USER_NAME\AppData\Roaming\npm

NOTICE: the path only till the \npm directory. Should now work!


text:
Q: How to shift logo to the extreme right using github-flavored-markdown? I am writing GitHub wiki for my project. There is something like:
[![Join the chat](https://something.svg)](https://some-link)

I want to shift this logo to the extreme right.
Initially I was wrapping this in <p align="right"> </p> and it's working. But after some update from Github side, it's not working now.

A: If you're using Bootstrap for Styling your CSS you can use the class pull-right and it will achieve this.
Maybe put your p element in a div and apply the pull right to your div


text:
Q: can't install i386 packages on Ubuntu server 20.04 I am using the version Ubuntu 20.04.4 LTS (GNU/Linux 5.13.0-1027-oracle aarch64) trying to add i386.
I was wanting to install a program called byond, and this program runs only with a 32-bit package.
I followed this step by step from them: Updated guide to running BYOND (DreamDaemon) on Debian/Ubuntu based distros
I Have tried to install it via the command:
sudo dpkg --add-architecture i386

And:
sudo apt update

And I get the error
Hit:2 http://ports.ubuntu.com/ubuntu-ports focal-security InRelease
Hit:3 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates InRelease
Hit:4 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports InRelease
Ign:5 http://ports.ubuntu.com/ubuntu-ports focal-security/main i386 Packages
Ign:6 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/main i386 Packages
Ign:7 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/restricted i386 Packages
Ign:8 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/universe i386 Packages
Ign:9 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/multiverse i386 Packages
Ign:10 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/main i386 Packages
Ign:11 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/restricted i386 Packages
Ign:12 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/universe i386 Packages
Ign:13 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/multiverse i386 Packages
Ign:14 http://ports.ubuntu.com/ubuntu-ports focal-security/restricted i386 Packages
Ign:15 http://ports.ubuntu.com/ubuntu-ports focal-security/universe i386 Packages
Ign:16 http://ports.ubuntu.com/ubuntu-ports focal-security/multiverse i386 Packages
Ign:5 http://ports.ubuntu.com/ubuntu-ports focal-security/main i386 Packages
Ign:14 http://ports.ubuntu.com/ubuntu-ports focal-security/restricted i386 Packages
Ign:15 http://ports.ubuntu.com/ubuntu-ports focal-security/universe i386 Packages
Ign:16 http://ports.ubuntu.com/ubuntu-ports focal-security/multiverse i386 Packages
Ign:5 http://ports.ubuntu.com/ubuntu-ports focal-security/main i386 Packages
Ign:14 http://ports.ubuntu.com/ubuntu-ports focal-security/restricted i386 Packages
Ign:17 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/main i386 Packages
Ign:18 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/universe i386 Packages
Ign:6 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/main i386 Packages
Ign:7 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/restricted i386 Packages
Ign:8 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/universe i386 Packages
Ign:9 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/multiverse i386 Packages
Ign:10 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/main i386 Packages
Ign:11 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/restricted i386 Packages
Ign:12 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/universe i386 Packages
Ign:15 http://ports.ubuntu.com/ubuntu-ports focal-security/universe i386 Packages
Ign:16 http://ports.ubuntu.com/ubuntu-ports focal-security/multiverse i386 Packages
Ign:5 http://ports.ubuntu.com/ubuntu-ports focal-security/main i386 Packages
Ign:13 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/multiverse i386 Packages
Ign:17 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/main i386 Packages
Ign:18 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/universe i386 Packages
Ign:14 http://ports.ubuntu.com/ubuntu-ports focal-security/restricted i386 Packages
Ign:15 http://ports.ubuntu.com/ubuntu-ports focal-security/universe i386 Packages
Ign:16 http://ports.ubuntu.com/ubuntu-ports focal-security/multiverse i386 Packages
Ign:6 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/main i386 Packages
Ign:7 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/restricted i386 Packages
Ign:8 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/universe i386 Packages
Ign:9 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/multiverse i386 Packages
Ign:10 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/main i386 Packages
Ign:11 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/restricted i386 Packages
Ign:12 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/universe i386 Packages
Ign:13 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/multiverse i386 Packages
Ign:17 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/main i386 Packages
Ign:5 http://ports.ubuntu.com/ubuntu-ports focal-security/main i386 Packages
Ign:14 http://ports.ubuntu.com/ubuntu-ports focal-security/restricted i386 Packages
Ign:15 http://ports.ubuntu.com/ubuntu-ports focal-security/universe i386 Packages
Ign:18 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/universe i386 Packages
Ign:6 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/main i386 Packages
Ign:7 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/restricted i386 Packages
Ign:8 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/universe i386 Packages
Ign:9 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/multiverse i386 Packages
Ign:10 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/main i386 Packages
Ign:11 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/restricted i386 Packages
Ign:12 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/universe i386 Packages
Ign:13 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/multiverse i386 Packages
Ign:16 http://ports.ubuntu.com/ubuntu-ports focal-security/multiverse i386 Packages
Err:5 http://ports.ubuntu.com/ubuntu-ports focal-security/main i386 Packages
  404  Not Found [IP: 185.125.190.39 80]
Ign:14 http://ports.ubuntu.com/ubuntu-ports focal-security/restricted i386 Packages
Ign:17 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/main i386 Packages
Ign:18 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/universe i386 Packages
Ign:6 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/main i386 Packages
Ign:7 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/restricted i386 Packages
Ign:8 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/universe i386 Packages
Ign:9 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/multiverse i386 Packages
Ign:15 http://ports.ubuntu.com/ubuntu-ports focal-security/universe i386 Packages
Ign:16 http://ports.ubuntu.com/ubuntu-ports focal-security/multiverse i386 Packages
Ign:10 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/main i386 Packages
Ign:11 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/restricted i386 Packages
Ign:12 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/universe i386 Packages
Ign:13 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/multiverse i386 Packages
Ign:17 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/main i386 Packages
Ign:18 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/universe i386 Packages
Err:6 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/main i386 Packages
  404  Not Found [IP: 185.125.190.39 80]
Ign:7 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/restricted i386 Packages
Ign:8 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/universe i386 Packages
Ign:9 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal/multiverse i386 Packages
Err:10 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/main i386 Packages
  404  Not Found [IP: 185.125.190.39 80]
Ign:11 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/restricted i386 Packages
Ign:12 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/universe i386 Packages
Ign:13 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-updates/multiverse i386 Packages
Err:17 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/main i386 Packages
  404  Not Found [IP: 185.125.190.39 80]
Ign:18 http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports focal-backports/universe i386 Packages
Reading package lists... Done
E: Failed to fetch http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports/dists/focal/main/binary-i386/Packages  404  Not Found [IP: 185.125.190.39 80]
E: Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/focal-security/main/binary-i386/Packages  404  Not Found [IP: 185.125.190.39 80]
E: Failed to fetch http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports/dists/focal-updates/main/binary-i386/Packages  404  Not Found [IP: 185.125.190.39 80]
E: Failed to fetch http://sa-saopaulo-1-ad-1.clouds.ports.ubuntu.com/ubuntu-ports/dists/focal-backports/main/binary-i386/Packages  404  Not Found [IP: 185.125.190.39 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.

Then this
sudo apt install libstdc++6:i386

And in the end
Building dependency tree
Reading state information... Done
E: Unable to locate package libstdc++6:i386

How can I resolve this error? Is it something related to the (/etc/apt/sources.list) file ? Or about the processor architecture (Arm-based processor) ?
Thank you in advance for your attention.


text:
Q: Video Compression in Android I want to compress and decompress a video File in Android.I tried with zipping and unzipping it and it was successful :)
But what I need is compress and decompress it like how it happens in Watsapp. Also, zipping could only compress the video by 2.5% .
I also tried looking for FFmpeg in android, but I was not able to get though it
Could anyone provide and good reference/help/CODE EXAMPLE where a .mp4 file could be easily compressed ?
Thanks !!

A: Whats app does it using MediaCodec. It doesnt do as quickly as it looks. The preview is a calculated preview which is shown to user. The actual compression takes place while sending. Try compressing 200 Mb file and see the file size in videos/sent folder. You will get an idea when and how much time it takes to compress.


text:
Q: Experimental evidence for parallel universes/multiverses My idea of physics is that it is a collection of mathematical laws relating observables. And that one can perform alot of mathematical derivations on these laws to produce new laws between observables. My question is how does one translate a mathematical equation into 'there exist other universes like ours'?
How does one derive that there exist other universes, what phenomena do they explain?
Which observables suggest other universes?

A: There is no evidence that another universe exists. There are various physical theories that allow for the existence of parallel universes, and as far as I know there are no widely accepted theories that prohibit their existence outright, so strictly speaking, I suppose it's possible. But it's unlikely that we would ever be able to detect them if they do exist.

A: There are many different versions of the multiple-universe idea in physics. Scientific American has a nice (skeptical) article on the topic this month, "Does the multiverse really exist?" by the well known relativist G.F.R. Ellis. Some of the possibilities discussed include the many-worlds interpretation of quantum mechanics, chaotic inflation, the string-theory landscape, and cyclic models such as ekpyrotic models and Penrose's conformal cyclic cosmology. You can find information about specific ideas from this list on Wikipedia, etc. There is not likely to be a generic answer to your question that will encompass all of these cases.
One thing you have to watch out for is that it is not necessarily easy to come up with a suitable definition of "universe." For example, you could say that it means the set of all events that a given observer O, who is assumed to be immortal, could in principle observe, subject to general relativity's restriction to the propagation of information at no more than the speed of light. The accelerating expansion of the universe implies that there is a cosmological horizon beyond which O can never see, so by this definition of "universe," O's universe has a boundary. With this definition, if you have two observers, O and P, there can be events that are in O's universe and also in P's universe, but other events that are in one but not the other. You could say, "Oh no, I don't like that definition, it's goofy. I want the whole universe to be included, not just the part that a particular observer can ever observe." But then you have the same philosophical problem as in other incarnations of the multiple-universe idea, which is that you have to talk about things that can never be observed, even in principle.
I will give one example where it seems to me to be valuable to discuss multiple universes.
History offers several examples of cosmological models that were wrong, and that with hindsight we can say should have been considered implausible at the time, because they required fine tuning. Newton envisioned an infinite, homogeneous cosmos so that despite the force of gravitational attraction, the force on any particle would cancel out by symmetry, thereby allowing the universe to exist forever. Einstein had a similar model in which the cosmoogical constant was exactly sufficient to balance gravitational attraction and keep the universe static. Even before Hubble discovered cosmological expansion, there was a problem with both of these models, because they were unstable, and required fine-tuning. In the Newton model, any deviation from homogeneity, no matter how small, causes a snowball effect. Similarly, Einstein's cosmological constant had to be perfectly tuned, or else there would be a vicious cycle of accelerating expansion or collapse. The lesson from history seems to be that we should not believe in cosmological models that require fine-tuning.
But the current consensus model of cosmology has multiple fine-tuning problems. There is a flatness problem, and also an entropy problem. Inflation is supposed to fix the former, but inflation has a lot of problems, one of which is that inflation is in some sense improbable. To define the notion of its probability, you pretty much have to start talking about the set of all possible universes, and asking how many of them have inflation that could lead to a universe such as ours. This is similar to the Einstein fine-tuning problem, where you basically want to object because the perfectly tuned value of the cosmological constant seems low in probability. You can't talk about probability unless you have a sample space, and here the sample space is some kind of multiverse. If you refuse to talk about the multiverse, then you've closed off an avenue of argument that has been historically fruitful.

A: There are speculative theories that suggest areas of cold/hot patches in the cosmic microwave background are 'bruises' caused by collisions of expanding bubble universe... These are not 'parallel' in your sense though, more they are just different regions of space-time.

A: The Many Worlds Interpretation of quantum mechanics is just a possible interpretation of the laws of quantum mechanics; it is not a consequence. It is a strong philosophical position if

*

*you believe that quantum mechanics in principle applies to everything, including
macroscopic objects (albeit it becomes practically impossible to calculate anything, so you default to classical mechanics as an effective theory);

*you are sufficiently a philiosophical materialist to believe that your consciousness is nothing more than a physical process;

*you connect these two ideas and recognise that your conscious observations are in principle continually being entangled with everything around you, including observations which arise from very obvious quantum mechanical processes, such as which-way experiments.

However, these assumptions are not uncontrovertial (which for #2 is, historically at least, somewhat of an understatement), and there is vigorous philosophical debate around both these ideas, and other foundational questions, such as whether the Many Worlds Interpretation could explain why the Born rule is the one which governs frequencies of the outcomes of repeated experiments.


text:
Q: fmdb insert date gives "invalid date" I'm trying to use fmdb in my latest ios-project and it worked great so far. But now i'm trying to do inserts with an NSDate as a parameter and it ends up being stored as an invalid date in my sqlite database.
I have tried multiple solutions, but nothing seems to work. What am i doing wrong?
[database executeUpdate:@"CREATE TABLE IF NOT EXISTS inspection (ID INTEGER PRIMARY KEY, result TEXT, date_of_inspection DATE, restaurant_id INTEGER"];

NSDate *today=[NSDate date];
[database executeUpdate:@"insert into inspection(id,result,date_of_inspection,restaurant_id) values(?,?,?,?)",[inspection valueForKey:@"id"], result, today, [restaurant valueForKey:@"id"],nil];

The database is populated and everything works fine except for the *#%! date... :)
What is wrong?

A: SQLite doesn't have a date format, so that FMDB expects the date fields to be stored as floats/real numbers:
else if ([obj isKindOfClass:[NSDate class]]) {
    sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
}

So try making your table with that format.

A: Try this:
[database executeUpdate:@"CREATE TABLE IF NOT EXISTS inspection(ID INTEGER PRIMARY KEY, result TEXT, date_of_inspection REAL, restaurant_id INTEGER"];

NSDate *today=[NSDate date];
[database executeUpdate:@"insert into inspection(id,result,date_of_inspection,restaurant_id) values(?,?,?,?)",[inspection valueForKey:@"id"], result, [today timeIntervalSince1970], [restaurant valueForKey:@"id"],nil];

SQLite does not support the DATE data type (http://www.sqlite.org/datatype3.html).
You must store it as a REAL data type. timeIntervalSince1970 returns the data type NSTimeInterval, which is a double (
https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html).


text:
Q: How do i avoid writing these 3 lines twice? considering the following extensions in SwiftUI:
extension Text{
   func applyBG() -> some View {
      self
         .padding(20)
         .background(Color(hue: 0, saturation: 0, brightness: 0.22).cornerRadius(10))
         .foregroundColor(.white)
   }
}

extension TextField{
   func applyBG() -> some View {
      self
         .padding(20)
         .background(Color(hue: 0, saturation: 0, brightness: 0.22).cornerRadius(10))
         .foregroundColor(.white)
   }
}

I feel like i could write this better, avoiding repetition.
I could probably solve this with something like:
extension View{
   func applyBG() -> some View {
      self
         .padding(20)
         .background(Color(hue: 0, saturation: 0, brightness: 0.22).cornerRadius(10))
         .foregroundColor(.white)
   }
}

But i do not want all my views to be able to call this method.
I just want Text and Textfield to have such method. I tried with protocol and associatedType, but i was not able to write these lines just one time in order to achieve clean code.
Any hint or pseudo code on how i could achieve the DRY ?

A: Use a Protocol like so:
import SwiftUI

protocol BGApplyable where Self: View {}

extension BGApplyable {
  func applyBG() -> some View {
    self
     .padding(20)
     .background(Color(hue: 0, saturation: 0, brightness: 0.22).cornerRadius(10))
     .foregroundColor(.white)
  }
}

Decide which views can adopt the protocol:
extension TextField: BGApplyable {}
extension Text: BGApplyable {}

Then use it:
var body: some View {
  VStack {
    Text("Foo")
      .applyBG()
    TextField("Hello", text: .constant("World!"))
      .applyBG()
  }
}

A: You can declare the function on a protocol, just change its return type from some View to AnyView, then make Text and TextField conform to this protocol.
protocol TextView: View {
    func applyBackground() -> AnyView
}

extension TextView {
    func applyBackground() -> AnyView {
        AnyView(padding(20)
                    .background(Color(hue: 0, saturation: 0, brightness: 0.22).cornerRadius(10))
                    .foregroundColor(.white)
        )
    }
}

extension Text: TextView {}
extension TextField: TextView {}

Text("text").applyBackground()


text:
Q: How to convert a String of format yyyymmdd to LocalDate in JodaTime I have a String in the form "20140518". How to convert it into LocalDate object
I tried this
this.todayDate = new LocalDate(val);
System.out.println(todayDate.toString("yyyy-mm-dd"))

When I try dumping this to standard output it dumps like 20140518-junk-junk. That it dumps a garbage string . I thought it would dump like 2014-05-18.

A: Use MM that represents Month instead of mm that represents minutes.
Use LocalDate.parse() instead of new LocalDate() to construct the LocalDate object.
DateTimeFormatter format = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd");
LocalDate lDate = org.joda.time.LocalDate.parse("20140518", format);
System.out.println(lDate);

output:
2014-05-18

org.joda.time.LocalDate#toString() be default uses yyyy-MM-dd pattern.
You don't need to use todayDate.toString("yyyy-MM-dd").


text:
Q: Creating a Tk Tcl entry that acts like a label I want to create labels that the text in them can be selected for copy/paste. To do this I tried to use entries that are read-only. But I can't seem to initialize the text value in them. The labels are generated inside a loop and the number of labels and their content is unknown. The code to produce the labels is:
proc test_labels {} {
    toplevel .labels
    # Main Frame
    frame       .labels.main_frame -relief "groove" -bd 2
    pack        .labels.main_frame

    set r 1

    foreach t [list banana apple grapes orange lemon peach] {
        set lbl  [label .labels.main_frame.lbl_$r   -text "fruit $r:"]
        set lbl2 [label .labels.main_frame.val_$r -text $t]

        grid $lbl  -row $r -column 1 -sticky nse
        grid $lbl2 -row $r -column 2 -sticky nsw

        incr r
    }
    set ok_btn [button .labels.main_frame.ok_b -text "OK" -command {prop_menu_ok_button}]
    grid $ok_btn -row [expr $r+2] -column 1 -columnspan 2 -sticky nsew

    grab release .
    grab set .labels
    center_the_toplevel .labels
    bind .labels <Key-Return> {test_labels_ok_button}
}

And it creates the fallowing window:

Then I try to replace the line set lbl2 [label .labels.main_frame.val_$r -text $t] with the lines:
eval "set text_val_$r $t"
eval "set lbl2 [entry .labels.main_frame.val_$r -relief flat -state readonly -textvar text_val_$r]"

But this only creates empty lines:

How can I put default values to entry widgets?
Related to the question How to make the text in a Tk label selectable?

A: These lines are almost certainly not what you want! (If you're using eval, you should always ask whether it's really necessary; from 8.5 onwards, the likely answer is "it's not necessary".)
eval "set text_val_$r $t"
eval "set lbl2 [entry   .labels.main_frame.val_$r -relief flat -state readonly -textvar \$\{text_var_$r\}]"

The key problem — apart from the use of eval — is that the -textvariable option takes the name of a variable. Let's fix that by using an array to hold the values:
set text_val($r) $t
set lbl2 [entry .labels.main_frame.val_$r -relief flat -state readonly \
        -textvariable text_val($r)]

Also, be aware that the text_val array needs to be global (or in a namespace, if you fully  qualify the name when giving it to the -textvariable option). This is because it is accessed from places which are outside the scope of any procedure.
Of course, it turns out that if we are keeping values constant then we can avoid using a variable at all and just insert the value manually.
set lbl2 [entry .labels.main_frame.val_$r -relief flat]
$lbl2 insert 0 $t
$lbl2 configure -state readonly

If you're never changing the value, that will work fine.


text:
Q: Get all the version of a row in a SharePoint list I am trying to read all the versions of a list on a site and store them. I would like to do it for the whole row rather than column by column (or item by item). I have seen this here https://sharepoint.stackexchange.com/questions/137360/how-to-get-all-major-versions-of-list-or-library-item-using-c
but cannot get my head around it as none of the oList, items, and listItem does not have "Version" attribute. I have enabled versioning for my list in the SharePoint. Below is my code in C#.
using (ClientContext clientContext = new ClientContext("https://domain.sharepoint.com/sites/mysite"))
{
    SecureString passWord = new SecureString();
    foreach (char c in "mypass".ToCharArray()) passWord.AppendChar(c);
    clientContext.Credentials = new SharePointOnlineCredentials("email@domain", passWord);
    Web web = clientContext.Web;

    clientContext.Load(web);
    clientContext.ExecuteQuery();
    CamlQuery query = new CamlQuery();
    query.ViewXml = @"";
    SP.List oList = clientContext.Web.Lists.GetByTitle("listname");

    clientContext.Load(oList);
    clientContext.ExecuteQuery();

    SP.ListItemCollection items = oList.GetItems(query);

    clientContext.Load(items);
    clientContext.ExecuteQuery();
    foreach (ListItem listItem in items)
    {

        foreach (KeyValuePair<string, object> dictitem in listItem.FieldValues)
        {
        //Read this key, value and save them in a datatable
        }
    }

}

buy using v16 of SharePoint SDK and items.Versions, I get the following error:
 Error  CS1061  'ListItemCollection' does not contain a definition
 for 'Versions' and no accessible extension method 'Versions' accepting a
  first argument of type 'ListItemCollection' could be found (are you missing
  a using directive or an assembly reference?)

A: You could use the ListItem.Versions Property to get all versions of an item:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.client.listitem.versions
foreach (ListItem listItem in items)
{
        ListItemVersionCollection itemversioncollection = listItem.Versions;
        clientContext.Load(itemversioncollection);
        clientContext.ExecuteQuery();
}

Also, use the latest version of SharePoint SDK if possible.

A: Commenting here, since this answer popped up when I searched for a solution. There is already a solution in another stackoverflow answer. That answer works also for SP13.
It is based on using:
"https://<server>/<site>/_layouts/versions.aspx?list={litsID}&ID=<itemID>"

Please see SharePoint 2013 - Get SPListItem versions via REST


text:
Q: Сделать чтобы содержимое textView в item в recyclerView отображалось только после клика на itemView - как? recyclerView заполняется объектами,объект имеет 2 стринга: name and status. Соответственно для
отображения есть два textView: mName и mStatus (см. onBindViewHolder внизу). Мне нужно, чтобы
изначально было прописано только mName, а только после клика на itemView появлялся текст mStatus.
Я запустил onClickListener из адаптера в Activity, но не понимаю как это там прописать (см. Activity).
In Activity:
//variables and methods etc..
myAdapter = new MyAdapter(new MyAdapter.MyDiff());
myCardStackLayoutManager = new CardStackLayoutManager(this, this);
myCardStackView.setLayoutManager(myCardStackLayoutManager);
myCardStackView.setAdapter(myAdapter);
myAdapter.setOnCardListener(new MyAdapter.OnCardListener() {
    @Override
    public void onCardClick(int position) {
        // WHAT TO TYPE HERE?
    }
});

In Adapter:
public class MyAdapter extends ListAdapter<Person, MyAdapter.MyViewHolder> {
    private OnCardListener mOnCardListener;
    public interface OnCardListener {
        void onCardClick(int position);
    }
    public void setOnCardListener(OnCardListener onCardListener) {
        mOnCardListener = onCardListener;
    }
// variables and methods...
public static class MyViewHolder extends CardStackView.ViewHolder /*implements View.OnClickListener*/ { //NEWWW
        public TextView mName;
        public TextView mStatus;
        public MyViewHolder(@NonNull View itemView, OnCardListener onCardListener) {   //NEWWW
            super(itemView);
            mName = itemView.findViewById(R.id.tv_name);
            mStatus = itemView.findViewById(R.id.tv_status);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onCardListener != null) {
                        int position = getAdapterPosition();
                        if (position != CardStackView.NO_POSITION) {
                            onCardListener.onCardClick(position);
                        }
                    }
                }
            });
        }
    }
// other methods
@Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Person currentPerson = getItem(position);
        holder.mName.setText(currentPerson.getName());
        holder.mStatus.setText(currentPerson.getStatus()); //это изначально не должно отображаться, а только после клика.
    }

A: *

*Добавьте в Person переменную, хранящую состояние видимости статуса.

*По клику на ячейку списка - меняйте состояние на противоположное. И уведомлейте адаптер об изменениях.

*В onBindViewHolder в зависимости от значения переменной из п.1 меняйте видимость нужного текстового поля.


text:
Q: Find if any set is covered by member sets [Please let me know if this maps to a known problem]
I have n sets of varying sizes. Each element in a set is unique. And each element can occur atmost in two different sets.
I want to perform an operation on these sets but avoid duplicates or missing any element.
Problem: Find out which all of these n sets should be removed because they are covered by other sets.
E.g. [a,b,c]; [a]; [b]. Remove [a], [b] since both are covered by the first one.
E.g. [a,b,c]; [a]; [b]; [c,d]. Remove [a,b,c] since all three elements are covered by remaining sets.
Note: here [a],[b] alone is not valid answer since 'c' is being duplicated. Similarly [a],[b],[c,d] is not valid answer since 'd' will be missed if removed.

A: I think that this is the Exact Cover problem. The last constraint—that each element is in at most two sets—doesn't seem to me to fundamentally change the problem (although I could easily be wrong about this). The Wikipedia web page contains a good summary of various algorithmic approaches. The algorithm of choice seems to be Dancing Links.

A: I think this is a case of a 2-sat problem that can be solved in linear time using a method based on Tarjan's algorithm.

*

*Make a variable Ai for each set i.  Ai is true if and only if set i is to be included.

*For each element that appears in a single set add a clause that Ai=1

*For each element that appears in 2 sets i and j, add clauses (Ai && ~Aj) || (~Ai && Aj).  These clauses meant that exactly one of Ai and Aj must appear.

You can now solve this using a standard 2-sat algorithm to find whether this is impossible to achieve or a satisfying assignment if it is possible.
For a case with V sets and N elements you will have V variables and up to 2N clauses, so Tarjan's algorithm will have complexity O(V+2N).

A: Since an element in a set can appear in no more than two sets, then there are fairly straightforward connections between sets, which can be shown as a graph, the two examples are shown below. One example uses red lines to represent edges and the other uses black lines to represent edges.

The above shows that the sets can be divided into three groups.

*

*Sets where all elements appear twice. These sets could potentially be removed and/or the sets that contain those elements could be removed.

*Sets where one or more elements appear twice. The elements that appear twice could potentially link to sets that could be removed.

*Sets where no elements appear twice. These sets can be ignored.

It's not really clear what happens if all of the sets are in either group 1 or group 3. However there seems to be a fairly simple criterion that allows for quickly removing sets, and the psudocode looks like so:
for each set in group2:
    for each element that appears twice in that set:
        if the other set that contains that element is in group1:
            remove the other set

The performance is then linear in the number of elements.

A: I tried to find which sets to include rather than remove. Something like this?
(1) List of elements and the indexes of sets they are in
(2) Prime the answer list with indexes of sets that have elements that appear only in them
(3) Comb the map from (1) and if an element's set-index is not in the answer list, add to the answer the index of the smallest set that element is in.
Haskell code:
import Data.List (nub, minimumBy, intersect)

sets = [["a","b","c","e"],["a","b","d"],["a","c","e"]]
lengths = map length sets

--List elements and the indexes of sets they are in

mapped = foldr map [] (nub . concat $ sets) where
  map a b = comb (a,[]) sets 0 : b
  comb result   []     _     = result
  comb (a,list) (x:xs) index | elem a x  = comb (a,index:list) xs (index + 1)
                             | otherwise = comb (a,list) xs (index + 1)

--List indexes of sets that have elements that appear only in them

haveUnique = map (head . snd)
           . filter (\(element,list) -> null . drop 1 $ list)
           $ mapped

--Comb the map and if an element's set-index is not in the answer list,
--add to the answer the index of the smallest set that element is in.

answer = foldr comb haveUnique mapped where
  comb (a,list) b
    | not . null . intersect list $ b = b
    | otherwise                       =
        minimumBy (\setIndexA setIndexB ->
                    compare (lengths!!setIndexA) (lengths!!setIndexB)) list : b

OUTPUT:
*Main> sets
[["a","b","c","e"],["a","b","d"],["a","c","e"]]

*Main> mapped
[("a",[2,1,0]),("b",[1,0]),("c",[2,0]),("e",[2,0]),("d",[1])]

*Main> haveUnique
[1]

*Main> answer
[2,1]


text:
Q: Getting an error trying to add a new Web Service reference to my c# project in VS2019 I am not able to add new Web Service references to my C# project. Visual Studio 2019 fails to open the dialog to add the Web Service.
When I launch the Add Connected Services option in my .NET 4.7.2 C# project, and try to add a SOAP Web Service reference using the "Microsoft WCF Web Service Reference Provider", instead of showing the dialog to add the Web Service reference, it shows an alert message with the following error:
The connected services component 'Microsoft WCF Web Service Reference Provider' failed: The project reference specification 'Microsoft.Csharp' does not have a file path.
BTW, even though this is a regular .NET framework assembly project, I am using the new .NET SDK style project file. Also, it works fine for the first web service reference that I add. Any further attempts to add more web service references cause this error!
Does anyone know whey this would happen?

A: I am using VS2019 16.7.5 currently and hit this issue, not being very familiar with all the ins and outs. I hit a number of sites in finding out about this issue - and one that said it had been an earlier bug in version 16.1.
After Adding the Reference - which in my case is to an existing project with an existing service reference.
I added a Controller - for a Web API 2 call -  it started giving me the errors.
I have to write a REST API to call a SOAP service that is blocked by a firewall.
I commented out the method - it would build - uncomment just the signature and it would not.
I found by commenting out the signature (no methods in the class) I could compile - and if I then used the right click of the servicereference and clicked on the Update Service Reference - it generated the reference - and I could browse to it in the Object Browser.
Now the controller needs a reference to that Service and then it will have Objects and Methods from the Reference to develop the correct service objects to do the work
Update: I had to add Another service and again it would not show up - and this time the solution was a little different - I added the service with the WSDL, and did the above and when it would not show - I did an Update Service Reference - still no show - but this time I closed Visual Studio and reopened it - and there was my object browser definition. Then I created My Controller and could use the objects.

A: I had to put the solution's name plus a dot in front of it. For example:
Solution is called 'Solution1'
Service reference is called 'Service1'
then call it with Solution1.Service1.... instead of only Service1...


text:
Q: NLTK function from string variable isn't callable I have a list of related function names which I want to iterate thru, calling the function held in the variable.  But no matter how I try it, I get:   "TypeError: 'TweetTokenizer' object is not callable"
Following the solution in Calling a function of a module from a string with the function's name in Python (of which it is suggested this question is a duplicate), finds the functions in the nltk module and assigns them. But my resulting "tok_alg" function is still failing as not callable.  Any advice on why this is happening would be appreciated.
#!/usr/bin/env python

import nltk
import os
testTxt="I'll have a Bloomin' Onion."
Tokenizers = [ 'Tweet', 'MWE', 'TreebankWord' ]

for tokenizer in Tokenizers:
    tokz = tokenizer + 'Tokenizer'

    tok_alg = getattr(nltk, tokz)()
    result = tok_alg(testTxt)

    print(result)

Listing the functions does work, viz
for tokenizer in [ TweetTokenizer(), MWETokenizer() ]:
    result = tokenizer.tokenize(testTxt)

But the suggested conversion of str variables via getattr() is not working for NLTK.  While this is elegant and practical, I need the string variables for other purposes.  Surely there is some way to vivify these into a function call.  What am I  missing?


text:
Q: How to add multiple validation parameters in a marshmallow schema I have the following schema in one of my class models:
class SocialMediaSchema(Schema):
    facebook_profile_url = fields.String(required=False, validate=validate.Length(0, 71, 'Facebook username is too long.')

Aside from validating the length, I also want to be able to make sure that facebook_profile_url is never equal to the string "http://www.facebook.com/".

A: You can pass a list as the validate parameter:
class SocialMediaSchema(Schema):
    facebook_profile_url = fields.String(required=False, validate=[
        validate.Length(0, 71, 'Facebook username is too long.'),
        lambda x: x != "http://www.facebook.com/"
    ])

From the documentation:

validate (callable) – Validator or collection of validators that are called during deserialization.


text:
Q: Cannot read property 'touched' of undefined Why am i getting this error Cannot read property touched of undefined?
Why is it not able to read formName.controls['email'].touched but its able to read formName.get('custDetails').touched
<form [formGroup]="formName">
<fieldset formGroupName="custdetails">

        Email
        <input type="text" class="form-control"
                formControlName="email" name="email" required />

</fieldset>

</form>

When we use formName.get('custdetails.email').touched ... i get the below erro

TypeError: _this.subscribe is not a function
      at eval (http://localhost:3000/node_modules/rxjs/operator/toPromise.js:68:15)
      at new ZoneAwarePromise (http://localhost:3000/node_modules/zone.js/dist/zone.js:551:29)
      at Object.toPromise (http://localhost:3000/node_modules/rxjs/operator/toPromise.js:66:12)
      at _convertToPromise (http://localhost:3000/node_modules/@angular/forms//bundles/forms.umd.js:541:73)
      at Array.map (native)
      at FormControl.eval [as asyncValidator] (http://localhost:3000/node_modules/@angular/forms//bundles/forms.umd.js:530:101)
      at FormControl.AbstractControl._runAsyncValidator (http://localhost:3000/node_modules/@angular/forms//bundles/forms.umd.js:2670:62)
      at FormControl.AbstractControl.updateValueAndValidity (http://localhost:3000/node_modules/@angular/forms//bundles/forms.umd.js:2630:26)
      at FormControl.setValue (http://localhost:3000/node_modules/@angular/forms//bundles/forms.umd.js:2988:18)
      at DefaultValueAccessor.eval [as onChange] (http://localhost:3000/node_modules/@angular/forms//bundles/forms.umd.js:1658:21)
      at Wrapper_DefaultValueAccessor.handleEvent (/InternalFormsSharedModule/DefaultValueAccessor/wrapper.ngfactory.js:29:34)
      at CompiledTemplate.proxyViewClass.View_ReactiveFormComponentFive0.handleEvent_36
  (/AppModule/ReactiveFormComponentFive/component.ngfactory.js:717:45)
      at CompiledTemplate.proxyViewClass.eval (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12397:41)
      at HTMLInputElement.eval (http://localhost:3000/node_modules/@angular/platform-browser//bundles/platform-browser.umd.js:3224:57)
      at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:275:35)

Below is how my form is construct:
ngOnInit() {
    this.formName = this.fb.group({
       name: ["", [Validators.required]],
       custdetails: this.fb.group({
            email: ["", Validators.required, ValidationHelper.emailValidator],
            confirm: ["", Validators.required]
        }, {
            validator: ValidationHelper.emailMatcher
        })

    })
}

And my email validator:
static emailValidator = (control: AbstractControl) : {[key: string]: boolean} =>{
        // RFC 2822 compliant regex
        if (control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) {
            return null;
        } else {
            return { 'invalidEmailAddress': true };
        }
    }

A: The complete path to the field is:
formName.get('custdetails.email')

So you need to access:
formName.get('custdetails.email').touched

Also, you have an error in the form model. When multiple validators are applied to the same field, they should be wrapped inside an array:
// Replace that:
email: ["", Validators.required, ValidationHelper.emailValidator]
// With this:
// Notice the additional [ ] around the validators
email: ["", [Validators.required, ValidationHelper.emailValidator]]

By passing the two validators as separate parameters, Angular interprets the second validator emailValidator as an async validator and it tries to subscribe to it. Hence the error message "_this.subscribe is not a function".

A: add in TS file
get email(){ return this.formName.get('custdetails.email'); }
add validation in html
*ngIf="email.touched"


text:
Q: C++ Create a new array off of some values of std::vector? I know what I am doing here is horribly wrong:
void Example( void )
{
    // DECLARE LOCAL VARIABLES
    ::UINT nPosition = 5;
    ::UINT nLength = 5;
    std::vector< ::UINT >vn_VectorA;
    ::UINT *an_ArrayA = new ::UINT[ nLength ];

    // FILL vn_VectorA WITH DECIMAL VALUE OF "HelloWorld!!!"
    // I KNOW THIS IS AN UGLY WAY OF DOING IT. BUT FOR DEMONSTRATION PURPOSES,
    // I CAN CARELESS.
    vn_VectorA.push_back( 72 );     // H
    vn_VectorA.push_back( 101 );    // e
    vn_VectorA.push_back( 108 );    // l
    vn_VectorA.push_back( 108 );    // l
    vn_VectorA.push_back( 111 );    // o
    vn_VectorA.push_back( 87 );     // W
    vn_VectorA.push_back( 111 );    // o
    vn_VectorA.push_back( 114 );    // r
    vn_VectorA.push_back( 108 );    // l
    vn_VectorA.push_back( 100 );    // d
    vn_VectorA.push_back( 33 );     // !
    vn_VectorA.push_back( 33 );     // !
    vn_VectorA.push_back( 33 );     // !

    // Copy the desire values of vn_VectorA to an_ArrayA
    for( ::UINT nCopyIndex = nPosition, nArrayAIndex = 0; nArrayAIndex != nLength; nArrayAIndex ++, nCopyIndex ++ )
    {
        an_ArrayA[ nArrayAIndex ] = vn_VectorA[ nCopyIndex ];
#ifdef DEBUG
        std::cout << an_ArrayA[ nArrayAIndex ] << ' ';
#endif // DEBUG
    }
};

This is what I use to copy certain values of a std::vector:
    // Copy the desire values of vn_VectorA to an_ArrayA
    for( ::UINT nCopyIndex = nPosition, nArrayAIndex = 0; nArrayAIndex != nLength; nArrayAIndex ++, nCopyIndex ++ )
    {
        an_ArrayA[ nArrayAIndex ] = vn_VectorA[ nCopyIndex ];
#ifdef DEBUG
        std::cout << an_ArrayA[ nArrayAIndex ] << ' ';
#endif // DEBUG
    }

After running the code, it should print:
87 111 114 108 100
So, how should I be doing this???

A: Why not use std::copy?
std::copy(&*vn_Vector.begin() + nPosition, &*vn_Vector.end(), an_ArrayA);

Note that I'm only dereferencing vn_Vector.end() so it has the same type as &*vn_Vector.begin() + nPosition.

A: This answer is mainly based on @john.pavan's answer.
#pragma region DOCUMENTATION ON: STD_COPY_VECTOR_TO_ARRAY
//////////////////////////////////////////////////////////////////////////////
// MACRO: STD_COPY_VECTOR_TO_ARRAY( Vector, Position, Length, Array )       //
//                                                                          //
// DESCRIPTION:                                                             //
// A defined macro that is created to copy selected values of std::vector   //
// an array. This defined macro takes 4 arguments.                          //
//                                                                          //
// ARGUMENTS:                                                               //
// Vector - The std::vector that contains the values that will be copied.   //
// Position - Position of the first value from Vector to be copied.         //
// Note: The first value of Position is marked by the value of 0 and not 1. //
// Length - Amount of values to be copied from Vector.                      //
// Array - The Array that the values will be copied to.                     //
//                                                                          //
// TIPS:                                                                    //
// #1 - To copy all values within Vector, set the value of Position to 0    //
// and set the value of Length to the size of Vector (std::vector::size).   //
//////////////////////////////////////////////////////////////////////////////
#pragma endregion
#define STD_COPY_VECTOR_TO_ARRAY( Vector, Position, Length, Array )         \
                                  std::copy( Vector.begin( ) + Position,    \
                                  Vector.begin( ) + Position + Length ,     \
                                  Array )


text:
Q: Drag image within it's parent border? I have created image viewer control, that provide zoom in/out the image, and when the image zoomed and be larger than it's viewer (you can't see all the image) I provided the ability to drag the image (like Windows Photo Viewer) using "TranslateTransform" but I wanna the image to stop dragging when it's border (left or right or left or down) is appeared, I have done some calculations of the width and height of the fourth sides and it's work fine but when you speedy drag the image it stop after it's border pass it's container border, and the distance increased by greater drag speed. For example: open an image in "Windows Photo Viewer" and zoomed it then drag it it's stop exactly when you reach it's border".
So I wanna the image to stop exactly when it's border appeared regardless of drag speed?
Appreciated your Helps,
Best Regards.

A: This looks like problem with your code. Can you just apply range check when you compute parameters for translate transform to avoid moving picture outside the region?

A: This is my code I have Image(name: imgView), insode grid(name: grdImage), I wanna the image(zoomed image) to move with mouse move in inside the Grid, and when it's borders reach the border of grid to stop, exactly like "Windows Photo Viewer". FYI: Im zoomed the image using the scaleTransform:
Private Sub imgView_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    _IsMouseCapture = True
    imgView.CaptureMouse()
    Dim tt = DirectCast(DirectCast(imgView.RenderTransform, TransformGroup).Children.First(Function(tr) TypeOf tr Is TranslateTransform), TranslateTransform)
    start = e.GetPosition(grdImage)
    origin = New Point(tt.X, tt.Y)
End Sub

Private Sub imgView_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    _IsMouseCapture = False
    imgView.ReleaseMouseCapture()
End Sub

 Private Sub imgView_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
    If (Not _IsMouseCapture) Then
        Return
    End If

    Dim tt = DirectCast(DirectCast(imgView.RenderTransform, TransformGroup).Children.First(Function(tr) TypeOf tr Is TranslateTransform), TranslateTransform)
    Dim vx As Double = start.X - e.GetSafePosition(grdImage).X
    Dim vy As Double = start.Y - e.GetSafePosition(grdImage).Y
    tt.Y = origin.Y - vy
    tt.X = origin.X - vx
End Sub`


text:
Q: How can I rebuild an old library to work on a recent Visual Studio? I've been trying to learn Directx recently and started to read "Introduction to 3D Game Programming With DirectX 11" by Frank Luna.
The book was being pretty interesting until I've encountered problems that I couldn't solve by my own. One of the first steps of the book is to compile one program that Frank Luna wrote, which is a Box drawn in DirectX, since the code he wrote in the book uses the Microsoft DirectX SDK(June 2010) I had to install it too, because apparently DirectX is now included in the Windows Kits which Windows 8 uses and, no longer supports D3DX(which is used in the book).
The error that I encountered was this one:
Error   2   error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1800' in Camera.obj

I found the answer by Luna himself (I think) here, but I don't know how to do that.
Luna says:
You need to rebuild the Effects11 library with VS12. This forum post has more details:
viewtopic.php?f=4&t=295
Dreamcore asks:
How do I rebuild it? The post only said that I must rebuild it but now HOW TO rebuild it.
Luna answers:
In the June 2010 SDK there is the Effects11 project:
E:\DXSDKJune10\Samples\C++\Effects11
Open the solution and build in debug mode (naming the output Effects11d.lib) and in release mode (naming the output Effects11.lib). Then copy these two .lib to the book's common directory.
Can someone tell me how do I build in debug and release mode and getting an output using visual studio 2013 professional? Effects11_2010.sln doesn't even compile neither in debug or release. It says unable to start the program.
Thanks

A: You found the answer, you're just missing one step.  Ignore the message saying that VS can't start the program.  You're building a binary library, not an executable.  That's why it can't start the program, because you didn't build one.
The newly compiled Effects11.lib file will be in the DEBUG folder.  Just rename it to add the 'd' at the end of the filename and save it to the COMMON folder in the LUNA sample files.  You should probably rename the original file in the COMMON folder first so that you can recover it, unless you have the original ZIP from the book disk.  Then recompile and the box example will work.  This is assuming that you've already used the VS2013 wizard to convert the solution's Platform Toolset from v100 (VS2010) to v120 (VS2012/VS2013).
Also, don't forget to comment out the entire contents of the HR macro in the Luna's D3DUtil.h file.  I don't know if it EVER worked, but it hasn't worked since DirectX9c in VS2010, and still doesn't work now using DirectX11 in VS2013.  Just find the HR definition and replace it with this:
#define HR(x){HRESULT hr = (x);}
    /*if(FAILED(hr))
    {
        //DXTrace(__FILE__, (DWORD)__LINE__, hr, L#x, true);
    }
}*/


text:
Q: What is the easiest way to get latitude and longitude? I'm working on a BlackBerry app that requires getting the phones current GPS coordinates. I've tried several surprisingly complex ways of acquiring the location that have not succeeded, but I can't believe there isn't a simpler way of doing it. Can anyone tell me what the simplest way of obtaining GPS coordinates on the BlackBerry is?

A: RIM has a GPS Sample Application.  And a quick Google for 'blackberry gps example' turns up this sample, among many others.


text:
Q: Receiver, that was created from IntentService, doesn't work I have Geofence IntentService. On GEOFENCE_ENTER I create broadcast receiver. But it doesn't get actions.
If I created it in MainActivity - all is good. But I don't need to.
I do not understand what happens when I create the receiver from the service.
    public class GeofenceTransitionsIntentService extends IntentService {

    ...

        @Override
        protected void onHandleIntent(Intent intent) {
           ...

           if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {

                //Create WiFi scan receiver
                WiFiScanReceiver wifiScan = new WiFiScanReceiver();
                registerReceiver(wifiScan, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

                //Scan
                WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                Boolean scanStarted = wm.startScan();
            }

        }

A: Calling registerReceiver() in onHandleIntent() will not work well. Your receiver will go away microseconds later, after onHandleIntent() returns and the service stops itself.
Either use a manifest-registered receiver, or use a regular Service instead of an IntentService, managing your own background thread and arranging to stopSelf() the service when you are done with it.

A: IntentService will be destroyed once onHandleIntent() finished.
You should use Service


text:
Q: I think it is in the number of arrays in the array and not all of them have data. Any help? This has been driving me nuts!!! I have taken an xml file and dumped the namespaces and have a great array but for the life of me can't figure out how to work with the json to get variable for:
{
    "ListMatchingProductsResponse": {
        "ListMatchingProductsResult": {
            "Products": {
                "Product": [
                    {
                        "Identifiers": {
                            "MarketplaceASIN": {
                                "MarketplaceId": "ATVPDKIKX0DER",
                                "ASIN": "B000WTLJIQ"
                            }
                        },
                        "AttributeSets": [],
                        "Relationships": {
                            "VariationParent": {
                                "Identifiers": {
                                    "MarketplaceASIN": {
                                        "MarketplaceId": "ATVPDKIKX0DER",
                                        "ASIN": "**B00FM1EXEQ**"
                                    }
                                }
                            }
                        },
                        "SalesRankings": {
                            "SalesRank": [
                                {
                                    "ProductCategoryId": "pet_products_display_on_website",
                                    "Rank": "115236"
                                },
                                {
                                    "ProductCategoryId": "**5769007011**",
                                    "Rank": "362"
                                }
                            ]
                        }
                    },
                    {
                        "Identifiers": {
                            "MarketplaceASIN": {
                                "MarketplaceId": "ATVPDKIKX0DER",
                                "ASIN": "B00NDY7666"
                            }
                        },
                        "AttributeSets": [],
                        "Relationships": [],
                        "SalesRankings": []
                    },
                    {
                        "Identifiers": {
                            "MarketplaceASIN": {
                                "MarketplaceId": "ATVPDKIKX0DER",
                                "ASIN": "B009YJ3JSI"
                            }
                        },
                        "AttributeSets": [],
                        "Relationships": {
                            "VariationParent": {
                                "Identifiers": {
                                    "MarketplaceASIN": {
                                        "MarketplaceId": "ATVPDKIKX0DER",
                                        "ASIN": "B00P3MYXHQ"
                                    }
                                }
                            }
                        },
                        "SalesRankings": {
                            "SalesRank": [
                                {
                                    "ProductCategoryId": "pet_products_display_on_website",
                                    "Rank": "180220"
                                },
                                {
                                    "ProductCategoryId": "3203999011",
                                    "Rank": "8108"
                                }
                            ]
                        }
                    },
                    {
                        "Identifiers": {
                            "MarketplaceASIN": {
                                "MarketplaceId": "ATVPDKIKX0DER",
                                "ASIN": "B00ARCFLFA"
                            }
                        },
                        "AttributeSets": [],
                        "Relationships": [],
                        "SalesRankings": {
                            "SalesRank": [
                                {
                                    "ProductCategoryId": "pet_products_display_on_website",
                                    "Rank": "297848"
                                },
                                {
                                    "ProductCategoryId": "5769009011",
                                    "Rank": "879"
                                }
                            ]
                        }
                    },
                    {
                        "Identifiers": {
                            "MarketplaceASIN": {
                                "MarketplaceId": "ATVPDKIKX0DER",
                                "ASIN": "B00DJAEX6U"
                            }
                        },
                        "AttributeSets": [],
                        "Relationships": {
                            "VariationParent": {
                                "Identifiers": {
                                    "MarketplaceASIN": {
                                        "MarketplaceId": "ATVPDKIKX0DER",
                                        "ASIN": "B0091TK10K"
                                    }
                                }
                            }
                        },
                        "SalesRankings": []
                    },
                    {
                        "Identifiers": {
                            "MarketplaceASIN": {
                                "MarketplaceId": "ATVPDKIKX0DER",
                                "ASIN": "B00FC7ALY6"
                            }
                        },
                        "AttributeSets": [],
                        "Relationships": [],
                        "SalesRankings": []
                    }
                ]
            }
        },
        "ResponseMetadata": {
            "RequestId": "9d9da767-ffc5-4eb3-ab95-8f9e91dc7af2"
        }
    }
}

A: use json_decode() and it will turn your json into an object.
$json = json_decode(<json_string));

A: Use json_decode() to return an array then use foreach loop
  $result = json_decode($yourJSON);

  foreach($result as $key => $val){
    //do something here
    echo 'Key: ' .$key . ' Value: ' . $val;
  }


text:
Q: select cell in collection view after edit an uitextfield I try to select first cell in collection view after edit an uitextfield.
in function func textFieldDidEndEditing(textField: UITextField) call function incandescenteCollection.selectItemAtIndexPath(NSIndexPath(forRow: 0 , inSection: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredHorizontally) where incandescenteCollection is IBOutlet to collectionview.@IBOutlet weak var incandescenteCollection: UICollectionView!
But not work. Any Idea?

A: Make sure your controller has the UITextFieldDelegate protocol and the text field in question's delegate is set self (the controller).
class ViewController: UIViewController, ..., UITextFieldDelegate {

    // MARK: Outlets

    @IBOutlet weak var incandescenteCollection: UICollectionView!
    @IBOutlet weak var textField: UITextField! {
        didSet {
            // If the text field is in your cell,
            // move this line to cellForItemAtIndexPath
            // as cell.textField.delegate = self
            textField.delegate = self
        }
    }

    ...

    // MARK: UITextFieldDelegate

    func textFieldDidEndEditing(textField: UITextField) {

        incandescenteCollection.selectItemAtIndexPath(
            NSIndexPath(forRow: 0 , inSection: 0),
            animated: true,
            scrollPosition: .CenteredHorizontally
        )
    }
}


text:
Q: Не могу обновить локальний репозиторий с помощью git pull Вчера работал в локальном репозитории на офисной машине. В конце рабочего дня запушил все коммиты на удаленный репозиторий. Проверил репо на GitHub - все изменения пришли.
Вечерком решил продолжить работу с дома. Склонировал данный репозиторий к себе на ноут и начал работать. В конце дня снова запушил все измененния на удаленный репо.
Сегодня на офисной машине хотел запулить все изменения в локальный репозиторий. Выполнил:
git pull

Увидел сообщение об ошибке:

По совету Git выполнил:
git pull udigital master

Получил следующее сообщение:

Попробовал другой вариант:
git branch --set-upstream-to=udigital/master master

Получил такое сообщение:

В итоге в локальном репозитории файлы не обновились. Как добавить изменения из удаленного репозитория и продолжить работать на локалке?

A: В моем случае помогли следующие команды:
rm .git/refs/remotes/origin/master
git fetch

А вот ссылка на ответ на англоязычном StackOverflow на котором этот вопрос был решен.


text:
Q: Method error while executing the Testng file I am a beginner to java. Kindly help me in the below code,
@Test(priority=1)
  public void signup(String emailvalue) {
  System.out.println("Page Title: " +driver.getTitle());

  driver.findElement(By.id("proprietorName")).sendKeys("Im Owner");

  driver.findElement(By.id("businessName")).sendKeys("Pharmacy By Selenium");

  driver.findElement(By.id("proprietorMobileNo")).sendKeys("1236547890");

  driver.findElement(By.id("website")).sendKeys("http://www.google.com");

  driver.findElement(By.id("businessUserEmail")).sendKeys("emailvalue");

  driver.findElement(By.id("businessUserPassword")).sendKeys("123456");

  driver.findElement(By.id("confirmpass")).sendKeys("123456");

  driver.findElement(By.xpath("//div[@class='col-md-12 mgbt-xs-10 mgtp-20']//div[@class='vd_checkbox']//label[@for='checkbox-2']")).click();

  driver.findElement(By.id("submit-register")).click();

  try
  {
      if(driver.findElement(By.xpath("//div[@class='alert alert-danger vd_hidden']")).isDisplayed())
      {
          driver.findElement(By.id("businessUserEmail")).clear();

          driver.findElement(By.id("businessUserEmail")).sendKeys("emailvalue");

          driver.findElement(By.id("submit-register")).click();
      }

  }
  catch(NoSuchElementException e)
  {
      System.out.println("Given inputs are accepted.");
  }

      switch(emailvalue)
      {

    case "0":
          emailvalue = "daniel@xxxx.in";
          break;

    case "1":
          emailvalue = "daniel1@xxxx.in";
          break;

    case "2":
          emailvalue = "daniel2@xxxx.in";
          break;

    case "3":
          emailvalue = "daniel3@xxxx.in";
          break;

    case "4":
          emailvalue = "daniel4@xxxx.in";
          break;

    case "5":
          emailvalue = "daniel5@xxxx.in";
          break;

      }

}
  }

When i execute the above code, i got the following error,
Method signup requires 1 parameters but 0 were supplied in the @Test annotation.
    at org.testng.internal.Parameters.checkParameterTypes(Parameters.java:198)
    at org.testng.internal.Parameters.createParameters(Parameters.java:134)
    at org.testng.internal.Parameters.createParameters(Parameters.java:373)
    at org.testng.internal.Parameters.handleParameters(Parameters.java:450)
    at org.testng.internal.Invoker.handleParameters(Invoker.java:1383)
    at org.testng.internal.Invoker.createParameters(Invoker.java:1075)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1180)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

A: You need to pass arguments to the test method. That could be done in multiple ways. Like using dataprovider classes or  running using testng.xml and passing as argument. You can createa a testng.xml like this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<suite allow-return-values="false" configfailurepolicy="skip" data-provider-thread-count="10" group-by-instances="false" junit="false" name="FullSuite" preserve-order="true" skipfailedinvocationcounts="false" thread-count="5" verbose="1">

   <test allow-return-values="false" group-by-instances="false" id="apiversion1" junit="false" name="TestExecutionWithAPIversion1" preserve-order="true" skipfailedinvocationcounts="false">
      <parameter name="emailvalue" value="0"/>
      <classes>
         <class name="com.test.scripts.yourclassnamewithcorrectpackage/>

      </classes>
   </test>
</suite>

and then modify your method to read the parameter you are passing
@Parameters({ "emailvalue" })
@Test(priority=1)
  public void signup(String emailvalue) {
  System.out.println("Page Title: " +driver.
....

}

And then run the file using testng.xml. You can right click go to runas - > run configurations - > Suite -> chose the testng.xml in your project. For more details read this


text:
Q: ApplyForce and ApplyLinearImpulse in Box2D is not working I am writing a 2D platformer game in Perl with SDL and Box2D,
the SetLinearVelocity() function is working well so I can moving my character to left or right. But when I want to make it jump using ApplyLinearImpulse(), it is not working, also the ApplyForce() is not working too. The character object just stay there.
my code :
if ($key_name=~/w/){
    $me->ApplyLinearImpulse(Box2D::b2Vec2->new(0,20.0), $me->GetWorldCenter());
    }

I also tried adding:
$world->step(1.0/60.0,10,10);

after it, but stil no response.
please help.

A: oh I found that it is because I should use GetPosition() rather then GetWorldCenter() and the force need to be much bigger to lift my object!