text:
Q: Which early game NPC is the better pack mule? In general when I play RPGs I tend to be a bit of a kleptomaniac and a bit of a pack rat.  So, of course Fallout 4's crafting system that leaves nothing to waste is enabling this behavior even further.
I have discovered that Dogmeat can carry a bunch of my junk, allowing me to range further and for longer, but is he the best choice?  Can Codsworth or Preston carry more?  I can find no number in the game enumerating their actual carry limit before it gets reached.

A: Basically Dogmeat is the best choice if you just want a pack mule, because he doesn't count for the Lone Wanderer perk. That means you can skill the perk and use Dogmeat, but still profit from the 50/100 additional carryweight which enables you to carry a lot more than you could with another follower.
Dogmeats own carryweight is 150 lbs, which is the same as codsworth and just a little bit less than npcs like preston garvey. Together with that perk on lvl 2, you can carry an additional 250 lbs. The only NPC which can outweigh that bonus is Strong, the super mutant, who can carry 270 lbs, but you lose the other advantages of the lone wanderer and only gain 20lbs more carryweight.


text:
Q: Rails form tag not going to custom delete route, going to standard delete route instead I am trying to delete a collection of items based upon checkboxes. I created a custom route. The destroy_multiple route.
  Rails.application.routes.draw do
  resources :projects do
    resources :lists, shallow: true do
      member do
        post :sort
      end
      resources :items, shallow: true
    end
  end

  resources :items do
    collection do
     delete :destroy_multiple, :as => :destroy_multiple
    end
  end
  resource :react
end

When I run rake routes I get this as a result
Prefix Verb   URI Pattern                               Controller#Action
             sort_list POST   /lists/:id/sort(.:format)                 lists#sort
            list_items GET    /lists/:list_id/items(.:format)           items#index
                       POST   /lists/:list_id/items(.:format)           items#create
         new_list_item GET    /lists/:list_id/items/new(.:format)       items#new
             edit_item GET    /items/:id/edit(.:format)                 items#edit
                  item GET    /items/:id(.:format)                      items#show
                       PATCH  /items/:id(.:format)                      items#update
                       PUT    /items/:id(.:format)                      items#update
                       DELETE /items/:id(.:format)                      items#destroy
         project_lists GET    /projects/:project_id/lists(.:format)     lists#index
                       POST   /projects/:project_id/lists(.:format)     lists#create
      new_project_list GET    /projects/:project_id/lists/new(.:format) lists#new
             edit_list GET    /lists/:id/edit(.:format)                 lists#edit
                  list GET    /lists/:id(.:format)                      lists#show
                       PATCH  /lists/:id(.:format)                      lists#update
                       PUT    /lists/:id(.:format)                      lists#update
                       DELETE /lists/:id(.:format)                      lists#destroy
              projects GET    /projects(.:format)                       projects#index
                       POST   /projects(.:format)                       projects#create
           new_project GET    /projects/new(.:format)                   projects#new
          edit_project GET    /projects/:id/edit(.:format)              projects#edit
               project GET    /projects/:id(.:format)                   projects#show
                       PATCH  /projects/:id(.:format)                   projects#update
                       PUT    /projects/:id(.:format)                   projects#update
                       DELETE /projects/:id(.:format)                   projects#destroy
destroy_multiple_items DELETE /items/destroy_multiple(.:format)         items#destroy_multiple
                 items GET    /items(.:format)                          items#index
                       POST   /items(.:format)                          items#create
              new_item GET    /items/new(.:format)                      items#new
                       GET    /items/:id/edit(.:format)                 items#edit
                       GET    /items/:id(.:format)                      items#show
                       PATCH  /items/:id(.:format)                      items#update
                       PUT    /items/:id(.:format)                      items#update
                       DELETE /items/:id(.:format)                      items#destroy
                 react POST   /react(.:format)                          reacts#create
             new_react GET    /react/new(.:format)                      reacts#new
            edit_react GET    /react/edit(.:format)                     reacts#edit
                       GET    /react(.:format)                          reacts#show
                       PATCH  /react(.:format)                          reacts#update
                       PUT    /react(.:format)                          reacts#update
                       DELETE /react(.:format)                          reacts#destroy

And my form tag looks like this..
<%= form_tag url_for(:controller => 'items', :action => 'destroy_multiple'), :method => 'delete' do %>

  <ul class="list-group sortable" data-update-url="<%= sort_list_path(list) %>">
    <%= render list.items %>

  <%= submit_tag("Delete Items") %>
<% end %>

I am not getting any errors but it is not going to the right controller action it ends up at just the destroy action for a singular item. Here is my controller.
class ItemsController < ApplicationController
  before_action :set_item, only: [:edit, :update]

  def create
    @list = List.find(params[:list_id])
    @item = @list.items.create params[:item].permit(:content)
  end

  def edit
  end

  def update
    @item.update_attributes(params[:item].permit(:content))
  end

  def destroy
    @item.destroy
  end

  def destroy_multiple

    debugger
  end

  private

  def set_item
    @item = Item.where(id: params[:id]).first!
  end

end

I just want the form submission to go to the custom destroy_multiple action. I appreciate any help. Thank You.

A: As per @JoshHumphrey my error was having multiple routes. My updated route file is
Rails.application.routes.draw do
  resources :projects do
    resources :lists, shallow: true do
      member do
        post :sort
      end
      resources :items, shallow: true do
        collection do
           delete :destroy_multiple, :as => :destroy_multiple
        end
      end
    end
  end

  resource :react
end

And I updated the form a bit to pass the list id down so here is the form
<%= form_tag(destroy_multiple_list_items_path(list_id: list.id),method: :delete,remote: true) do %>
  <ul class="list-group sortable" data-update-url="<%= sort_list_path(list) %>">
    <%= render list.items %>

  <%= submit_tag("Delete Selected",  :class => "btn btn-warning") %>
<% end %>

Everything else stayed the same! Thanks for the help Josh.

A: You can try to follow, at first you create route like original destroy action
resources :items do
 collection do
   #delete :destroy_multiple, :as => :destroy_multiple
   delete '/destroy_multiple/:id(.:format)' => 'items#destroy_multiple', constraints: { id: /.*/ }, as: :destroy_multiple
  end
end

Now run rake routes you get the something like this (not tested route but code is right now)
destroy_multiple_items DELETE /items/destroy_multiple/:id(.:format)         items#destroy_multiple

Now you can try to delete using checkbox
def destroy_multiple
   Item.where(id: params[:id]).destroy_all
   # redirect
end

Hope to help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как написать lambda функцию с условием которая проходит по строкам всего датафрейма? Например есть простенький датафрейм:
df = pd.DataFrame([[1,'Apple', True],[2,'Apple', False],[3,'Orange', False],[4,'Orange', True]],
         columns=['count','fruit','fresh'])

Мне нужно написать lambda функцию с условием описанным ниже и применить ее к датафрейму, чтобы получить новый столбец через apply:
lambda x: 1 if 2<=x.count<=3 and x.fruit=='Apple' or x.fresh==True else 0
df['new_col'] = df.apply(lambda...

A: Ну вам, вероятно, просто нужно указать axis. Только определитесь с приоритетом условий OR и AND:
df['new_col'] = df.apply(lambda x: 1 if (2<=x["count"]<=3)&
                         (x["fruit"]=="Apple")|
                         (x["fresh"]==True) else 0, axis=1)

df:
   count   fruit  fresh  new_col
0      1   Apple   True        1
1      2   Apple  False        1
2      3  Orange  False        0
3      4  Orange   True        1

A: при желании тут можно обойтись без лямбды:
df['new_col'] = ((df['count'].isin([2,3]))&(df['fruit']=='Apple')|df['fresh'])*1
print(df)
'''
   count   fruit  fresh  new_col
0      1   Apple   True        1
1      2   Apple  False        1
2      3  Orange  False        0
3      4  Orange   True        1


text:
Q: Measuring very small changes in resistor network using current source I am trying measure a very small change in resistance (approximately .400 Ohms), due to the the effects of connecting a large resistance in parallel with a network of smaller resistors essentially looking like this

The voltage drop across A and B however cannot exceed 0.5V, I consider using a AD8276 in the following configuration to create a constant current source. I got this design from http://www.analog.com/library/analogDialogue/archives/43-09/current_source.html figure 5 without the transitor.

My problem is that the difference in current through the load (in my case the first diagram) when the measured R is connected and not connected is 1.388mA and 1.3912mA respectively (approximately). To achieve these currents the range of Vref is extremely small, when R2 =1K the swing is 1.354926V and 1.35726V. The range grows as you increases R2 and R1 but Vref also increase.
I want to do this measurement in house and it will only ever be done in this configuration so I don't want to have to buy expensive equipment, I was hoping to be able to build a circuit to do this. do you think my original idea would work (AD8276 current source) I just need a method to control Vref, or do you think there is another method.
Thanks for the second pair of eyes.

A: Try this idea: -

5mA is generated by X1 and X5 - you'll need a stable voltage source where X6 is - it's referenced to the +5V to make life easier. If you are happy with your 5V rail stability it can just be a potential divider instead of the precision zener and R6 shown. X5 (AD8628) I used on a recent job but any 5V op-amp with decent offset voltage and inputs/outputs capable of getting near either rail will work. There are Plenty of P channel FETs that will do the job too - i picked this one because it has low Vgs(threshold) and there would be no-doubt it would work across the loads and power rails.
The AD627 is fairly standard and, for every ohm that R4 changes, the output (V out) alters 394 mV. The output offset is 2.5V (with a perfectly balanced bridge) but it could be set to 1V or if you had split supplies, 0V. Good luck.


text:
Q: HTML-signature renders differently I am making a new html signature for use in Outlook 2010. It looks fine in browsers and most email clients but in Outlook 2010 it renders a bit wrong. As you can see from the first screenshot from Chrome the text aligns to the right of the image, but in the second screen from Outlook it renders below the image. How do I fix this?
Chrome:
Chrome http://unihouse.no/images/sig_chrome.PNG
Outlook:
Outlook 2010 http://unihouse.no/images/sig_outlook2010.PNG
Ps. I paste the code directly into the Outlook Signature html file without using the inbuilt editor.

        Test Name, Unihouse Norge AS

        Storkundeansvarlig Østlandet

        e-post: test@test.no  | tlf: +47 123 45 567

        Besøksadresse: Tjuvholmen allé 3, 0252 Oslo

        Hovedkontor: Innherredsveien 103, 7043 Trondheim

A: You could use a table instead of floating divs. Try making a table with one row and 2 cells. Place the image in the first cell and the text in the second.
This should force them to be next to each other in any application.

        Test Name, Unihouse Norge AS

        Storkundeansvarlig Østlandet

        e-post: test@test.no  | tlf: +47 123 45 567

        Besøksadresse: Tjuvholmen allé 3, 0252 Oslo

        Hovedkontor: Innherredsveien 103, 7043 Trondheim

A: for HTML email, you HAVE to use <tables> to ensure uniformity. And then place the text and the image in adjacent  in the same
.
A helpful website


text:
Q: Example of Stirling Numbers of the First Kind I am trying to calculate the stirling numbers of the first kind. I am not very good in math and there is not a single example somewhere in the internet.
So I would really appreciate it if you could help me there.
The stirling number which I want to calculate is s1(4,2). I know the solution is 11.
How far I came:

A: You could use the rising factorial to find $\left[\begin{array}{c} 4 \\ 2 \end{array}\right]$. It goes as follows:
$$(x)^4 = x(x+1)(x+2)(x+3) = x^4 + 6x^3 + 11x^2 + 6x$$
$\left[\begin{array}{c} 4 \\ k \end{array}\right]$ is now the coefficient with $x^k$. Thus $\left[\begin{array}{c} 4 \\ 2 \end{array}\right]$ = 11.
For the recurrence relation with the unsigned Stirling numbers of the first kind, you would have:
$$\begin{align}
\left[\begin{array}{c} 4 \\ 2 \end{array}\right] & = 3\left[\begin{array}{c} 3 \\ 2 \end{array}\right] + \left[\begin{array}{c} 3 \\ 1 \end{array}\right]\\
& = 3\left(2\left[\begin{array}{c} 2 \\ 2 \end{array}\right] + \left[\begin{array}{c} 2 \\ 1 \end{array}\right]\right) + 2\left[\begin{array}{c} 2 \\ 1 \end{array}\right] + \left[\begin{array}{c} 2 \\ 0 \end{array}\right] = 6\left[\begin{array}{c} 2 \\ 2 \end{array}\right] + 5\left[\begin{array}{c} 2 \\ 1 \end{array}\right] + 0 \\
& = 6\left(\left[\begin{array}{c} 1 \\ 2 \end{array}\right] + \left[\begin{array}{c} 1 \\ 1 \end{array}\right]\right) + 5\left(\left[\begin{array}{c} 1 \\ 1 \end{array}\right] + \left[\begin{array}{c} 1 \\ 0 \end{array}\right]\right) = 6\left[\begin{array}{c} 1 \\ 2 \end{array}\right] + 11\left[\begin{array}{c} 1 \\ 1 \end{array}\right] + 0 \\
& = 6\left(0 + \left[\begin{array}{c} 0 \\ 1 \end{array}\right]\right) + 11\left(0\left[\begin{array}{c} 0 \\ 1 \end{array}\right] + \left[\begin{array}{c} 0 \\ 0 \end{array}\right]\right) = 11
\end{align}$$
For the recurrence relation with the signed Stirling numbers of the first kind, you would get:
$$\begin{align}
\mathrm{s}(4,2) & = -3 \mathrm{s}(3,2) + \mathrm{s}(3,1) \\
& = -3[-2\mathrm{s}(2,2) + \mathrm{s}(2,1)] -2\mathrm{s}(2,1) + \mathrm{s}(2,0)  = 6\mathrm{s}(2,2) -5\mathrm{s}(2,1) + 0 \\
& = 6[-\mathrm{s}(1,2) + \mathrm{s}(1,1)] -5[-\mathrm{s}(1,1) + \mathrm{s}(1,0)] = -6\mathrm{s}(1,2) + 11\mathrm{s}(1,1) - 0 \\
& = -6[0 + \mathrm{s}(0,1)] + 11[0 + \mathrm{s}(0,0)] = 11
\end{align}$$


text:
Q: Is there a difference between using Svelte with Nativescript and "Svelte native"? Is there a difference between using Svelte with Nativescript and "Svelte native" ?
If yes, what is the most significant difference in practice ?

A:
Svelte Native is a new approach to building mobile applications using NativeScript. Where other JavaScript mobile development frameworks like React Native and NativeScript-Vue do the bulk of their work on the mobile device, Svelte Native shifts that work into a compile step that happens when you build your app.
Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the native view widgets when the state of your app changes.

this is from svelte-native official web-site
so Svelte native is the name of the framework and that framework uses Nativescript.


text:
Q: How to increase the font size in Context-Sensitive Autocompletion? Today I just upgrade my Mathematica to 12.1 under Ubuntu 19.04.
Everything works fine but the font size is too small. As a result, I set the zoom level to 150%. Even though the font in the editor zone is big enough, the font size in the Context-Sensitive Autocompletion pop-up window is still too small to read.
I wonder how to increase the font size in the Context-Sensitive Autocompletion.
Thank you.
P.S. Resolution of my monitor is 4k Ultra HD.

A: Suggested by @ihojnicki, another solution is:

*

*create a file named ~/.Mathematica/FrontEnd/frontend.css;

*append the following configuration to frontend.css:
* { font-size:16pt; font-family:"Griffy"; }

*done.

A: Inspired by the solution from Font size for help drop down menu in input cell, my solution is as followed:

*

*Go to menu Format / Edit Stylesheet. this will open the style configuration similar as the left of the following image.

*Open Core.nb in $InstallationDirectory/SystemFiles/FrontEnd/Stylesheets. This doc looks as the right of the following image.

*Copy the cells "CodeAssistCompletion" and "CodeAssistCompletionHighlight" from Core.nb to the opened window in 1., and format these two cells by configuring menu -> Fromat -> Size.
Done. This configuration increases the font size only for this notebook, not for global setting.
I am still looking forward to a permanent global setting.

A: Launch Mathematica from the terminal in Ubuntu 19.04 with the following command:
 QT_SCALE_FACTOR=1.5 Mathematica

The font size in the Context-Sensitive Autocompletion increases, except for the font in the pop-up window blurs.

A: Some supplement to PureLine's answer.
(works for Mathematica 12.0 on Ubuntu 20.04 LTS)
To make it work permanently, I mainly follow the official tutorial https://support.wolfram.com/29974?src=mathematica.
1.open a new notebook, click "Format->Edit Stylesheet" and edit the private stylesheet as mentioned by PureLine
2.click "File->Save As" and save to be $UserBaseDictionary/SystemFiles/FrontEnd/StyleSheets/Default.nb
3.click "Format->Option Inspector",change selection->global option (if necessary), search for DefaultStyleDefinition and set to be the .nb saved in step 2
done (re-open a notebook and see changes

A: Based on @PureLine's answer and many other answers to related questions, I test my Mathematica for maybe 4h to learn the following things. And I will give the maybe untimate method to do this (At least works for my Mathematica 13.1).
The problem also arised when I got my new computer with relatively high screen resolution(2.5k). That's the code-assistant-popup fonts is too small, not zoomed to the ratio of the other normal texts. Even, I use other stylesheet instead of Default. So the problem become more complex.
Phenomena I encounter includes:

*

*Don't know what terms control only the code-assistant popup font.

*When I find out the answer, it's found that it doesn't save the change I make. i.e. I do successfully change the font, but when I close and reopen the .nb, it come back to the original status.

So here is the solutions:

Case A. You use Default stylesheet.

*

*Go to menu Format / Edit Stylesheet. This open the first window which is going to (futher)modify your current stylesheet. It's first line is "Inheriting base definitions from style sheet Default.nb"

*Open the Core.nb, find the following terms (depends on your need). Copy them one by one to the first window mentioned before. Append them in the next several lines, as follows:

(I suggest to set them in the same size, a little smaller than the code in the notebook.)
As for the meaning of these 5 terms, just change it to a big font and try typing some code (e.g. Table) and you will understand. (It's so hard to describe sorry.)

*Change them to the font style you wants. For examples, 12 pts heavy.

*In the top of the window, click "Export" and name it. Then this is your stylesheet in which fonts are correctly(as you want) shown.

*Apply it to your current notebook or set as default.

Case B. You use some other stylesheet.
ATTENTIONS!!! Before going into next steps, DESELECT it from the "DefaultStyleDefinitions"! Otherwise it will fail.
After this prior preparation, open your stylesheet file (e.g. my "Dracula.nb").  Go to the 2. and 3. steps mentioned before. And the 4th step is, save the file. Finally step 5----set it again as the default stylesheet by going to Ctrl+Shift+O(see Additional knowledge 1.).
Additional knowledge:

*

*How to set stylesheet .nb file as default. : Press Ctrl+Shift+O, in "Show option values" select "Global Preferences". Search in "Lookup" for "DefaultStyleDefinitions". Change it to your stylesheet .nb file. Reboot Mathematica.

*There is a bug here. That's why you need to deselect original stylesheet before successfully update it. The phenomena that it goes inaccurately: a. Ctrl+S doesn't save the file and when you close the window you
receive a warning asking whether to save it. Actually even though
you tap "Save" it doesn't work. b. You reopen the stylesheet file. You will find all your changes have disappeared.

A: *

*Go to Format / Option Inspector

*Show Option Values: change from Selection to Global Preferences

*Go to Global Options / System Configurations / ScreenResolutionCompatibilityMode - False

*Restart Mathematica


text:
Q: Is data driven identification in a simultaneous equation model possible? Suppose I have to estimate 3 models:
$y_1 = y_2\beta_1 + y_3\beta_2 + X\beta_3 + u_1$
$y_2 = y_1\alpha_1 + y_3\alpha_2 + X\alpha_3 + u_2$
$y_3 = y_1\gamma_1 + y_2\gamma_2 + X\gamma_3 + u_3$
I account for the endogeneity of $y_1, y_2$ and $y_3$ with a approach which creates a additional variable which allows me to not exlude any other regressors.
Suppose these additional regressors are $c_1$ for $y_1$, $c_2$ for $y_2$ and $c_3$ for $y_3$. Now the models will be:
$y_1 = y_2\beta_1 + y_3\beta_2 + X\beta_3 + c_2\beta_4 + c_3\beta_5 + u_1$
$y_2 = y_1\alpha_1 + y_3\alpha_2 + X\alpha_3 + c_1\alpha_4 + c_3\alpha_5 + u_2$
$y_3 = y_1\gamma_1 + y_2\gamma_2 + X\gamma_3 + c_1\gamma_4 + c_2\gamma_5 + u_2$
Given that the influence of the $c_i$ in each equation is significant, identification is achieved. The reason is that in each equation one $c_i$ is missing (for example $c_1$ in the $y_1$ equation).
It turns out that I cannot leave $c_1$ out of the equation regarding $y_1$ (same for all the other equations). If I would, the model would be seriously biased.
My questions are: When I estimate the full model, i.e., all $c_i$ are included in every equation and some of the regressors contained in $X$ are not signficant and these regressors are all different for each equation, is identification achieved?
I would say yes. But this approach does only achieve identification through the insignificance of a regressor. I'm not quite sure if this is the right angle to it.


text:
Q: PhantomJS error on basic tests I'm using the node-phantom npm module, and whenever I do a super simple test like
phantom=require('node-phantom');
var phantom=require('node-phantom');
phantom.create(function(err,ph) {
    console.log("testing");
    ph.exit();
});

It prints the following error:
phantom stdout: console msg:XMLHttpRequest cannot load http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=1439501157936-0. Origin http://127.0.0.1:60689 is not allowed by Access-Control-Allow-Origin.

Anyone know what the cause of this could be?
package.json:
{
  "name": "test",
  "version": "0.0.1",
  "devDependencies": {
    "grunt": "^0.4.5",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-exec": "^0.4.6",
    "mocha": "^2.2.5",
    "node-phantom": "^0.2.5",
    "phantom": "^0.7.2",
    "phantomjs": "^1.9.18",
  }
}

(there are multiple versions of phantom because I've been trying some out)

A: Changed window.location.hostname to window.location.host in node-phantom.js file.


text:
Q: Displaying a symbol µ I have <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> in the header, but it still shows � instead of µ. I tried adding AddCharset UTF-8 .php to .htaccess, but it didn't help.
EDIT: if I just put symbol µ in the file, it displays correctly. I get � when I try to output it from a database.

A: If something displays as the � UNICODE REPLACEMENT CHARACTER, that means the document is interpreted in a Unicode encoding (e.g. UTF-8) but the byte sequence at this point is invalid in this encoding.
In other words, your data/file is not UTF-8 encoded. Make sure it's saved as UTF-8, not just declared as such.
If you have problems outputting it from a database, it means the data coming from the database is not UTF-8 encoded. See Handling Unicode Front To Back In A Web App.

A: You get this problem because your output actually is not UTF-8, even though you tell the browser that it is. You should fix that problem.
If you fix it by correcting the output so it is proper UTF-8, then your problem will be fixed, because UTF-8 can display this symbol (and any other). If you fix it by changing the charset to an ANSI character set, then you will have output in a codepage that may not support this symbol.
To output it correctly, you can output it as a html entity, either µ or µ. If you do this now, the symbol will also display correctly, but remember that your actual output is not UTF-8, so if you need another symbol on your page, then you'll have the same problem!
Edit
I see your edit now. If it works with a hard coded character, then the PHP is right, but the fetched data doesn't have the proper encoding. You can solve this by giving your database, table and/or the specific column any of the unicode collations. An alternative method would be to use the function iconv to convert the data from your database to UTF-8 after you query it.


text:
Q: Can two different continuous forms run off the same queryi in access 2010? So I have two subforms, one to show internal training course completion for an employee and the other is the same thing but for vendor training.
Both subforms pull the same data from the same table, but display different selective data (different columns from the table).
I added the employee search combobox code to reflect the second "vendor training" subform:
Private Sub cboEmployee_AfterUpdate()
    On Error GoTo Proc_Error
    If IsNull(Me.cboEmployee) Then
        Me.subEmployeeCourseTrainingCompletion.Form.Filter = ""
        Me.subEmployeeCourseTrainingCompletion.Form.FilterOn = False
        Me.subEmployeeVendorCourseTrainingCompletion.Form.Filter = ""
        Me.subEmployeeVendorCourseTrainingCompletion.Form.FilterOn = False
    Else
        Me.subEmployeeCourseTrainingCompletion.Form.Filter = "[EmployeeID]=" & Me.cboEmployee
        Me.subEmployeeCourseTrainingCompletion.Form.FilterOn = True
        Debug.Print Me.subEmployeeCourseTrainingCompletion.Form.Filter
        Me.subEmployeeVendorCourseTrainingCompletion.Form.Filter = "[EmployeeID]=" & Me.cboEmployee
        Me.subEmployeeVendorCourseTrainingCompletion.Form.FilterOn = True
        Debug.Print Me.subEmployeeVendorCourseTrainingCompletion.Form.Filter
    End If
Proc_Exit:
        Exit Sub
Proc_Error:
        MsgBox "Error " & Err.Number & " in setting subEmployeeCourseTrainingCompletion filter:" & vbCrLf & Err.Description
        MsgBox "Error " & Err.Number & " in setting subEmployeeVendorCourseTrainingCompletion filter:" & vbCrLf & Err.Description
        Resume Proc_Exit
End Sub

The internval training subform still works and updates based on the employee ID in the combobox, but the second, vendor, subform doesn't update.
Any ideas as to why and possible solutions?

A: Force the update of the second form once you have made changes and saved the data in the first one:
Me.subEmployeeVendorCourseTrainingCompletion.Form.Requery

You could do this in the Form_AfterUpdate of the first subform:
Private Sub Form_AfterUpdate()
    Parent.subEmployeeVendorCourseTrainingCompletion.Form.Requery
End Sub

UPDATE
Try another approach. Instead of setting filters use the Link Child Fields and Link Master Fields properties of the subforms in order to link the subforms to the main form.


text:
Q: Amazon MWS _GET_MERCHANT_LISTINGS_DATA_ empty When I call GetReport I only get the headers for the tab delimited response. However, when I use the scratch pad to, RequestReport, RequestReportList, using the RequestId to get GeneratedReportId and then GetReport with that Id. I get expected results.
Does anyone have an idea why my code doesn't pull the report like the scrathpad does?
            RequestReportRequest request = new RequestReportRequest();
            request.Merchant = settings.SellerId;
            request.MarketplaceIdList = new IdList();
            request.MarketplaceIdList.Id = new List<string>(new string[] { settings.MarketplaceId });
            request.ReportType = "_GET_MERCHANT_LISTINGS_DATA_";

            RequestReportResponse requestResponse = _mws.RequestReport(request);
            Thread.Sleep(15000);
            Console.WriteLine(requestResponse.RequestReportResult.ReportRequestInfo.ReportProcessingStatus);
            GetReportRequestListRequest reportRequestListRequest = new GetReportRequestListRequest();

            reportRequestListRequest.Merchant = settings.SellerId;
            List<ReportRequestInfo> requestInfos = new List<ReportRequestInfo>();

            GetReportRequestListResponse reportRequestListResponse = new GetReportRequestListResponse();
            reportRequestListResponse = _mws.GetReportRequestList(reportRequestListRequest);
            GetReportRequestListResult reportRequestListResult = new GetReportRequestListResult();
            reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
            requestInfos = reportRequestListResult.ReportRequestInfo;

            while (requestInfos[0].ReportProcessingStatus.ToString() != "_DONE_")
            {
                Thread.Sleep(20000);
                reportRequestListResponse = _mws.GetReportRequestList(reportRequestListRequest);
                reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
                requestInfos = reportRequestListResult.ReportRequestInfo;

            }

            GetReportListRequest listRequest = new GetReportListRequest();
            listRequest.Merchant = settings.SellerId;
            listRequest.ReportRequestIdList = new IdList();
            listRequest.ReportRequestIdList.Id.Add(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);

            GetReportListResponse listResponse = _mws.GetReportList(listRequest);

            GetReportListResult getReportListResult = listResponse.GetReportListResult;

            GetReportRequest reportRequest = new GetReportRequest();
            reportRequest.Merchant = settings.SellerId;
            reportRequest.WithReportId(getReportListResult.ReportInfo[0].ReportId);

            GetReportResponse reportResponse = new GetReportResponse();
            string fileName = dataPath + "\\report-" + getReportListResult.ReportInfo[0].ReportId + ".txt";
            reportRequest.Report = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            reportResponse = _mws.GetReport(reportRequest);

A: I removed the MarketplaceId from the ReportRequest and it works fine. I'm not sure why it didn't pull the report with it specified, but it is working without the information.
Removed these 2 lines from above code.
        request.MarketplaceIdList = new IdList();
        request.MarketplaceIdList.Id = new List<string>(new string[] { settings.MarketplaceId });


text:
Q: Formula for intersection of "power" curve and parabola. EDIT
I have edited this question to make it more clear.
I have spent quite some time trying to find this on Google, but haven't succeeded.
I need the formula(s) to determine the intersection between an power curve and a parabola.
The image below shows a curve in black, and a blue power curve (ignore the other curves and the fact that the curves have a somewhat equal x-mirror image). I need to find the point where blue intersects black.
The only other scenario I have is that the arc may be on the "left" of this image, i.e. intersect the opposite shown blue exponential curve.
The power curve may be convex, concave, or flat (linear), and has the following general equation:
$ y = 1 - ( s ( x^p - i ) )^b$
$p, b, s, i$ are known positive constants; $x$ is known.
$x^p > i$
The parabola is derived from 3 known points by using the quadratic equation $ax^2 + bx + c = 0$
The $y$ apex of the parabola is always 1.

Can someone point me to a resource that gives the formula(s)?


text:
Q: Powershell ForEach Loop Failing I'm trying to generate a report for all WIM files in my MDT Deployment Share.  Basically, I think need to do a ForEach loop on all the WIM files found.  I have what I think should work but, obviously, it doesn't.  How far off am I?
$WimPath = "G:\DeploymentShare\Operating Systems"

Get-ChildItem -Path $WimPath -Filter *.wim -Recurse -File | Select-Object -ExpandProperty VersionInfo | Select-Object FileName | ForEach-Object { Get-WindowsImage -ImagePath $_ }

The error I'm seeing is nagging about the Parameter being incorrect for the Get-WindowsImage command.
Get-WindowsImage : The parameter is incorrect.
At line:3 char:147
+ ... t-Object FileName | ForEach-Object { Get-WindowsImage -ImagePath $_ }
+                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I'm thinking my Select-Object isn't working like I think it should or I'm not using the pipeline correctly in my Get-WindowsImage command.

A: I'm a PowerShell noob and don't fully understand this, but I think what is going on can be explained by first focusing on this part of the command:
Get-ChildItem -Path $WimPath -Filter *.wim -Recurse -File | Select-Object -ExpandProperty VersionInfo | Select-Object FileName

To get this far, we first get all the *.wim files in your path, we expand the VersionInfo property, and then select the FileName. In the console, that will show you results like this:

FileName
--------
[files here]

The trick is in understanding what PowerShell is telling you with this output. The fact you see a FileName header means the pipeline has a stream of Objects with one property named FileName. Then we send that stream of Objects to ForEach-Object and look at the $_ special variable.
Hopefully it is clearer now what is going on. Get-WindowsImage -ImagePath $_ wants to see a string value holding the path of a *.wim file. But we sent it an object with one property.
You can fix this a few ways... adding ExpandProperty to the second Select-Object would probably do it. But really there's no reason for two Select-Objects in there at all. I think you could just do this:
Get-ChildItem -Path $WimPath -Filter *.wim -Recurse -File | Select-Object -ExpandProperty FullName | ForEach-Object { Get-WindowsImage -ImagePath $_ }

And the trick here is the string representation you see in the shell from Get-ChildItem doesn't necessarily show every property in the object. There wouldn't be space. The FileName was always there, and you can see it by checking the Get-Member cmdlet, like so:
Get-ChildItem -Path $WimPath -Filter *.wim -Recurse -File | Get-Member


text:
Q: Save Smart Blob in Informix Database and FluentNhibernate I need to Save a Smart Blob  in informix database, ther is my model :
 public class ArtistaFoto : Entity
{
    public virtual Artista Artista { get; set; }
    public virtual int NumeroSeq { get; set; }
    public virtual byte[] BlobArtistas { get; set; }
    public virtual string NomeArquivos { get; set; }
    public virtual string Extensao { get; set; }
}

there is my Mapping
       public ArtistaFotosMapping()
    {
        this.Table("sb_aneartistas");
        this.CompositeId().KeyReference(x => x.Artista, "cdartista").KeyProperty(x => x.NumeroSeq, "nrseq");
        this.Map(x => x.BlobArtistas).Column("sbaneartistas");
        this.Map(x => x.NomeArquivos).Column("nome_arq");
        this.Map(x => x.Extensao).Column("extensao");
    }

and there is my exception when I try to save my entity

So I know that this field in Informix Database is a SmartBlob, and this is not a normal blob (byte or string).Someone can help me?

A: My difficulty is in build a connection follow :
   ISessionFactory factory = Fluently.Configure()
                          .Database(
                IfxSQLIConfiguration
               .Informix1000
              .ConnectionString("Provider=Ifxoledbc.2;Password=xxxx;Persist Security Info=True;User ID=xxxx;Data Source=xxxx")
                             .Driver<OleDbDriver>()
               .Dialect<InformixDialect1000>()
               .ShowSql())
               .Mappings(x => x.FluentMappings.AddFromAssemblyOf<ArtistaFotoMapping>()
               ).ExposeConfiguration(x =>
                  x.SetProperty(NHibernate.Cfg.Environment.PrepareSql, "True")
               )
               .BuildSessionFactory();`

and I change for IfxOdbcConfiguration that follow sample:
  ISessionFactory factory = Fluently.Configure()
  .Database(
    IfxOdbcConfiguration
    .Informix1000
    .ConnectionString("DRIVER={IBM INFORMIX ODBC DRIVER};SERVER=xxxx;DATABASE=xxxx;UID=xxx;PWD=xxx;NEEDODBCTYPESONLY=1;")
    .ShowSql())
    .Mappings(x => x.FluentMappings.AddFromAssemblyOf<ArtistaFotoMapping>()
    ).ExposeConfiguration(x =>
       x.SetProperty(NHibernate.Cfg.Environment.PrepareSql, "False")
    )
    .BuildSessionFactory();


text:
Q: HTML 5 Video not working on IE9 Why video on this page and this page working in all browser but not in Microsoft Internet explorer 9?
Any fix for it?
This video is not playing on My IE 9.0.8112.16421
My OS is Windows 7 64 bit

A: Some versions of IE9 require an absolute path to the video file for some reason.
For example:
<video poster="big_buck_bunny/poster.jpg" controls>
  <source src="http://www.example.com/big_buck_bunny/trailer.mp4" type="video/mp4" >
  <source src="http://www.example.com/big_buck_bunny/trailer.webm" type="video/webm">
</video>

A: The MIME type returned by the server is also quite important as Jason Dorell said.
I was using <video> tag on a website and while writing it in localhost everything worked perfectly. Once uploaded into the server, the <video> stopped working only in IE (Firefox and Chrome still worked fine).
After digging a bit into it, I simply added AddType video/mp4 .mp4 into the .htaccess file and that solved the problem.

A: the problem maybe the type of file try with this:
<video poster="big_buck_bunny/poster.jpg" controls>
  <source src="big_buck_bunny/trailer.mp4" type="video/mp4" >
  <source src="big_buck_bunny/trailer.ogg" type="video/ogg" >
  <source src="big_buck_bunny/trailer.webm" type="video/webm">
</video>

big_buck_bunny/trailer.* is your video

A: It could also be an error in the compatibility detection : Just a theory =X
Taken from: videojs: main.js (line 249-255)
// Check if the browser supports video.
browserSupportsVideo: function() {
    if (typeof VideoJS.videoSupport != "undefined") { return VideoJS.videoSupport; }
    VideoJS.videoSupport = !!document.createElement('video').canPlayType;
    return VideoJS.videoSupport;
}

Cause the fallback to flash is i believe, quite reliable, after this detection. I do not have IE 9.0.8... : So you could give this code a run, to see if this is true/false
var test = function() {
    return (!!document.createElement('video').canPlayType);
}

If this is true, i may consider forking the file : And adding a fail for IE 9.0.8...
It would not surprise me if IE did a half-hearted video support halfway : And this means of detection broke, in the process.

A: I have exactly the same issue. The two example pages you linked to let me click the play button which then changes to a pause button but the videos do not play.
The java script i tried to help track down the issue returns null.
alert(document.getElementsByTagName("video")[0].error);
I did stumble upon this though:
I'm using the N distribution of Windows 7 64Bit. This msdn page suggests that the reason that my IE9 will not play video is that my distribution of windows did not come with media player or "Media Features" is turned off.
Hope this helps.

A: If it's still not working here's what may certainly be a solution: encode the mp4 with compression format H.264. If you encode it with format mpeg4 or divx or else it will not work on IE9 and may as well crash Google Chrome. To do that, I use Any Video Converter freeware. But it could be done with any good video tool out there.
I've been trying all solutions listed here and tried other workaround for days but the problem lied in the way I created my mp4. IE9 does not decode other format than H.264.
Hope this helps,
Jimmy

A: Make sure the content type being returned from the server is "video/mp4"

A: Sometimes the problem could be in the installed video codecs, and different browsers may play video in different ways (from the point of inner implementation).
Try to install e.g. K-Lite codec pack and see what happens.
p.s. those videos work fine on my Win 7 x64 within IE9 x86 and IE9 x64

A: In IE9 There is no flash video but a HTML5 <video> element used, it tries to load:
http://www.bodhibikes.com/_/video/WELCOME_TO_BODHI_840_472.mp4

And that fails somehow. You should specify  a correct videoformat for both IE/Chrome?etc...


text:
Q: Should a Web site also be a Web resource?
Every web application - every web site - is a service. (...) The features that make a web site easy for a web surfer to use also make a web service API easy for a programmer to use.
Richardson and Ruby, "RESTFul Web Services"

As I intend it, a Web site that is also a Web service provides multiple representations of its resources, depending on what the user-agent requests. The API, so-to-speak, is the Web site itself, and is not provided separately.
This isn't the case for many popular "REST APIs" out in the wild. Twitter's API, for example, is located at http://api.twitter.com/1/, the '1' in the URI being the version of the API itself. Socialcast also provides a REST API at https://demo.socialcast.com/api/ , the third level name being the name of the network it addresses.
This seems wrong to me. If I have my blog at http://www.example.com/blog, I shouldn't need to provide an API at a different location, serving JSON just for robots. Instead of having http://www.example.com/blog/posts/ and http://api.example.com/blog/posts, two different URIs, I should have just the former, and multiple representations available, among which application/json for the JSON API I wish to provide to my users.
Example 1: a browser asking for the posts on my blog;
Request:
curl -i \
 -H "Accept: text/html" \
 -X GET \
 http://www.example.org/blog/posts/

Response:
 200 OK
 Content-Type: text/html; charset=utf-8

Posts

My first post ...

Example 2: same URI, but this time a robot makes the request;
Request:
curl -i \
 -H "Accept: application/json" \
 -X GET \
 http://www.example.org/blog/posts/

Response:
 200 OK
 Content-Type: text/html; charset=utf-8

 {
    "posts": [
        {
            "id": 1,
            "title": "My first post" ...

Version numbers for APIs should be encoded in the "Accept" field of the request headers, and above all avoiding strongly typing the URIs like Twitter does ("statuses/show.json?id=210462857140252672" or "statuses/show/210462857140252672.json").
I could lose some flexibility by going for the unified approach (but, shouldn't Cool URIs never change?), but I think adhering to REST (or at least my interpretation of it) would provide more benefit.
Which is the more correct approach: separating the API and the Web site, or unifying them?

A: There is no right or wrong here. Following REST and RFCs too closely may prove to be difficult when your API development is driven by specific client requirements.
In reality, human users have different behaviour patterns compared to API clients, and therefore require different treatment. The most vivid distinction comes from the fact that many APIs are very data intensive, designed for batch operations and data dumping, whereas applications for human users are more "reactive" and often do things step-by-step, request-by-request. As a consequence, in many projects APIs URL design is optimised to avoid wasting client and server resources on multiple network roundtrips and repeat storage calls.
Under the hood, API implementations often have different design from core application, optimised for the kind of operations APIs provide. For example, API implementation may use a separate caching strategy. Now if you split the code out, you may want to create a cluster of hosts that only handle the API calls. That is where placing API on another domain becomes beneficial for load management: a separate domain allows for simpler load balancing on high-load sites. In comparison, when you use /api URL prefix on the same domain name (but have separate clusters) then you need a smart (L7-aware) load balancer to do the job of splitting the request flow between API and web front end clusters, but such load balancers are more expensive.
So there may be very good technical reasons why the likes of Twitter separate out the API, but references to other implementations may not apply to YOUR project. If you are at early stages of design, you may want to start with a unified URL scheme on the same domain, but eventually you may find that there are good real-life use cases that make you change the approach, and then ... refactoring.
P.S. there is a lengthy discussion on versioning here - Best practices for API versioning?
P.S.S. I find strongly typed URLs helpful in quick debugging. You can simply put a URL into the browser with .json and quickly get the result without switching to the command line. But agree with you that "accept" header is the preferred method
P.S.S.S. SEO for APIs? I can see how a good URL design can be beneficial, but for a search engine its probably irrelevant if your service provides multiple output formats on the same path / domain name. In the end of the day, search engines are built for human users, and human users don't consume XML and JSON.

A: The Web and a RESTful API may behave in different ways.
In theory, how would a request like http://mysite.com/blog/1 distinguishes if it needs to return an HTML page or just the data (JSON, XML...)? I'll vote for using the Accept http header:
Accept: text/html <-- Web browsers
Accept: application/json <-- Applications/Relying parties consuming data or performing actions

Why Twitter, Facebook or other sites don't mix both Web browsers and relying parties? Honestly I would argue that is an arbitrary decision.
Perhaps I can provide one possible reason: Web browser/Search engine robot URLs should be friendly-URLs because these work better on SEO. For that reason, maybe the SEO-ready URLs aren't very semantic in terms of REST, but they're for search engine or even human users!
Finally: which is better (it's my opinion)?

*

*You need SEO, then use separate URLs.

*You don't need SEO, then unify URLs in the same domain and format.

A: I disagree with the other answer that this decision should have anything to do with SEO or how 'friendly' a URL is (robots are [written by] people too!). But my intuition tells me that better SEO results would come from unifying the URIs since that also unifies pagerank in the (unlikely) event that your API URIs would get linked to from the world wild web.
What this decision should rest on is what your server and clients are capable of. If they can set Accept request headers, and your server is smart enough to do transparent content negotiation, then by all means unify the URIs. This is what I do (my only JSON client though is myself, issuing AJAX requests served from other HTML parts of my web app, where I do control the Accept header).
If a client is not able to set request headers, such as a web user wanting to get the json response, they will end up with the default (presumably text/html). For this reason you may want to allow non-negotiated responses to occur under unique URIs (/foo.txt, /foo.rtf). Conventionally this is done by appending the format to the URI seperated by a dot, as if it were a filename extension (but it usually isn't, mod_rewrite does the juggling) so that old clients on platforms that need filename extensions can save the file with a meaningful one.
Most pages on my site work something like this:

*

*Determine SQL query from request URL. (e.g. /cars?colour=black => SELECT * FROM cars WHERE colour='black')

*Issue SQL query.

*Determine acceptable response type from list supported by this file. This is usually HTML and HAL (i.e. JSON), though sometimes XML too. Fall back to text/html if nothing else is Acceptable.

*if(HTML) spit out  and  (considering the parameters:
Black Cars
)

*spit out results using most acceptable response type.
This function knows how to take a SQL result object and turn it into HTTP Link headers, a stream of HTML <LINK> elements, HAL's _links key, a stream of XLink elements, an HTML
 element (with cells containing  elements), or a CSV file. The SQL query may return 0 rows, in which case a user-friendly message is written instead of an HTML table if that output was being used.

*if(HTML) spit out
This basic outline handles about 30 different resource collections in my web app, though each one has a different set of options the request URI may invoke, so the start of each differs in terms of parameter validation.
So, now I have explained all that, you can see how it might be useful to have all the specifics of each resource handled in one place, and the generics of outputting in format X or format Y handled by a common library function. It's an implementation detail which eases my life and helps me adhere to the Don't Repeat Yourself maxim.

A: I definitely don't agree with the web-site == web-service approach.
Simply put, the web site should be treated as a client, just a client, that consumes the web-service and renders the data in an appropriate form for web use. Just like a mobile application is a client, just a client, consuming the same web-service and renders the data in an appropriate form for the mobile use.
The web-service is the service provider. All others are just clients; web-site, android app, iphone app,...etc.


text:
Q: Get text from multiple span tags both inside a single div but with no additional distinguishing info In my soup object, I have a div tag with two nested span tags and need to grab the "750 mL" from the first span and the "117" from the second span.
two span tags inside a div

I'm able to get into the first span tag using :
soup.find('div', class_='other_details').find('span')

Unfortunately, I can't get into the second span tag as it shares a div and class with the first. Can anyone suggest a way to grab the second span tag?

A: Can you show the link that you want to scrape?
The only thing I can help is to use the findAll() function for tabindex in BeautifulSoup
bottle = soup.findAll("tabindex")
print(bottle[0].text)    #Output:750ml
print(bottle[1].text)    #Output:LCBO#:

A: For getting 750 ml and 117, you can try it:
from bs4 import BeautifulSoup
html_doc = '''

                    750 ml
                     bottle

                lCBO#:
                            117

'''

soup = BeautifulSoup(html_doc, 'lxml')

spans = soup.find_all("span")
# print(spans)
for span in spans:
    print(span.next_element.strip())
    break
i = 0
for span in spans:
    if i==1:
        if span.span != None:
            print(span.span.text)
    i = 1

Output will be:
750 ml
117

A: Another version using CSS selectors:
from bs4 import BeautifulSoup

txt = '''

                    750 ml
                     bottle

                lCBO#:
                            117

'''

soup = BeautifulSoup(txt, 'html.parser')

volume = soup.select_one('.other_details span:nth-child(1)').contents[0].strip()
number = soup.select_one('.other_details span:nth-child(2) span').text.strip()

print(volume)
print(number)

Prints:
750 ml
117


text:
Q: How to change Tor port in Kali i would like to change default tor port from 9050 to 9150.
Editing /etc/tor/torsocks5.conf i can see these:
TorPort 9050
so, changing to 9150, it should work, right? it doesnt.
> sudo vi /etc/tor/torsocks.conf

> sudo cat /etc/tor/torsocks.conf  | grep 9150

TorPort 9150

> sudo service tor reload
> sudo service tor restart
> sudo service tor status
● tor.service - Anonymizing overlay network for TCP (multi-instance-master)
 Loaded: loaded (/lib/systemd/system/tor.service; enabled; vendor preset: disabled)
 Active: active (exited) since Mon 2022-06-27 13:46:11 CEST; 7s ago
Process: 43748 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 43748 (code=exited, status=0/SUCCESS)
    CPU: 2ms

Jun 27 13:46:11 kali systemd[1]: Starting Anonymizing overlay network for TCP (multi-instance-master)...
Jun 27 13:46:11 kali systemd[1]: Finished Anonymizing overlay network for TCP (multi-instance-master).
> sudo netstat -tanp | grep tor
tcp        0      0 127.0.0.1:9050          0.0.0.0:*               LISTEN      43758/tor
tcp        0      0 192.168.85.139:36538    178.238.236.41:1337     ESTABLISHED 43758/tor
tcp        0      0 192.168.85.139:57824    162.55.131.67:9100      ESTABLISHED 43758/tor

What do i am doing wrong?

A: The parameter you want to change is:
SocksPort 0.0.0.0:9150

Usually this is located in torrc file.


text:
Q: Too many hashing function collisions I'm trying to make a hashing function using the polynomial accumulation method (which is supposed to give you 5 collisions per 55k words or something) but when I run it with 1,000 words, I get ~190 collisions. Am I doing something wrong?
public int hashCode(String str) {
        double hash_value = 0; // used for float
        for (int i = 0; i < str.length(); i++){
            hash_value = 33*hash_value + str.charAt(i);
        }
        return (int) (hash_value % array_size);
    }

A: Generally, prime numbers are favoured for hash code generation. I suggest trying 109 or 251. 33 is a multiple of 3 which means you are more likely to have issues based on your inputs.
Also you should use an int for the calculations and call Math.abs on the result.

A: Either your data set is extremely "unlucky", or (which is more probable) the array_size is too small (hash function params are usually quoted without consideration of finite bucket array size).

A: You are generating a large number which is different for different word in the input. But there is still a chance of collisions, as for example
"bA" = 98+(33x65)=2243
"AB" = 65+(33x66)=2243

If you go for a large number greater then 57, there will be less chance of collision. 109 or 251 will be a good choice.


text:
Q: Nullable object must have a value? On the line: bool travel = fill.travel.Value; I am getting the following error:

Nullable object must have a value

and i am not sure why. All I want to do is get the value in the database of travel which is currently false. Any help would be appreciated.
using (var db = new DataClasses1DataContext())
{
    var fill = (from f in db.expenseHdrs
                where f.rptNo == getPkRowReport()
                select f).FirstOrDefault();

    txtReportDesc.Text = fill.description;
    txtPeriod.Text = fill.period;
    txtPurpose.Text = fill.purpose;

    bool travel = fill.travel.Value;
    chkTravel.Checked = travel
 }

A: You can always switch to
 fill.travel.GetValueOrDefault()

To provide the default (false), or the value of the boolean column from the database. Or you can specify the default with an overload. Either way, the nullable currently doesnt have a value, which is why you get that exception.

A: You will get a InvalidOperationException if you access the Nullable.Value property when the HasValue property is false.

A: You can check if nullable variable has some value like this before your actually access its value
if(fill.travel.HasValue)
{
   bool travel = fill.travel.Value;
}

A: The value coming from the database is a nullable boolean.  When you call Nullable.Value, and the value is null, you will get this exception.  Consider checking the property Nullable.HasValue before calling .Value.

A: I had this happen because there was code like this:
bool? someVariable = (bool)someNullableBool;

The someNullableBool was null and this error was thrown.
The solution was to re-write it as:
bool? someVariable = (bool?)someNullableBool;

A: You are trying to access property from the nonexistent object (your fill.travel is null, and you calling prop from it),
you can use coalesce operator (.Net 4.0):
bool travel = fill.travel ?? false;

A: Null is not false. See Eric Lippert's blog article series about this at: http://blogs.msdn.com/b/ericlippert/archive/2012/03/26/null-is-not-false.aspx
You need to process a null result into a false, if that is how you want to translate it.
To make this case clear, consider this code:
bool travel;
bool? temptravel = fill.travel.Value;
if( temptravel == true )
    travel = true;
else
    travel = false;

Or just use Val Bakhtin's solution if you are using .Net 4

A: You can always use the classic C ? operator like this:
bool travel = (fill.travel == null ? false : fill.travel.Value);


text:
Q: addEventListener to array of elements and target array of elements window.onload = function() {
    // set default for landing page:
    window.location.replace("#Overview");
    // register click event listener for top navigation:
    var navBarButtons = ["class1","class2","class3","class4","class5","class6","class7","class8","class9"];
    var navBarTargets = ["id1","id2","id3","id4","id5","id6","id7","id8","id9"];
    registerNavBar(navBarButtons, navBarTargets);
}
function registerNavBar(navBarButtons, navBarTargets){
    for (var i=0; i<navBarButtons.length; i++){
        sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
        sourceElement.addEventListener("click",clickNavBarButton({targets:navBarTargets,index:i}))
    }
}
function clickNavBarButton(event){
    clearPages(event.targets);
    document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
}
function clearPages(navBarTargets) {
    for (i=0; i<navBarTargets.length; i++){
        var target = "#".concat(navBarTargets[i]),classList=document.querySelector(target).classList;
        if (classList.contains("active")){
            classList.remove("active")
        }
    }
}

Im trying to to add an onclick events to elements in my navigation bar which looks like this:

The registerNavBar() function fails to add onclick events to the elements getting returned by the #left_nav .classn selectors.
The .active class is defined as
.active {
    display: block!important
}

while the default state is
display: none

so adding/removing the .active class toggles visibility. Using external libraries is not an option.
Currently all the functions in the loop are beeing performed without throwing errors and i end up with the element with #id9 beeing displayed, but the buttons won't trigger the onclick events when clicked.
How to properly add eventListeners to all elements in the Array?

A: You can create a closure to keep the event Object data
function registerNavBar(navBarButtons, navBarTargets){
    for (var i=0; i<navBarButtons.length; i++){
        sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
        sourceElement.addEventListener("click",clickNavBarButton({targets:navBarTargets,index:i}))
    }
}
function clickNavBarButton(event){
  return function(){
    clearPages(event.targets);
    document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
    }
}


text:
Q: How i can change my splash screen with zsh terminal? Guys I install a bad splash screen and my KDE desktop is broke and not loud bet I have access to my terminal so I want to change my splash screen by terminal maybe my problem is fixed
I use Kubuntu 20.04 LTS

A: The KDE splash screen configuration is stored in:-
/usr/share/plasma/look-and-feel/org.kde.breeze.desktop/contents/lockscreen/LockScreen.qml

My suggestion is your custom image directory create a symlink to a real image file then all you have to do is change the symlink to a different file.
Example assuming you configure KDE to use ~/images/kde_splash.png
e.g.
ln -sf ~/images/batman_logo.png ~/images/kde_splash.png

or
ln -sf ~/images/superman_logo.png ~/images/kde_splash.png

Which means whenever KDE reads ~/images/kde_splash.png it will reference the file you have chosen.


text:
Q: ViewPager and updating Fragments In my app's activity, I have a ViewPager implementation which loads a Map fragment (FragmentA) on launch and then there are 2 other fragments showing content based on the latitude and longitude selected in FragmentA.
I am unable to get the behavior where upon launch, the latitude/longitude from FragmentA, should be provided to the 2 other fragments and continue to provide whenever user clicks on the map in FragmentA.
Here are the approaches I tried:

*

*using interface to communicate between fragment -> activity -> fragment (sticking with this approach)

*using bundle to pass information between fragments when the fragments are getting initialized

However, neither of these approaches have worked for me.
MyActivity.java//update to show Daniel's suggestion
public class MyDemoActivity extends FragmentActivity
                implements FragmentA.OnFragmentInteractionListener,
                    FragmentB.OnFragmentInteractionListener, IUserLatLong  {

    private MyPagerAdapter pagerAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_in_pager_demo);

        ViewPager mPager = (ViewPager) findViewById(R.id.pager);
        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), getApplicationContext());
        mPager.setAdapter(pagerAdapter);

        //always start w/ Maps View, FragmentA
        mPager.setCurrentItem(1);

        //
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
           @Override
           public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //do something
           }

           @Override
           public void onPageSelected(int position) {
             // do this instead of calling, notifyDataSetChanged()
            Fragment frag = pagerAdapter.fragments[position];
            if (frag != null && frag instanceof FragmentB) {
                Log.i(TAG, "::FragmentB:: Fetching data from Activity");
                //here is my confusion, calling FragmentB with latlong from FragmentA
                ((FragmentB) frag).setNewLatLong(newUserLatLong);
            }
           }

           @Override
           public void onPageScrollStateChanged(int state) {
             //do something
           }
       });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        //do something
    }

    @Override
    public void makeUseOfNewLocation(UserLatLong userLatLong) {
       newUserLatLong = userLatLong;
       Log.i(TAG, "LatLong from FragmentA is: " + newUserLatLong.getLat()
                + " and long is: " + newUserLatLong.getLng());
    }

/**
 * Used for fetching data from activity
 * @return
 */
public UserLatLong getLLFromActivity() {
      if(newUserLatLong == null) {
        Log.e(TAG, "LatLong from FragmentA came up empty");
      } else {

        Log.i(TAG, "LatLong from FragmentA IS NOT empty: " + newUserLatLong.getLat()
                + " and long is: " + newUserLatLong.getLng());
      }
      return newUserLatLong;
    }

}

MyPagerAdapter.java
public class MyPagerAdapter extends FragmentPagerAdapter {

    private static int NUM_ITEMS = 3;
    public MyPagerAdapter(FragmentManager fm, Context context) {
       super(fm);
       this.context = context;
    }

    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // not sure if this is really helping
    @Override
    public int getItemPosition(Object object) {
        // POSITION_NONE makes it possible to reload the PagerAdapter
        return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                //uses location from FragmentA to get data
                return new FragmentB();
            case 1:
                //loads map and gets location
                return new FragmentA();
            case 2:
                //uses location from FragmentA to get data
                return new FragmentC();
            default:
                return null;
        }
    }

   //This populates your Fragment reference array:
   @Override
   public Object instantiateItem(ViewGroup container, int position) {
       Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
       fragments[position]  = createdFragment;
       Log.i(TAG, "::instantiateItem:: " + position + " " + createdFragment.toString());
       return createdFragment;
    }

}

FragmentA.java /**left out most of map specific code,
but I am interested in getting latitude/longitude whenever onConnected() or onMapClick() gets called*/
@Override
public void onConnected(@Nullable Bundle bundle) {
     Log.i(TAG, "In onConnected(), Google API client is:: " + mGoogleApiClient.isConnected());

     if (mGoogleApiClient != null) {
         try {
                // Get last known recent location.
                mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                if (mCurrentLocation != null) {
                    // Print current location if not null
                    final LatLng latLng = new LatLng(mCurrentLocation.getLatitude(),
                                                        mCurrentLocation.getLongitude());

                    //wrap LatLng into UserLatLong
                    userLatLong.setLat(latLng.latitude);
                    userLatLong.setLng(latLng.longitude);
//updating the value in the interface
                    mLLCallback.makeUseOfNewLocation(userLatLong);

                    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 20);
                    mMap.animateCamera(cameraUpdate);
                    mMap.addMarker(new MarkerOptions().position(latLng));
                    Log.i(TAG, "::Google::My current location set::");

                    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                        @Override
                        public void onMapClick(LatLng latLng1) {
                            mMap.clear(); //removes the previous marker
                            mMap.addMarker(new MarkerOptions().position(latLng1));

                //updating the value in the interface
                mLLCallback.makeUseOfNewLocation(userLatLong);
                            float x = (float) latLng1.latitude;
                            float y = (float) latLng1.longitude;
                            Log.d(TAG, "Map clicked w/ lat: " + x + " and long: " + y);

                            //wrap LatLng into UserLatLong
                            userLatLong.setLat(latLng1.latitude);
                            userLatLong.setLng(latLng1.longitude);

                        }
                    });

                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

                    //for zooming automatically to the location of the marker
                    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(12).build();
                    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                    //TODO: Constrain the camera target to bounds defined by API
                    mMap.setMinZoomPreference(Constants.DEFAULT_MIN_ZOOM);
                    mMap.setMaxZoomPreference(Constants.DEFAULT_MAX_ZOOM);

                } else {
                    Toast.makeText(getActivity(), "Current location is null", Toast.LENGTH_SHORT).show();
                }
            } catch (SecurityException se1) {
                Log.e(TAG, "SecurityException1: " + se1.getLocalizedMessage());
            }

        } else {
            Toast.makeText(getActivity(), "Google API client is null!", Toast.LENGTH_SHORT).show();
        }

FragmentB /**in this fragment, I want to refresh content based on latitude/longitude from FragmentA*/
public class FragmentB extends Fragment {
    /**
     * Required empty public constructor
     */
    public FragmentB() {
    }

/**the getArguments() is always null*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    currLatLong = getNewLatLong();
    }

    /**I want latitude/longitude from FragmentA before onCreateView gets called*/
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {

        LayoutInflater inflater1 = LayoutInflater.from(getContext());
        // Inflate the layout for this fragment
        view = inflater1.inflate(R.layout.fragment_a, container, false);
       currLatLong = getNewLatLong();
        //fetch my list based on LatLong
        handleDataFetch(currLatLong);

        return view;
    }

    //
    private void handleDataFetch(UserLatLong newLatLong) {
        final UserLatLong latLong = newLatLong;
        final APIEndpointI apiEndpointI = APIRequests.getClient().create(APIEndpointI.class);

        String userId = "XXXX-XXX-XXXXXXX";

        currLatLong = new UserLatLong(newLat.doubleValue(), newLong.doubleValue());
        if (currLatLong != null) {
            Log.i(TAG, "Finally! Lat is: " + currLatLong.getLat() +
                    " and Long is:" + currLatLong.getLng());
            /**using retrofit*/
            Call<MyResp> call = apiEndpointI.getMyList(userId, currLatLong);
            call.enqueue(new Callback<MyResp>() {
                @Override
                public void onResponse(Call<MyResp> call, Response<MyResp> response) {

                    Log.i(TAG, "Count: " + response.body().getBundles().size());
                    Resources res = getContext().getResources();
                    String cntString = String.format(res.getString(R.string.count), response.body().getBundles().size());
                    tv1.setText(cntString);

                    //Initialize with empty data
                    mGridData = new ArrayList<>();
                    mGridAdapter = new ProfilePicAdapter(getActivity(), R.layout.grid_item_layout, mGridData);
                    mGridView.setAdapter(mGridAdapter);

                   }
                @Override
                public void onFailure(Call<MyResp> call, Throwable t) {
                    //do something here
                    Log.d(TAG, "Failed to get response for GetMyList(): " + t.getMessage());
                }
            });
        } else {
            Log.e(TAG, "In onCreateView(), lat long are empty");
        }
    }

   //called from activity to pass the latest latlong
   public void setNewLatLong(UserLatLong userLatLong) {
      currLatLong = userLatLong;
   }

   //called from activity to pass the latest latlong
   private UserLatLong getNewLatLong() {
      return currLatLong;
   }

}

A: It looks like all you need to complete the implementation is to call handleDataFetch() from the setNewLatLong() method if it is a new location.
This is needed since onCreateView() won't be called due to the Fragment being in a ViewPager, so the best way to get the updated location info to FragmentB when it is displayed is to just use a public method called from the ViewPager.OnPageChangeListener in the Activity, as you are doing here.
Just be sure that your equals() method override is implemented correctly in the UserLatLong class, and add this to the setNewLatLong() method:
   //called from activity to pass the latest latlong
   public void setNewLatLong(UserLatLong userLatLong) {
      //Added:
      if (!currLatLong.equals(userLatLong)) {
          handleDataFetch(userLatLong);
      }
      currLatLong = userLatLong;
   }


text:
Q: SDL2 get keymapped / "cooked" code for a keypress event? I'm trying to "cook" a modifier + keycode as received from SDL_KEYDOWN events, into what the combination represents in the current OS keymap.
In SDL1, this was available in the keysym.unicode field, but this is gone in SDL2.
Instead, you're supposed to listen to SDL_TEXTINPUT events for this, which does work, but the problem is they come after the corresponding SDL_KEYDOWN events, so if you have for example a hotkey that you use and want to react to, which could need to be a part of a composite key, you get into trouble.
More specifically, I'm trying to react to the '/' press, in the current keymap, to open an admin command box in a game. But on my keymap, / is reached with Shift+7, and I'm already using 7 as a hotkey for other stuff and don't want to trig that other stuff in the Shift+7 case (but I can't know from the game that it's the particular Shift+7 which represents '/'!)
In SDL2, I get these events in this order:

*

*SDL_KEYDOWN for L_SHIFT

*SDL_KEYDOWN for 7

*SDL_TEXTINPUT for '/'

One workaround I was going to ask about is if there was a way to "cook" the "L_SHIFT + '7'" combination into '/' myself, this way I could check this immediately on the SDL_KEYDOWN for 7, before waiting for an SDL_TEXTINPUT event.
In SDL1 on the other hand, I would get:

*

*SDL_KEYDOWN for L_SHIFT

*SDL_KEYDOWN for '7' with keysym.unicode field set to '/'

which worked fine (and also worked then for keymaps that had '/' on a dedicated key).


text:
Q: extjs 6.53 increase remote request timeout globally I have put the following inside Application.js:
Ext.Ajax.setTimeout(300000);
Ext.override(Ext.data.proxy.Server, { timeout: Ext.Ajax.getTimeout() });

My store still timeouts after 30s.

A: You do need to override it for both ajax/proxy, however you override the one for ajax via the Connection. In your code, for the proxy you've overridden the timeout to be a function reference.
Ext.define(null, {
  override: 'Ext.data.Connection',
  timeout: 1
});

Ext.define(null, {
  override: 'Ext.data.proxy.Server',
  config: {
    timeout: 1
  }
});


text:
Q: Multilingual MySQL Database Structure for huge data I'm looking for some advice regarding a multilingual MySQL Database Structure which can handle huge amounts of data.
We are using the following method at the moment:
Articles  <- Article_translations -> Languages
id           id                      id
date         language_id (fk)        locale
category     article_id  (fk)
             content

Ok, lets just say we've got like 100.000 Articles and 5 languages...well..you see the problem. The larger the data, the slower the database (just a guess here, but complex JOIN queries which are absolutely necessary probably won't be O(log(n)) but rather something like O(n^2)).
Our current solution is to split the Article_translations into [locale]_article_translations (e.g. en_us_article_translation) in which case we would need to synchronize the structure between those tables easily. Is this an appropriate method to solve this problem or are there better ones? If this is a good solution, is there something out there which could help to monitor changes (only structural, no data synch!) and synchronize those structures?

A: you are half right, larger data slower database, but if the DB don't have a good design it will be slow even with small data.
I can't tell you what is the best way or the best solution, remember that you need to make multiple things to find the "best solution".  I just can recommend you some tools and some tips that could help you.
First, check your index, index types, no only PK and FK, you need also see which type of index do you need, I.E, do you need text index? or hashtree??.
Check also your engine, MyISAM or InnoDB?.  You said that you split the table, check this post about split.
Also your query will be faster if you avoid things like  '%word%' remember that a bad query will make a huge difference about time of response.
You can use Show create table or Describe select ...... or explain to see what's going on, or use the command benchmark to see the approximate time of a function that you are applying to improve it
Some tools for MySQL I'll recommend you to take a look to this program that will help you with this part of performance.

*

*Mysqlslap (it's like benchmark but you can customize more the result).

*SysBench (test CPUperformance, I/O performance, mutex contention, memory speed, database performance).

*Mysqltuner (with this you can analize general statistics, Storage engine Statistics, performance metrics).

*mk-query-profiler (perform analysis of a SQL Statement).

*mysqldumpslow (good to know witch queries are causing problems).

A: Assuming if you tune your query properly

*

*Check query execution plan with the large set of data

*Make sure if you use DB level parameter as "large set" instead of row level

*See if you make your table denormalized(or vise versa) enough.

I would suggest belows although I am not sure which version of MySQL your are using

*

*Partitioing at DB level

*Fast hard disk in the DB server

I would suggest to use partitioning first and then you might consider to upgrade hard disk.
Partitioning
Partitioning is data spliting provided by database level.
Based on your query usage, you can divide data, for example, by language in your case.
The good thing to use DB partitioning is that

*

*it could be treated by a single table from application side

*Depends on the data volumn and frequncy, it can be rearranged by DB level. No impact to the apps.

Hard disk quality
Also the hard disk quality is important to handle large set of data.
Even if the query is tunned at best, if you deal with lots of data in a single query, you need fast data access. But this is costy.


text:
Q: Which YCbCr matrix to use? BT.709 or BT.601 I'm working on a video player project on iOS.
It uses AVFoundation to extract CVPixelBuffer from a video file and then send that buffer to OpenGL as textures.
The proof-of-concept code is inspired by Apple's sample code.
The AVFoundation provides each frame in YCbCr color space and it need to be transformed into RGB to render in OpenGL. This transform seems to have multiple transform matrix options depending on different YCbCr standard(e.g. ITU-R BT.709, ITU-R BT.601). The sample code determines which one to use by following code:

CFTypeRef colorAttachments = CVBufferGetAttachment(pixelBuffer, kCVImageBufferYCbCrMatrixKey, NULL);
if (colorAttachments == kCVImageBufferYCbCrMatrix_ITU_R_601_4) {
    _preferredConversion = kColorConversion601;
}
else {
    _preferredConversion = kColorConversion709;
}

However, I'm using swift and the return colorAttachment is of type Unmanaged<CFTypeRef> while the constant kCVImageBufferYCbCrMatrix_ITU_R_601_4 is of type CFString so they can't be equaled directly. I did some research and ended up with:

CFEqual(colorAttachments, kCVImageBufferYCbCrMatrix_ITU_R_601_4) // returns false
CFEqual(colorAttachments, kCVImageBufferYCbCrMatrix_ITU_R_709_2) // returns false too!!
//-----------------------------------------
CFGetType(colorAttachments) // returns 1
CFStringGetType() // returns 7, note kCVImageBufferYCbCrMatrix_ITU_R_601_4 is of type CFString
// so I still can't check their equality
// because the retrieved  colorAttachments is not of type CFString at all

I tried two transforms one-by-one by hardcoding the matrix and the result (rendered scene) seems no difference to human eye which is predictable because the two transform matrixes are not differed to much.
My questions:

*

*How to determine which transform to use?

*If it's impossible to solve [1.], can I hard code either one? what's the consequence of doing so?

A: Using takeUnretainedValue() will give you a CFTypeRef. This then needs to be downcast to a CFString. For example, your code could look like this:
if let colorAttachment = CVBufferGetAttachment(image, kCVImageBufferYCbCrMatrixKey, nil)?.takeUnretainedValue(),
    CFGetTypeID(colorAttachment) == CFStringGetTypeID() {
    let colorAttachmentString = colorAttachment as! CFString
    print(colorAttachmentString)
    print(colorAttachmentString == kCVImageBufferYCbCrMatrix_ITU_R_601_4)
    print(colorAttachmentString == kCVImageBufferYCbCrMatrix_ITU_R_709_2)
}

Which prints:
ITU_R_601_4
true
false


text:
Q: Dynamically added views not displaying in LinearLayout The client I am building for needs a feature that requires me wrap a scroll view around a lot of content, including the 'news' section. Because of this, I can't use a ListView. I am attempting to manually inflate all of the ListItem views into a vertical LinearLayout. I realize I'll lose of the sweet optimizations of ListView, but it's what the client wants so I have to oblige. I feel like my solution should be working, but no views are being drawn to the screen. Inside of my ScrollView is a LinearLayout, and inside of it is this second LinearLayout:
<!-- News Fragment -->
        <LinearLayout
            android:id="@+id/news_frag"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/test_yellow"/>

Here is the layout file for NewsListItem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:orientation="horizontal"
android:onClick="newsListItemClick"
android:background="@color/test_green">

<com.android.volley.toolbox.NetworkImageView
    style="@style/thumbnail_image"
    android:id="@+id/news_list_item_image"
    android:layout_width="@dimen/thumbnail_width"
    android:layout_height="@dimen/thumbnail_height" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        style="@style/headline_text"
        android:id="@+id/news_list_item_headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        style="@style/promo_text"
        android:id="@+id/news_list_item_promo_brief"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

And finally, the code I'm using programmatically. newsRequest() is the last call I make in onCreateView:
private void newsRequest() {
    Log.d("snw", "newsRequest()");
    JsonArrayRequest jsonRequest = new JsonArrayRequest(NEWS_FEED_URL,
            new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    NewsListItem item = new NewsListItem((JSONObject) response.get(i));
                    View view = addNewsToView(item);
                    containerView.addView(view);
                    containerView.invalidate();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            containerView.bringToFront(); //something I tried, didn't help
            containerView.postInvalidate(); //Same as above
        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }

    });

    volleyQueue.add(jsonRequest);
}

private View addNewsToView(NewsListItem item) {
    Log.d("snw", "addNewsToView()");
    ViewHolder holder;
    View view = new View(getActivity());

    if (view.getTag() == null) {
        Log.d("snw", "Holder was null, inflating view");
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.news_list_item, null);

        // set up ViewHolder
        holder = new ViewHolder();
        holder.thumbnail = (NetworkImageView) view.findViewById(R.id.news_list_item_image);
        holder.headline = (TextView) view.findViewById(R.id.news_list_item_headline);
        holder.promoBrief = (TextView) view.findViewById(R.id.news_list_item_promo_brief);

        //set custom fonts
        Typeface futuraBold =
                Typeface.createFromAsset(view.getContext().getAssets(), "fonts/futura_today_bold.ttf");
        Typeface futuraLight =
                Typeface.createFromAsset(view.getContext().getAssets(), "fonts/futura_today_light.ttf");

        holder.headline.setTypeface(futuraBold);
        holder.promoBrief.setTypeface(futuraLight);

        // store holder with the view
        view.setTag(holder);
    }
    else {
        holder = (ViewHolder) view.getTag();
    }
    holder.headline.setText(item.getHeadline());
    holder.promoBrief.setText(item.getPromoBrief());
    holder.thumbnail.setImageUrl(UrlBuilder.buildUrl(item.getImgUrl()),
            VolleySingleton.getInstance(getActivity()).getImageLoader());

    return view;
}

private class ViewHolder {
    NetworkImageView thumbnail;
    TextView headline;
    TextView promoBrief;
}

Everything I've read suggests this should be working fine, it's just as easy as calling addView and attaching my inflated view to the ViewGroup container, a LinearLayout. A few things I've read suggesting manually setting the LayoutParameters on the view before attaching it, but this had no effect as far as I can tell. Any insight?

A: I got an Idea for using the ListView even if you have to scroll content above and beneath with it. You can define a footer and a header to an ListView, this makes it appear above and below just as you would expect. For me that looked like this:
View headerView = inflater.inflate(R.layout.my_header_layout, null, false);
this.footer = new MyFooterView(getActivity());
this.interactionsList.addHeaderView(headerView);
this.interactionsList.addFooterView(this.footer);

Works like a charm. :)
I found an example, notice the Elements above and below, which behave as they would within the ListView: https://www.youtube.com/watch?v=pAiHQAE5G6c


text:
Q: Table Valued CLR Function with SQL date return type I'm trying to create a CLR (C#) table valued function that returns a table of dates.
[SqlFunction(
   DataAccess = DataAccessKind.Read,
   FillRowMethodName = "FindDates_FillRow",
   TableDefinition = "ReturnDate date")]
public static IEnumerable BusinessDays(SqlDateTime startDate, SqlDateTime endDate)
{
    //function body
}

public static void FindDates_FillRow(
object resultObj,
out SqlDateTime returnDate)
{
    dayResult result = (dayResult)resultObj;
    returnDate = result.Date;
}

The above code results in an error because the SqlDateTime type creates a method signature on FillRow that differs from what SQL Server expects given the TableDefinition attribute.

SQL72014: .Net SqlClient Data Provider: Msg 6258, Level 16, State 1,
  Procedure BusinessDays, Line 1 Function signature of "FillRow" method
  (as designated by SqlFunctionAttribute.FillRowMethodName) does not
  match SQL declaration for table valued CLR function'BusinessDays' due
  to column 1.

If I change the TableDefinition to a datetime type, everything works but since there is no SqlDate type, how can I return a date type? Is this even possible or do I just need to use datetime on the CLR side and cast to a date in my SQL query?

A: There is no SqlDate type in system.data.sqltypes, and no other data type that would contain only a date. The way to do it is to pass a datetime and convert it in SQL(if you really need conversion to Date).


text:
Q: Regular expression token antlrV3 Can I write a rule where the initial token is partly fixed and partly generic?
rule: ID '=' NUMBER
      ;

ID: (A.. Z | a.. Z) +

NUMBER: (0 .. 9) +

But only if the token ID is in the form var* (var is fixed)
Thanks

A: Do you mean this?
// Use this instead of ID in all parser rules that take either token
identifier
    :   VAR_ID | ID
    ;

VAR_ID
    :   'var' ('A'..'Z' | 'a'..'z')*
    ;

ID
    :   ('A'..'Z' | 'a'..'z')+
    ;

Either way: when possible, do NOT use a strict lexer grammar for your error messages. They are slower and completely illegible to users. You should parse ID in a relaxed form, then check later on if it's in precisely the correct form.


text:
Q: Get child element by HTML Object I'm attempting to reuse the variable "startGame", variable through which I declare an "a" element to be appended to the "table" element, in order to test for its own presence posteriorly. The code I've written for doing so is the following:
//Helper function to set HTML Tags attributes
function setAttributes(element, attributes)
{ for (var key in attributes) { element.setAttribute(key, attributes[key]); } }

//Opening screen
var startGame = document.createElement("a");
setAttributes(startGame,
{
    "style" : "float:left; width: 100%; text-align: center;",
    "onclick" : "dealHands()"
});
startGame.appendChild(document.createTextNode("Play"));

var table = document.getElementById("table");
table.appendChild(startGame);

function dealHands()
{
    if (table.childNodes[0].nodeValue == startGame)
    { table.removeChild(startGame); }
    ...
}

So far, the code fails to perceive "startGame" and nothing happens.

A: You cannot set the style attributes using this:
"style" : "float:left; width: 100%; text-align: center;"

they have to be set individually. But IE doesn't support changing style in this way. You need:
element.style.cssFloat = "left";    // etc.

Discussed here
Also, I wouldn't use table as an ID.

A: I just had to remove the ".nodeValue" from the if statement in order to make a comparison between two HTML elements instead of comparing a value with a HTML element.


text:
Q: The power set under intersection and addition as a ring If $D$ is a set and $P(D)$ its power set, and $A+B=(A-B) \cup (B-A)$, $AB=A \cap B$ how come $P(D)$ is not a suitable identity?
Also, I would appreciate it if someone could elaborate on why if $A \cap A^{-1}=D$ that $A=A^{-1}=D$? Intuitively this makes sense, but is there an axiom or such that I can use to better explain this property?
I understand that $D$ itself is an identity, and as such is unique. But shouldn't $P(D)$ work as well? Can someone provide a counter example?

A: The (multiplicative) identity must be an element of $P(D)$ and $P(D)$ doesn't qualify: $P(D)\notin P(D)$, in general. And $D=P(D)$ is impossible, by the way. So, even if $P(D)\in P(D)$, it wouldn't be a multiplicative identity, because you already know that $D$ is.
The only element having a multiplicative inverse is $D$. Suppose $AB=A\cap B=D$. Then $D\subseteq A$, so $A=D$.


text:
Q: How to delete the virtual directory entry from IIS? I have written some code to delete Virtual Directories, however all that it is doing is that it deleted the folder structures beneath the Virtuals and not the actual virtual entries in IIS, so that if I open IIS I can still see the listings under Default Web Site.
How does one delete virtual while also deleting the entries so that nothing is listed under Default Web Site?

A: This should work for both IIS6 (metabase config system) and IIS7 (xml-based config system):
string vDirPath = "IIS://localhost/W3SVC/<siteIndex>/ROOT/<vdirName>";
DirectoryEntry vDir = new DirectoryEntry(vDirPath);
vDir.DeleteTree();

where siteIndex is an index of your site and vdirName is the name of your vdir.


text:
Q: How can I filter out just one ocurrence in a string vector in Scala? I need to create a new vector from Vector("lumber", "stone", "magic potion","stone","lumber") but without the string "lumber", if i use the method filterNot(_=="lumber") it removes the two elements that match "lumber". is there a filter out just one ocurrence?
i tried using .distinct but i need the two stones in the vector.

A: Easiest way is to use diff:
val c = Vector("lumber", "stone", "magic potion","stone","lumber")
c diff Vector("lumber")
// result: Vector(stone, magic potion, stone, lumber)

A: You can split the collection at the first occurence and then drop it:
val (pre, post) = c.span(_ == "lumber")
pre.dropRight(1) ++ post

When there is no "lumber" in the collection, pre will be empty and pre.dropRight(1) will drop nothing.
With 2.13 you can prefer a one-liner using pipe:
import scala.util.chaining._

c.span(_ == "lumber").pipe(split => split._1.dropRight(1) ++ split._2)


text:
Q: Post int directly to web api without model class I am new to C#. I tried to create a post service with using int. All get and post service are working fine.
But when I pass parameter to post service, it's always null. But after creating a class it works fine. Can we pass direct int to service or we must have to create a model class for it?
    [System.Web.Http.HttpPost]
    public IHttpActionResult GetUserByID(int id)
    {
        var user = userList.FirstOrDefault((p) => p.Id == id);
        if (user== null)
        {
            return NotFound();
        }
        return Ok(user);
    }

but it always send 0 .  but when i create a class and add that int as attribute it works fine.
Working code
    [System.Web.Http.HttpPost]
    public IHttpActionResult GetUserByID(data id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return Ok();
    }

   public class data
   {
       [Required]
       public int id { get; set; }
   }

Edit

are my header accurate?

A: I think you need to add [FromBody] to the parameter:
[System.Web.Http.HttpPost]
public IHttpActionResult GetUserByID([FromBody]int id)
{
    var user = userList.FirstOrDefault((p) => p.Id == id);
    if (user== null)
    {
        return NotFound();
    }
    return Ok(user);
}

According to the docs: Parameter Binding in ASP.NET Web API

By default, Web API uses the following rules to bind parameters:

*

*If the parameter is a "simple" type, Web API tries to get the value    from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from
  a string.

*For complex types, Web API tries to read the value from the message      body, using a media-type formatter.

It goes on to say: Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter

UPDATES - to get [HttpPost] working...
As @Shahbaz suggested below, make sure that you've got the Content-Type header set to application/json, otherwise you will get error message saying:

The request entity's media type 'text/plain' is not supported for this resource.

Also, make sure you're posting just the id in the Request Body e.g. 1, as opposed to posting the id wrapped in a JSON object as a key/value pair { "id": "1" }.
FINALLY - consider using [HttpGet] instead...
It's worth pointing out, because you are now just sending a single int to get a single record, even if you can get this working using [HttpPost], it's still probably best to change it to [HttpGet] which is semantically correct - you are getting a user record, and don't actually need to post anything at all. So something like this might be better:
[System.Web.Http.HttpGet]
[Route("api/users/{id}")]
public IHttpActionResult GetUserByID(int id)
{
    var user = userList.FirstOrDefault((p) => p.Id == id);
    if (user== null)
    {
        return NotFound();
    }
    return Ok(user);
}

Then put your id in the request URL, something like:
https://yourdomain/api/users/1

The above example makes use of Attribute Routing which can help  you create your own custom URLs to target your own API Action Methods.

A: Send Data to Web Api by a Jquery Like Below :
function PostSth(fid){
  $.ajax({
    url: apiBaseUrl + 'api/Controller/ActionMethod',
    type: 'Post',
    data:`'`+fid+`'`,
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        alert(data);

    },
    error: function () {
        alert('Error');
    }
 });
}

Don't Forget

data:`'`+fid+`'`,

above.
and do in the Code Behind Part :
public string ActionMethod([FromBody]int fid)
{
     string result = string.Empty;
     //TODO: Your Code

    return result;
}