text:
Q: Listbox Left Align inside table column I have the following popup window, which rendors listbox and some other objects inside table. There are three column in first row where i have placed two differenet listbox, my problem is they are not aligning to left. There is some spaces between the first and second listbox.
$
@{  Html.Telerik().Window()
    .Name("Window")
    .Title("Select Product")
    .Content(@<text>
        @using (Html.BeginForm())
        {

Categories:

                                @Html.ListBox("lstCat", new SelectList(new[] {""}), new {@style = "width: 250px;height:300px"})

Sub-Categories:

                                @Html.ListBox("lstSubCat", new SelectList(new[] {""}), new {@style = "width: 250px;height:300px"})

Products:

                                @*@Html.ListBox("lstProducts", new SelectList(new[] {""}), new {@style = "width: 400px;height:300px"})*@

                                @(Html.Telerik().Grid<CS_Product>()
                                .Name("product-grid")
                                .Scrollable(c => c.Height("120px"))
                                .Columns(columns =>
                                {
                                    columns.Bound(o => o.ID).Hidden(true);
                                    columns.Bound(o => o.Name).Width(200);
                                    columns.Bound(o => o.Sku).Width(200);
                                    columns.Bound(o => o.Price).Width(60);
                                    columns.Command(commands =>
                                        commands.Custom("AddProduct")
                                        .Text("Add")
                                        .DataRouteValues(route => route.Add(o => o.ID).RouteKey("productid"))
                                        .Ajax(true)
                                        .Action("AddProduct", "DirectOrder")).Width(100);
                                })

                                )

Shopping Bag:
(double click to remove product)

                            @(Html.Telerik().Grid<CS_ShoppingCartItem>()
                                .Name("shoppingbag-grid")
                                .Scrollable(c => c.Height("120px"))
                                .Columns(columns =>
                                {
                                    columns.Bound(o => o.ID).Hidden(true);
                                    columns.Bound(o => o.Sku).Width(100);
                                    columns.Bound(o => o.Name).Width(200);
                                    columns.Bound(o => o.Quantity).Width(60);
                                    columns.Bound(o => o.Price).Width(60);
                                    columns.Bound(o => o.Discount).Width(60);
                                    columns.Bound(o => o.PriceAfterDiscount).Width(90);
                                    columns.Command(commands =>
                                        commands.Custom("DeleteProduct")
                                        .Text("Delete")
                                        .DataRouteValues(route => route.Add(o => o.ID).RouteKey("productid"))
                                        .Ajax(true)
                                        .Action("DeleteProduct", "DirectOrder")).Width(100);
                                })

                                )

  Sub-Total:

        }
        </text>)
    .Height(600)
    .Draggable(true)
    .Modal(true)
    .Visible(false)
    .Render();

}

A: put align='left' in  as cell's default alignment is center.


text:
Q: How to make spelling does not count in Ruby?     if @msg =~ /facebook/i
        puts "Nice job, you got it!"
    end

I want to make a trivia game that would somehow do not care about spelling count if a person typed in facebook as the answer to the game.
if someone accidentally typed in  faceboko, fecabook, or ftckbook, it would work and give an output of "Nice job, you got it!"
I don't know how I would start it.

A: Generally Levenshtein distance is used to handle such problems.
You can implement your own solution - but there is a good gem which uses native C bindings.
Define an error rate (e.g. 4) and check the distance between user input and original string.
2.2.2 :001 > require "levenshtein"
 => true
2.2.2 :002 > Levenshtein.distance("facebook", "ftcebook")
 => 1

So, if you use this, your code will become,
err = 4
if Levenshtein.distance("original", @msg)>err
  "Nice job"
end

This also may be useful - Edit distance such as Levenshtein taking into account proximity on keyboard

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding controls dependent on sql table? Hello all I'm working on a little project where I'm adding controls to a page based on a SQL table of questions, this table will grow overtime. I just wanted to share the code and see if there was any better way or if any of the experts could chime in and give me any insight on future problems.  Here is the code:
       protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            SqlParameter[] paramz = new SqlParameter[1];
            paramz[0] = new SqlParameter("@c_id", 1);

            dt = SqlHelper.ExecuteDataTable(ConfigurationManager.ConnectionStrings["sql"].ToString(), CommandType.StoredProcedure, "get_Questions", paramz);
            clinicName.Text = "" + dt.Rows[0]["Clinic Name"].ToString();

            for(int row = 0; row <= dt.Rows.Count; row++)
            {
                if (row == dt.Rows.Count) //if we're on the last question put a break for spacing(this could be fixed with styling)
                {
                    Literal alit = new Literal();
                    alit.Text = "
";
                    questionsPanel.Controls.Add(alit);
                }
                else
                {
                    addQuestion(dt.Rows[row], row);
                }
            }

        }
        catch (Exception err)
        {
            Response.Write(err.Message);
        }

    }

    private void addQuestion(DataRow row, int i)
    {
        Label lbl = new Label();
        lbl.Text = row["question"].ToString();
        questionsPanel.Controls.Add(lbl);

        Literal lit = new Literal();
        lit.Text = "
";
        questionsPanel.Controls.Add(lit);

        TextBox txt = new TextBox();
        txt.ID = "txt" + i.ToString();
        questionsPanel.Controls.Add(txt);

        Literal lit2 = new Literal();
        lit2.Text = "
";
        questionsPanel.Controls.Add(lit2);

    }

A: Use a Repeater control:
ASPX Code:
<asp:Repeater id="repData" runat="server">
    <ItemTemplate>
        <asp:Label id="lblQuestion" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "question") %>' />

        <asp:TextBox id="lblAnswer" runat="server" />
    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

Code behind:
// Populate repeater
SqlParameter[] paramz = new SqlParameter[1];
paramz[0] = new SqlParameter("@c_id", 1);
dt = SqlHelper.ExecuteDataTable(ConfigurationManager.ConnectionStrings["sql"].ToString(), CommandType.StoredProcedure, "get_Questions", paramz);

repData.DataSource = dt;
repData.DataBind();

A: If the controls either use or contribute to ViewState, then you must ensure that the same controls are added to ViewState in the same order, on every post back. The order in which objects are added to ViewState depends on the order of the controls in the control tree.


text:
Q: Suppress / handle type errors in Angular for interpolated data I have some html that interpolates data from my component.ts, like
<div>
    {{currentData.property}}
</div>

Where currentData is a variable of type Data, which I made a class for. My component.ts looks something like this
export class DashboardComponent implements OnInit {

  cookie:any;
  currentData:Data;

  constructor(private apiService: ApiService, private utilService: UtilService, private router: Router) { }

  ngOnInit(): void {
    this.cookie = this.utilService.getCookie();
    if(this.cookie != ""){
      this.callServices()
    }else{
      this.router.navigate(['/login'])
    }
  }

  callServices(){
    this.currentData = await this.apiService.getData();
  }

My problem is more of a nuisance than anything. Everything functions as it should, but Angular bombards my console with errors because there is no property "property" on currentData, which is undefined. Once my API calls come through, the data goes where it should and I get no errors.
How do I get rid of these errors? Moreso, is there a best practice way of doing this that I'm missing here?


text:
Q: VB.NET implementation for C# base.GetHashCode() of struct I am porting a C# struct over to VB.NET and am facing the following problem:
The struct is used to safely invoke methods on objects without the need to check for null all the time. It has exactly one generic member, which can be null:
mValue As T

The GetHashCode method is implemented like that:
public override int GetHashCode()
{
    if (this.mValue != null)
    {
        this.mValue.GetHashCode();
    }

    return base.GetHashCode();
}

In the VB.NET implementation I cannot do
Return MyBase.GetHashCode()

because MyBase is not valid within a structure.
I have read this comment on how ValueType.GetHashCode is implemented.
According to this, in my example, I could probably just use
Return Me.GetType().GetHashCode()

for the case where mValue is null.
But this does not seem like a very solid implementation to me. Is there some simple way to call base.GetHashCode() for a structure in VB.NET?


text:
Q: How can I print mathing lines of text files in a directory and it's subdirectories which begin with a number or a dot, using shell script? I tried using the 'grep' command with a pattern, but it didn't work.
Here is my code:
#!/bin/bash

if [ ! $# -eq 1 ]
then echo usage: $0 dir
     exit 1
fi

if [ ! -d $1 ]
then echo "$1 is not a directory\!"
     exit 1
fi

grep -r '^[.0-9].*\t$' $1

Let's say I have a file (sample1), in ~/Downloads/
sample1:
123fghgfhfghgfhgfh
.9
something
45
jhjkhjhgjhjh

When I type "./myscript.sh ~/Downloads", I want to view:
 123fghgfhfghgfhgfh
.9
45

A: You can use this grep command:
grep -rE '^\.?[0-9]' "$1"

A: You can use command:
grep -I -rE "^[.0-9]" $1

or
grep --binary-files=without-match -rE "^[.0-9]" $1


text:
Q: Java polymorphism and method chaining So I have a couple of inherited classes defined like so.
class Base {
    public Base chainedMethodA() {
        // some stuff
        return this;
    }
}

class Derived extends Base {
    public Derived chainedMethodB() {
        // some stuff
        return this;
    }
}

Now, the following code works:
Derived obj = new Derived();
obj.chainedMethodB().chainedMethodA();

But this does not (notice the switched order of function calls):
Derived obj = new Derived();
obj.chainedMethodA().chainedMethodB();

The compiler gives an error on the chainedMethodB() function call. I can understand that this is because when you run chainedMethodA(), it returns an object of type Base, which does not have chainedMethodB defined.
I can think of a few solutions to this problem:

*

*Chain methods while paying attention to order (call Derived's methods first, and then call Base's methods). This looks like a very brittle solution.

*Override chainedMethodA in Derived so it returns an instance of Derived instead of Base. This looks like a waste of inheritance.

Is there any elegant way around this problem? Maybe some construct that magically changes chainedMethodA to return a Derived instance when called by an object of type Derived, without being explicitly overridden in Derived.

A:
Override chainedMethodA in Derived so it returns an instance of
  Derived instead of Base. This looks like a waste of inheritance.

You're wrong. You aren't wasting inheritance.
Technique of overriding is to do just that namely specialize a method. Override can be done when the returned type is the same or a subtype of the return type declared in the original overridden method in the superclass. So in this case you are violating nothing.
Read here for more about overriding.
Here example 1: (calling the superclass method)
public class Derived extends Base {
    @Override
    public Derived chainedMethodA(){

         super.chainedMethodA();
         //some stuff
        return this;
    }

    public Derived chainedMethodB() {
        // some stuff
        return this;
    }
}

Here example 2: (changing it completele)
public class Derived extends Base {
    @Override
    public Derived chainedMethodA(){
        //some stuff
        return this;
    }

    public Derived chainedMethodB() {
        // some stuff
        return this;
    }
    }

A: In this situation inheritance is probably the simplest solution.
However, your last sentence pretty much explains generics:

Maybe some construct that magically changes chainedMethodA to return a
  Derived instance when called by an object of type Derived, without
  being explicitly overridden in Derived.

So something like this may be useful in other similar use cases:
static class Base {
    public <T extends Base> T chainedMethodA(Class<T> clazz) throws Exception {
        // some stuff
        return clazz.cast(this);
    }
}

static class Derived extends Base {
    public Derived chainedMethodB() {
        // some stuff
        return this;
    }
}

public static void main(String args[]) throws Exception {
    Derived obj = new Derived();
    obj.chainedMethodA(Derived.class).chainedMethodB();
}


text:
Q: How to update content in Row after selection in dojo datagrid I have created one dojo datagrid. Every column has a formatter attached to it. When grid is generated the formatter is called. Now I want it so that if a user selects any row the formatter will be called and some strings should be attached to the selected row's column element.
Like grid is like this :
COLUMN
-------
a

b

c

and now user selects the 2nd row, the grid should change to :
COLUMN
-------
a

b SELECTED

c

Currently I implemented it like this :
if(this.grid.selection.selectedIndex !== -1){
  retrun value + "SELECTED";
}else{
 return value;
}

Can you please suggest a some good way of doing this? Please note that "SELECTED" string should not be added to the grid store.

A: The formatted is not hooked into clicking / selection of rows. It is solely performed when the contents (value) of a cell is set. Instead you'd want to move focus over to onRowClicked - an event on the grid component. It works like this:
grid.onRowClick = onRowClickHandler;

I wouldnt know which of following samples would put you closest to your goal but  onRowClickHandler could be setup as such:
function onRowClickHandler(evt) {
    var rows = this.selection.getSelected();
    // perform cell rendering here
    dojo.forEach(rows, function(row) {
       // this row is an item though.. you will have row._O as its index
    });
}

OR
function onRowClickHandler(e) {
   var cellClicked = this.focus.cell
   cellClicked.formatter();
}

However you may find that there are not much references to the viewable data anywhere in the grid component.. You could use following query selectors to find cell data and update the viewed html by calling formatter on each value. You would need to capture a previous selection for 'teardown' of your custom setting of values though.
var prevSelectedRows = [];
function onRowClickHandler(evt) {
    var idx = this.selection.selectedIndex,
        rawRow = dojo.query(".dojoxGridRow:nth-child("+(idx+1)+")", this.domNode)[0],
        self = this;

    // perform resetting of viewable values
    dojo.forEach(prevSelectedRows, function(raw) {
      dojo.query('.dojoxGridCell', raw).forEach(function(cellDOM, i) {
        cellDOM.innerHTML = cellDOM.innerHTML.replace("SELECTED", "");
      });

    });
    prevSelectedRows = []; // reset prev selection
    // look into grid.view.content for methods on this
    // perform setting of viewable values (SELECTED)
    dojo.query('.dojoxGridCell', rawRow).forEach(function(cellDOM, i) {
        // this function might be of interest, lets see how it looks in console
        console.log(self.layout.cells[i].formatter);
        cellDOM.innerHTML = cellDOM.innerHTML + "SELECTED"
    });

    prevSelectedRows.push(rawRow);
}


text:
Q: Package BlackBerry App using Cordova 2.7.0 I've have created an HTML5 app using Cordova 2.7.0.
All is working well with IOS and Android, but not Blackberry. I have googled/self troubleshoot the issue to death, but no dice...
Firstly my issue:
Whenever I try run the app on the simulator with the command (from the app location C:....):

ant blackberry build

It will successfully build the app see output below:

Buildfile: C:\SourceCode\App\BlackBerry\build.xml
blackberry:
build:
generate-cod-name:
       [echo] Generated name: cordovaExample.cod
clean:    [delete] Deleting directory
  C:\SourceCode\App\BlackBerry\build
package-app:
      [mkdir] Created dir: C:\SourceCode\App\BlackBerry\build\widget
       [copy] Copying 22 files to C:\SourceCode\App\BlackBerry\build\widget
        [zip] Building zip: C:\SourceCode\App\BlackBerry\build\cordovaExample.zip
build:
       [exec] [INFO]                      Parsing command line options
       [exec] [INFO]                      Parsing bbwp.properties
       [exec] [INFO]                      Validating application archive
       [exec] [INFO]                      Parsing config.xml
       [exec] [INFO]                      Populating application source
       [exec] [INFO]                      Compiling BlackBerry WebWorks applicatio n
       [exec] [FATAL]                     Executable name has embedded quote, spli t the arguments
BUILD SUCCESSFUL Total time: 13 seconds

However the app does not appear anywhere on the simulator. Also, in the build folder there are only 2 directories, "widget" and "cordovaExample.zip". I read somewhere there should be a "StandardInstall" and "OTAInstall" folder as well.
In neither of them are any .jad or .cod files.
I have also installed my code signing keys.
When trying to manually build the package (to get .jad or .cod files to install on my device) like so:

C:\Program Files (x86)\Research In Motion\BlackBerry WebWorks SDK
  2.3.1.5\bin>ja va -jar bbwp.jar C:\SourceCode\App\BlackBerry\build\cordovaExample.zip -g >myPassword -o C:\SourceCode\App\BlackBerry\build\signed

I get the following output:

[INFO]                  Parsing command line options [INFO]
  Parsing bbwp.properties [INFO]                  Validating application
  archive [INFO]                  Parsing config.xml [INFO]
  Populating application source [INFO]                  Compiling
  BlackBerry WebWorks application [FATAL]                 Executable
  name has embedded quote, split the arguments

My IDE: Windows 7 64 bit,
java version "1.7.0_21" (32 bit),
javac 1.7.0_21,
BlackBerry WebWorks SDK 2.3.1.5
Apache Ant(TM) version 1.9.0
I hope I supplied enough info to the issue. Please can you guys give me some help to get this up and running on the simulator and to get a distribution package?
Thanks in advance!

A: Ok, just for in case somebody else ever gets this issue, I got this sorted by uninstalling all Java versions and re-installing Java SDK 6 Update 43 (32 bit - as only this will work with the Blackberry Webworks SDK).


text:
Q: How to get a Flex project to load a plugin at runtime? I'm looking to have a couple of plugins in a Flex project I'm working on. I know I can load a SWF using the SWFLoader, but I thought in Flex3 you can now have Runtime Shared Libraries or something. Does anyone have any good documentation on loading a plugin at runtime? Ideally I'd like to be able to load a plugin from a URL, then execute some code from within the plugin (e.g. add a control to the page).

A: You can use either Modules or RSL.
RSLs have the advantage of getting cached by flash rather than the browser so they stick around longer.
Modules are easier to create and use. I have used modules and had issues with modules failing to load (code needs to handle that case). I haven't tried RSLs yet.
Here is some documentation on creating RSLs http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs

A: Note that, currently, loaded RSLs must be compiled against the very same version of the Flex framework.. if you plan for a "binary" plugin system, probably you want to wait for the Marshall plan feature to be implemented, in the next Flex version.

A: If you want to try a new and alternative approach, this is a application core framework modelled after java OSGi: http://www.potomacframework.org/
I haven't tried it myself, but it looks really cool!


text:
Q: Why do I have to install Rails every time I open a new terminal? I am having a problem with Ruby On Rails. Every time I open a new terminal and type a Rails command I get this error:
rails --version
Sorry, command-not-found has crashed! Please file a bug report at:
https://bugs.launchpad.net/command-not-found/+filebug
Please include the following information with the report:

command-not-found version: 0.3
Python version: 3.2.3 final 0
Distributor ID: Ubuntu
Description:    Ubuntu 12.10
Release:    12.10
Codename:   quantal
Exception information:

unsupported locale setting
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/CommandNotFound/util.py", line 24, in crash_guard
    callback()
  File "/usr/lib/command-not-found", line 69, in main
    enable_i18n()
  File "/usr/lib/command-not-found", line 40, in enable_i18n
    locale.setlocale(locale.LC_ALL, '')
  File "/usr/lib/python3.2/locale.py", line 541, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

The only way I can avoid this problem is to re-install Ruby and Rails, and I am a bit tired of doing it, since I have to do it every time I open a new terminal.
I tried to do a full uninstall with this command:
rvm implode

But with no success.
I also tried these commands, but still with no success:
rvm --default use 1.9.2 (or whatever you want your default ruby interpreter to be)
rvm gemset create rails-3.0.3
rvm use 1.9.2@rails-3.0.3 --default
gem install rails

A: Probably you just need to add RVM to PATH for scripting.
Add the following lines to your ~/.bashrc file.
PATH=$PATH:$HOME/bin/sublime_text/:$HOME/bin/cad_cuda/:$HOME/.rvm/bin
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"

A: It looks like you are trying to use rvm - check the install docs and make sure that you add the code to your shell bootup process that sets up RVM when you start a new shell.
https://rvm.io/rvm/install/
Look for "2. Load RVM into your shell sessions as a function"

A: I used this step by step guide when I installed rails on my Ubuntu machine. http://coding.smashingmagazine.com/2011/06/21/set-up-an-ubuntu-local-development-machine-for-ruby-on-rails/
I can't imagine what is causing your problem, but I had some problems myself because a few dependencies came in with the wrong versions. Doing a full update might help.


text:
Q: Interaction between PyAutoGui and Pynput // Threading I am currently writing some hotkey "macros" using python for a software which has bad usability and no API to speak off. I have no real experience/background in python programming (or really programming in general), just some general knowledge and small side projects.
The programm I am writing is supposed to repond to hotkey combinations and then click certain interface elements by locating them via image matching with openCV. This general works fine. The problematic behaviour is, that after some initial hotkey usages it seems that somewhere down the line a key value is registered which is not currently pressed, which leads to hotkeys firing off, when only 2 out of 3 needed keys are pressed.
The combination alt + shift + J does something. After initially using it, it seems that the "J" key is registered as pressed till I use another hotkey (p.e. shift+alt+K). This leads to the "J"-Function beeing executed, when I am only pressing alt + shift.
It seems some other people had the same problem, see here Pynput seems to conflict with pyautogui when defining hotkeys and simulating mouse clicks (sadly no solution there) or here PySimpleGUI breaks pynput. How do I combine them? (I sadly am not quite sure how to adapt threading to my program. My first naive attempt at simply wrapping the with-statement into an extra thread didn't solve the issue.)
Here's my code (I am aware that it probably is really really un-optimized, especially regarding my "click"-function):
import cv2
import numpy as np
import pyautogui
import mouse
import sys
import time
from pynput import keyboard as kb

# insert needle images here. p.e. advanced selection, matrix wiz etc...
designButtonImage = cv2.imread('needle_images/designButton.png', cv2.COLOR_RGB2BGR)
navigationButtonImage = cv2.imread('needle_images/navigationButton.png', cv2.COLOR_RGB2BGR)
dataEntyButtonImage = cv2.imread('needle_images/dataEntryButton.png', cv2.COLOR_RGB2BGR)
openItemsButtonImage = cv2.imread('needle_images/openItemsButton.png', cv2.COLOR_RGB2BGR)
tagetikRibbon = cv2.imread('needle_images/tgk_ribbon.png', cv2.COLOR_RGB2BGR)

allNeedleImages = [designButtonImage,
                   navigationButtonImage,
                   dataEntyButtonImage,
                   openItemsButtonImage,
                   tagetikRibbon
                   ]

def search(needleImage):

    image = cv2.cvtColor(np.array(pyautogui.screenshot()), cv2.COLOR_RGB2BGR)
    result = cv2.matchTemplate(image, needleImage, cv2.TM_CCOEFF_NORMED)

    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result)
    w = needleImage.shape[1]
    h = needleImage.shape[0]

    return [minVal, maxVal, minLoc, maxLoc, result, w, h]

def click(needleImageMetaDataIndex):

    initialMousePos = pyautogui.position()
    needleImageMetaData = search(allNeedleImages[needleImageMetaDataIndex])

    if needleImageMetaData[1] >= 0.75:
        mouse.move(int(needleImageMetaData[3][0]+needleImageMetaData[5]/2), int(needleImageMetaData[3][1]+needleImageMetaData[6]/2))
        mouse.click("left")

    else:
        tgkRibbonMetaData = search(tagetikRibbon)
        if tgkRibbonMetaData[1] > 0.90:

            mouse.move(int(tgkRibbonMetaData[3][0]+tgkRibbonMetaData[5]/2), int(tgkRibbonMetaData[3][1]+tgkRibbonMetaData[6]/2))
            mouse.click("left")
            time.sleep(0.05)
            needleImageMetaData = search(allNeedleImages[needleImageMetaDataIndex])
            mouse.move(int(needleImageMetaData[3][0]+needleImageMetaData[5]/2), int(needleImageMetaData[3][1]+needleImageMetaData[6]/2))
            mouse.click("left")
        else:
            pass

    mouse.move(initialMousePos[0],initialMousePos[1])

def clickDesign():
    click(0)
def clickNavigation():
    click(1)
def clickDataEntry():
    click(2)
def clickOpenItems():
    click(3)

def kill_script():
    kb.Listener.stop
    print("0")
    sys.exit()

with kb.GlobalHotKeys(
        {'<alt>+<shift>+J': clickDesign,
         '<alt>+<shift>+K': clickNavigation,
         '<alt>+<shift>+L': clickDataEntry,
         '<alt>+<shift>+Ö': clickOpenItems,
         '<alt>+<shift>+Q': kill_script}) as h:
        h.join()

I'd be grateful for all help I can get, thanks in advance!


text:
Q: 'System.Net.FileWebRequest' can not be casted to 'System.Net.HttpWebRequest' on remote machine, but works locally I am getting the error when trying from a server (deployed the same code on the server):

Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.HttpWebRequest'

But when I am trying to use the same code from my local machine, it is not giving error.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

Any idea guys what could be wrong?

A: WebRequest is the type returned by WebRequest.Create() factory method, and is an abstract type.
According to the protocol recognized in the URL string, it returns you a valid subclass, like FileWebRequest or FtpWebRequest.
The problem in your code is that you are trying to create a request for a local file (file://) protocol, so the factory returns FileWebRequest, but you are forcing the code to think it's are remote HTTP URL. Simply wrong.
This explains the fact that it works only with remote and not local files

A: The URI being passed in is not an http URI -- it's either just a path or a file URI.  Ensure the URI starts with http:.  If it's a relative URI, you'll need to make it absolute.


text:
Q: PHP form submits regardless of required/error handling attempts newbie here
I am currently attempting to build a simple contact form to learn how best to build one. I've tried to make several fields required (name, email, do you like spam radio button). The required html5 element isn't working for me or I am not implementing it correctly based on what i've read here, on google and other places. Likewise the error/require messages don't display if someone attempts to submit a message. Instead the form goes through on submit even if NO content anywhere has been entered. I built this yesterday and have been working on the errors for about 24 hours now and am hoping to find some help here.
I currently am returning no errors, the form sends all information entered as hoped, but it also sends if NO information is entered and that doesn't seem like the best possible form to me. I've tried to build a function to help the required, but that doesn't seem to be working either.
Again, i'm new so if my mistakes are obvious and silly, please help em to understand them, that would be greatly appreciated.
current example can be found here
My code:

 <?php
//template.php
include '_inc/config.php';//holds arrays, et al.
include '_inc/functions.php';//holds functions that call arrays, etc

include '_inc/head.php';//Begin Document

//include '_inc/header.php';//Begin Content
?>

<?=NAME_SITE?>

Spam Survey

<?php
 $to = "chezshire@gmail.com";
 $subject="Spam Survey";

//----- end conf ----- //

// define variables and set to empty values
 $nameErr = $emailErr = $spamErr = "";
 $userName = $userEmail = $userMessage = $website = "";

 if ($_SERVER["REQUEST_METHOD"] == "POST")
{
  if (empty($_POST["userName"]))
    {$nameErr = "* Name is required";}
  else
    {$name = testInput($_POST["userName"]);}

  if (empty($_POST["userEmail"]))
    {$emailErr = "* Email is required";}
  else
    {$email = testInput($_POST["userEmail"]);}

  if (empty($_POST["spamErr"]))
    {$emailErr = "* You must select an option";}
  else
    {$email = testInput($_POST["userEmail"]);}

  if (empty($_POST["userMessage"]))
    {$comment = "";}
  else
    {$comment = testInput($_POST["userMessage"]);}
}

 if(isset($_POST['userName']))
{//data is submitted, show it
//echo $_POST['userName'];

$text = 'From: ' . $_POST['userName'] . PHP_EOL;
//$text .= $_POST['Comments']; //add on to text
$text .= process_post(); // uses proces_post to handle comments and stuff
$from = $_POST['userEmail'];

/*
echo '
';
var_dump($_POST);
echo '
';
*/

//domain spoofing controls
$headers = 'From: noreply@max-o-matic.com' . PHP_EOL . //from where formhandler sits
   'Reply-To: ' . $from . PHP_EOL . //where replies are to go to
   'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $text, $headers); //from becomes headers

echo '

Thanxs!

RESET

        ';
/*
echo '
';
var_dump($_POST);
echo '
';
*/

}else{//no data, show form

echo '
    <form action="' .  THIS_PAGE . '" method="post">

                <input type="text" class="text" name="userName" placeholder="Name?" required autofocus />
                <?php echo $nameErr;?>

                <input type="text" class="text" name="userEmail" placeholder="Email" required />
                <?php echo $emailErr;?>

                Do you like spam?

                    <input type="radio" name="Please_Spam_Me" value="YES!" required value="1" />Yes

                    <input type="radio" name="Please_Spam_Me" value="NO!" />No

                    <?php echo $spamErr;?>

                How much Spam is too much?

                <input type="checkbox" name="checkbox-group" class="group-required" id="checkbox-group-id" value="6+" >6 or more

                <input type="checkbox" name="checkbox-group" value="2+">2 to 5

                <input type="checkbox" name="checkbox-group" value="Any">ANY

        <input id="website" name="website" type="text" value"Website" />

                <textarea name="userMessage" placeholder="What is your opinion on Spam?"></textarea>

SEND!

                    <input type="submit" />

                    * Please note, instead of a reCaptcha I build my own \'honeypot\' from scratch.

    </form>

';

}

 function testInput($data)
{
 $data = trim($data);
 $data = stripslashes($data);
 $data = htmlspecialchars($data);
 return $data;
}

// this is a function
 function process_post()
{//loop through POST vars and return a single string
$myReturn = ''; //set to initial empty value

foreach($_POST as $varName=> $value)//$_POST is an array

{#loop POST vars to create JS array on the current page - include email
     $strippedVarName = str_replace("_"," ",$varName);#remove underscores
    if(is_array($_POST[$varName]))
     {#checkboxes are arrays, and we need to collapse the array to comma separated string!
         $myReturn .= $strippedVarName . ": " . implode(",",$_POST[$varName]) . PHP_EOL;
     }else{//not an array, create line
         $myReturn .= $strippedVarName . ": " . $value . PHP_EOL;
     }
}
return $myReturn;
}

 include "_inc/footer.php";//End Content/Document
?>

A: If you're trying to use HTML5 stuffs then you need the HTML5 doctype. Place this at the start of your output and see what happens:
<!DOCTYPE html>
Also, typo value"Website" should be value="Website"


text: Q: Imported sharepoint 2007 site to sharepoint 2010 but can't site create site option I imported a sharepoint 2007 site to sharepoint 2010 but under site actions I can't see an option for creating subsites.


text:
Q: Errno 32: Broken pipe when using getMapId() I am reading a large geojson file containing the footprints of thousands of buildings. This file looks like this:
{
  "type":"FeatureCollection",
  "features":
  [
    {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-97.208203,50.90649],[-97.208203,50.906568],[-97.208367,50.906568],[-97.208367,50.90649],[-97.208203,50.90649]]]},"properties":{}},
    {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-97.138545,50.91915],[-97.1387,50.919146],[-97.138692,50.919018],[-97.138537,50.919022],[-97.138545,50.91915]]]},"properties":{}},
    {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-97.106312,50.949822],[-97.106178,50.949845],[-97.106255,50.950025],[-97.106389,50.950002],[-97.106312,50.949822]]]},"properties":{}},
.
.
.
  ]
}

I am reading this file and loading it into a ee.FeatureCollection() with:
import json

# Open file to parse
with open('/content/drive/My Drive/Earthengine/buildings.geojson') as f:
  data = json.load(f)

# Parse each of the polygons to features
polygons = []
for feat in data['features']:
  polygons.append(ee.Feature(feat))

# Create the feature collection
buildings = ee.FeatureCollection(polygons)

But when I try to show these buildings into folium with:
polyImage = ee.Image(0).byte().paint(buildings, 1)
polyImage = polyImage.updateMask(polyImage)

mapid = polyImage.getMapId()
map = folium.Map(location=[38., -100.], zoom_start=5)
folium.TileLayer(
    tiles=EE_TILES.format(**mapid),
    attr='Google Earth Engine',
    overlay=True,
    name='training polygons',
  ).add_to(map)
map.add_child(folium.LayerControl())
map

I get the following error:
---------------------------------------------------------------------------
BrokenPipeError                           Traceback (most recent call last)
<ipython-input-7-3c769c73ff13> in <module>()
      2 polyImage = polyImage.updateMask(polyImage)
      3
----> 4 mapid = polyImage.getMapId()
      5 map = folium.Map(location=[38., -100.], zoom_start=5)
      6 folium.TileLayer(

15 frames
/usr/lib/python3.6/ssl.py in write(self, data)
    640         The 'data' argument must support the buffer interface.
    641         """
--> 642         return self._sslobj.write(data)
    643
    644     def getpeercert(self, binary_form=False):

BrokenPipeError: [Errno 32] Broken pipe

Could this happen because the file is too large? Any way around this problem?

A: I am pretty sure this is happening because Earth Engine is still computing and the connection is closed on the client side after not receiving a response. See this answer for more information on Broken Pipe.
Assuming that you have a lot of polygons, Earth Engine has to construct the polygons and then rasterize them which may not take a lot of compute but can take some time, hence the broken pipe. One way around this would be to save the buildings polygons as an asset and then load the asset to the map directly.
You can export the featureCollection using this syntax:
task = ee.batch.Export.table.toAsset(
  collection=buildings,
  description='my-buildings',
  assetId='users/myusername/buildings'
)
task.start()


text:
Q: EZPLOT tangent curve gets cut off I'm trying to draw a tangent plot using the EZPLOT function.
For some reason the tangent gets cut off on the y axis after a certain value.
Is there a way of setting ezplot's y axis range of drawing?


text:
Q: After npm eject in CRA environment variables receive undefined I started new project with npx create-react-app and after that npm eject. But when everything completed, in the beginning of each file I get this eslint error:
Parsing error: [BABEL] /Users/admin/Desktop/Work/practise/todo-blockchain/scripts/start.js: Using `babel-preset-react-app` requires that you specify `NODE_ENV` or `BABEL_ENV` environment variables. Valid values are "development", "test", and "production". Instead, received: undefined. (While processing: "/Users/admin/Desktop/Work/practise/todo-blockchain/node_modules/babel-preset-react-app/index.js")

I've surfed the net a lot but did not found any answers. I tried to change the babel presets, add plugins but nothing helped.
I'm using MacOS and looking forward to your help
This is my package.json:
{
  "name": "todo-blockchain",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.16.0",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
    "@svgr/webpack": "^5.5.0",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "babel-jest": "^27.4.2",
    "babel-loader": "^8.2.3",
    "babel-plugin-named-asset-import": "^0.3.8",
    "babel-preset-react-app": "^10.0.1",
    "bfj": "^7.0.2",
    "browserslist": "^4.18.1",
    "camelcase": "^6.2.1",
    "case-sensitive-paths-webpack-plugin": "^2.4.0",
    "css-loader": "^6.5.1",
    "css-minimizer-webpack-plugin": "^3.2.0",
    "dotenv": "^10.0.0",
    "dotenv-expand": "^5.1.0",
    "eslint": "^8.3.0",
    "eslint-config-react-app": "^7.0.1",
    "eslint-webpack-plugin": "^3.1.1",
    "file-loader": "^6.2.0",
    "fs-extra": "^10.0.0",
    "html-webpack-plugin": "^5.5.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.4.3",
    "jest-resolve": "^27.4.2",
    "jest-watch-typeahead": "^1.0.0",
    "mini-css-extract-plugin": "^2.4.5",
    "postcss": "^8.4.4",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-loader": "^6.2.1",
    "postcss-normalize": "^10.0.1",
    "postcss-preset-env": "^7.0.1",
    "prompts": "^2.4.2",
    "react": "^18.1.0",
    "react-app-polyfill": "^3.0.0",
    "react-dev-utils": "^12.0.1",
    "react-dom": "^18.1.0",
    "react-refresh": "^0.11.0",
    "resolve": "^1.20.0",
    "resolve-url-loader": "^4.0.0",
    "sass-loader": "^12.3.0",
    "semver": "^7.3.5",
    "source-map-loader": "^3.0.0",
    "style-loader": "^3.3.1",
    "tailwindcss": "^3.0.2",
    "terser-webpack-plugin": "^5.2.5",
    "tonweb": "^0.0.40",
    "web-vitals": "^2.1.4",
    "webpack": "^5.64.4",
    "webpack-dev-server": "^4.6.0",
    "webpack-manifest-plugin": "^4.0.2",
    "workbox-webpack-plugin": "^6.4.1"
  },
  "scripts": {
    "start": " node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "jest": {
    "roots": [
      "<rootDir>/src"
    ],
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom",
    "transform": {
      "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ],
    "resetMocks": true
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  }
}

A: Just to close the question
As mentioned in this link https://github.com/facebook/create-react-app/issues/12070#issuecomment-1086568526
It's an issue related to create-react-app that will probably be fixed in the next version.
Adding the code below to the eslintrc.js resolves the issue for now
"parserOptions": { "babelOptions": { "presets": [ ["babel-preset-react-app", false] ] } }


text:
Q: Measures which are invariant under a group action are unique I am reading about geodesic currents on surfaces, which are measures on the space of geodesic curves on the surface.
The authors use a result that since a particular measure is invariant under a group  action, it is unique up to a scalar. However I cannot find any such result in the literature. Does this result exist?
Here's a specific example, from "Hyperbolic structures on surfaces and geodesic
currents" by Aramayona-Leiniger, pg 29:
"Even without the specific expression for L used in the proof, it is easy to see that $L(E_\delta)$ is a fixed constant multiple of \delta. For this, note that since L is invariant under the action of the entire isometry group of $\mathbb{H}^2$, $\delta\to L(E_\delta)$ defines a measure on any geodesic, and this measure is invariant under any isometry. Therefore, it is a constant multiple of the Lebesgue (length) measure. Because PSL$(2,\mathbb{R})$ acts transitively on the set of geodesics, the constant is independent of the geodesic."
I don't understand why we can say it is some multiple of the Lesbesgue measure. Any help would be greatly appreciated.
Edit: Thanks for the feedback!


text:
Q: Dialog with OK/Cancel behavior in C#/WPF with data binding In my App class, I have a Collection of objects, like this:
(the Collection is in the App class because I need to have access to it application-wide in different windows, etc.)
public partial class App : Application
{
    public ObservableCollection<Person> Persons { get; set; }

    public App()
    {
        Persons = new ObservableCollection<Person>();
        Persons.Add(new Person() { Name = "Tim", Age = 20 });
        Persons.Add(new Person() { Name = "Sarah", Age = 30 });
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

On the main window of the application, there is a ComboBox binding to the Persons Collection:
<ComboBox ItemsSource="{Binding Source={x:Static Application.Current}, Path=Persons}" DisplayMemberPath="Name"/>

Now I want to create a dialog, in which the user is able to add/remove/edit persons with the well known OK/Cancel button behavior. Can this be down easily? One important thing is that the items in the ComboBox must not be affected by the changes the user is making before pressing OK.
Thanks in advance!
Edit: I think I should point out that I don't want to edit a specific person in the dialog, but the whole list of persons.

A: Add and remove are simple enough since it will only happen when you click OK.
For editing, you more options:

*

*Make Person implement IClonable, pass in a cloned copy of the Person you are editing to be bound on the edit form, then switch out the appropriate Person in your Persons collection when you're done.  This makes the edit form less complicated and more WPFey.

*Don't use binding on your edit form, just do a manual synch between the controls and the Person passed in when you're done.  Least WPFey.

*A combination of 1 and 2 - the edit form has properties that mirror the properties of Person and are bound to its controls, then you synch the Person with the form's properties when you're done.


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

A: Вопрос интересный, но не простой.
Посмотрим на процесс загрузки страницы.
Страница состоит из html, картинок и скриптов. И картинки, и скрипты не только грузятся с внешних ресурсов, но и кешируются. Это означает, что при первом заходе по некоторому адресу и при втором заходе по нему же объем загруженного трафика может сильно различаться.
Кроме того, если какой то скрипт закеширован - это означает, что ДРУГАЯ страница, котрая использует его же (jquery, например) уже не будет его выкачивать.
В то же время в характеристиках сетевого интерфейса, который поазывают такие команды как ifconfig - есть счетчики переданного и принятого трафика.
Рассмотрим такую схему: мы для каждого URL запускаем легковесную виртуальную машину с браузером, у которого очищен кеш. И по окончнии загрузки - например, через условные 30 секунд - спрашиваем у сетевого интерфейса внутри виртуалки, сколько трафика было передано и принято.
Тогда цифра, которую покажет команда ifconfig, будет довольно точно показывать максимальный объем трафика, который понадобился для отображения страницы со всеми вложенными элементами.
Идея Вам понятна?
Как это реализовывать?
Опять таки, не самый простой вопрос. Реализация с настоящей вииртуалкой, которая управляется командой virsh - довольно громоздка. Я бы стал копать в сторону докер - контейнера, внутри которого установлен и запускается браузер. Как из контейнера извлечь нужную инфу - ну, это уже дело техники...
Еще одно направление, в котором можно посмотреть - так называемые headless - браузеры, что то вроде selenium. Это штуки, часто используемые в автоматизированном тестировании. При этом они очень точно повторяют работу обычного браузера. Их headlss-ность ("безголовость", отсутствие графического интерфейса) может дать существенную экономию.
Ну и, конечно, возможно - я не совсем правильно или как то слишком однобоко понял вопрос - тогда поправьте меня...
PS после комментария с уточнением вопроса.
Грубо говоря, если при загрузке страницы нажать f12  и зайти на вкладку network браузера - там будут перечислены все загружаемые страницей элементы и их размер. Сложить эти размеры - и будет нужный автору вопроса результат.
Но как бы это автоматизировать?
Кажется, я нашел расширение для хрома, которое делает что то такое. Вот что про него пишут: "Displays HTML, Javascript and CSS sources of a page in a fast and compact way".
Расширения дяя хрома имеют описанный формат. его можно "расковырять" и посмотреть, как там всё считается.
Также, есть еще проект на эту тему.


text:
Q: How to label or plot only the previous nth bar with Pine Script I try to highlight only the previous 5th bar within the Pine Script Editor.
I found the Pine Script always outputs a range of bars from the present like this:
//@version=5
indicator("Previous Day Retrace", overlay = true)
l = label.new(bar_index, close)
label.delete(l[5])

How can I just label or plot only one bar at each time?  Looking for your help

A: You can plot the label at bar_index-4 and then delete upto previous label i.e. b1
//@version=5
indicator("Previous Day Retrace", overlay = true)
l = label.new(bar_index-4, high)
label.delete(l[1])


text:
Q: Name is not defined in Python I'm using Python 2.7.12 and trying this code.
clientNet = []
class Client:
    def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password
        self.session = self.connect()
    def connect(self):
        try:
            s = pxssh.pxssh()
            s.login(self.host, self.user, self.password)
            return s
        except Exception, e:
            print e
            print '[-] Error Connecting'
    def botnetCommand(command):
        for client in clientNet:
            output = client.send_command(command)
            print '[*] Output from ' + client.host
            print '[+] ' + output + '\n'
    def send_command(self, cmd):
        self.session.sendline(cmd)
        self.session.prompt()
        return self.session.before
    def addClient(host, user, password):
        client = Client(host, user, password)
        clientNet.append(client)

addClient('192.168.1.94','root','root')

And
 Traceback (most recent call last):
  File "host.py", line 33, in <module>
    addClient('192.168.1.94','root','root')
NameError: name 'addClient' is not defined

I tried to run Client.addClient(..) but didn't resolve my problem.
I think I need some help to understand this.. How cannot be defined if it is inside of the Class?

A: You need to make an instance of the class to use its methods first:
client = Client('192.168.1.94','root','root')
client.addClient('192.168.1.95','root','root')

Otherwise you could use a static method if you define the method as:
...
@staticmethod
def addClient(host, user, password):
    client = Client(host, user, password)
    clientNet.append(client)

and use it like:
Client.addClient(...)

without having to make an instance.


text:
Q: How do I get the value of the result body rather than full result body in scala spark I have a flask api endpoint that when you query it, response with the following:
{
    "embeddings": [
        [
            0.09660455584526062,
            0.020427927374839783,
            -0.006049016956239939
        ]
    ]
}

I have some code in scala that queries it and extracts the response but it currently gets the whole body like this:

{"embeddings": [[-0.09660455584526062, 0.020427927374839783, -0.006049016956239939]]}

I would just like to extract the body inside the "emdeddings" like:
    [
        [
            0.09660455584526062,
            0.020427927374839783,
            -0.006049016956239939
        ]
    ]

Question is how do I do this:
Code so far:
  def callFlaskApiEndPoint(url: String): String => String = (requestBody: String) => {
    implicit val formats = DefaultFormats

    val formatted_content = "text" -> requestBody
    val jsonData = compact(render(formatted_content))
    try {
      val result = Http(url)
        .postData(jsonData)
        .header("Content-Type", "application/json")
        .header("Charset", "UTF-8")
        .option(HttpOptions.connTimeout(10000))
        .option(HttpOptions.readTimeout(5000))
        .asString

      result.body
      //tried following but not working so commented out
      //(parse(result.body) \\ "embeddings").extract[String]
    } catch {
      case e: Exception => {
        "{}"
      }
    }
  }

A: Try this:
pretty(render(parse(str) \\ "embeddings"))

This gives:
[ [ -0.09660455584526062, 0.020427927374839783, -0.006049016956239939 ] ]


text:
Q: C# Mail - Separate Sender and Return Path I am attempting to set a different return path and sender in the headers to replicate a previous PHP system. It needs to be exactly the same.
When I put in a Sender it sets this to the return path and I can't seem to find a solution to separate these. Also the sender shows as behalf of in the From part of the mail message which I do not want.
Any recommendations?

A: Use:
MailMessage mail = new MailMessage("sender@email.com", "to@email.com");
mail.ReplyToList.Add(new MailAddress("reply@email.com", "reply-to"));

Please note MailMessage.ReplyTo is now obsolete.
Documentation

A: Have a look at the MailMessage.ReplyTo property.

Use the ReplyTo property to indicate an address other than the From address to use to reply to this message.

A: I used the MailKit library to solve my issue.
This allows you to specify a different sender at server level


text:
Q: How to calculate the X distance while Z object is moving top to bottom? First of all, sorry for my extremely low knowledge about mathematics. All i am able to do is this image which describe the problem.
Image of triangle + information
I want to know that how can i calculate the X distance each time while Z object is moving continuously from top to bottom.
Note: This is not an assignment.

A: Note that $$AB^2+BC^2=(18-6)^2+(16-10)^2=AC^2$$
So $\triangle ABC$ is a right-angled triangle.
Let the smaller triangle be $\triangle ADE$. It is obvious that $\triangle ADE\sim \triangle ABC$($\because AAA$).
Similar triangles have the same ratio for every pairs of sides. In this problem,
$$\frac{DE}{BC}=\frac{AZ}{AB}$$
Let $Z=(10,a)$, $6\le a\le 18$. We have
$$\frac{x}{6}=\frac{a-6}{12}$$
$$x=\frac{a-6}2$$


text:
Q: Declaring var inside Javascript for loop declaration I'm sure I've read a discussion on SO about this but can't find it. Simply, are there cons to declaring a for loop's increment inside the loop's declaration? What is the difference between this:
function foo() {
    for (var i=0; i<7; i++) {
        // code
    }
}

...and this:
function foo() {
    var i;
    for (i=0; i<7; i++) {
        // code
    }
}

Since JS has function scope, either should be fine, right? Are there edge cases where the former approach would cause problems?
If they are identical, why is Crockford/JSLint all, "No way dawg," about it?

A: The problem with declaring with var in the loop header is that it's deceptive.  It looks like you're declaring a variable whose scope is limited to the for loop, when it actually exists everywhere within the function - including before the declaration:
var i = 1;
function foo() {
   console.log(i);                     // 'undefined'
   for (var i=1; i<100; ++i) {
   }
}

Even though the console.log call occurs before the declaration of the local i, it is still in scope for it because it's inside the same function. So the local i, which has not yet had any value assigned to it, is what gets passed to log. This can be surprising; it's certainly not obvious to anyone who's not familiar with Javascript scoping rules.
Starting with ECMAScript 2015, there is a better way to declare variables: let. Variables declared with let are local to the block containing them, not the entire function. So this version of the above code will print 1 as intended:
let i=1; // could use var here; no practical difference at outermost scope
function foo() {
  console.log(i);               // 1
  for (let i=1; i<100; ++i) {
  }
}

So best practice in modern Javascript is to declare variables with let instead of var.  However, if you are stuck with a pre-ECMAScript 2015 implementation, it's a little less confusing to declare all variables at the top of the function, rather than waiting till first use.

A: These are exactly the same.  All local variables in javascript have function scope which means they are alive for the entire function they are declared in.  This is often counter intuitive at first as most curly brace languages scope the life time of the variable to the block they are declared in.
A portion of Javascript developers very much prefer the second form.  The rationale is that since all variables have function scope, you should declare them at the function level to make the life time explicit even for those not familiar with Javascript.  This is just a style though and by no means a hard rule
EDIT
Note that with the introduction of ES6 let, you can now use let inside your loop for real block-scoped variable more details
for(let i = 1; i <= 5; i++) {
   setTimeout(function(){
       console.log('Value of i : ' + i);
   },100);
}

A: There's no difference, but I prefer the second way (per Crockford) because it explicitly shows that the variable to available outside of the for loop:
function() {
    for(var i=0; i<7; i++) {
        // code
    }

    // i is still in scope here and has value 7
}

A: Those are both exactly the same thing.

A: The two code block are identical. The first statement of the for loop is executed before the for loop starts, the loop is running while the second statement is true, and the third statement is run every time the loop iterates once.
This means that
for(var i = 0; i < 8; i++) {
    //some Code
}

is identical to
var i = 0;
for(;i < 8;) {
    //some Code
    i++;
}

(The semicolon following the ( is to tell the computer that i < 8 is actually the second statement, not the first).


text:
Q: How to remove minutes button from Materual UI datetime picker I am trying to customize a datetimepicker of materialUI in ReactJS. I do not want the user to be able to see or select minutes in the picker. I have set the views prop to year month date and hours but the user can still click on minutes from the toolbar. How can I hide minutes from the toolbar. This is the code for the component
<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <DateTimePicker
    required
    label="Start Date and Time"
    inputVariant="outlined"
    value={SelectedFromDate}
    onChange={(value) => handleSelectedFromDate(value)}
    fullWidth
    margin="dense"
    disablePast
    format="do MMMM yyyy HH:mm"
    openTo={'year'}
    views={['year', 'month', 'date', 'hours',]}
    ampm={false}
    allowKeyboardControl={true}
    hideTabs
    disableToolbar={false}
    minutesStep={60}
    disabled={!(checkName && checkFile)}
    />
</MuiPickersUtilsProvider>

and this is how it looks currently

A: I think format is a problem. Can you try changing:
format="do MMMM yyyy HH:mm"

to:
format="do MMMM yyyy HH"


text:
Q: sql query times out...case / if / what to do I have the following sql server sproc:
PROCEDURE [dbo].[GetSoftwareProgramsGrid]
    @SoftwareTitle varchar(1000)='All',
    @CategoryID varchar(100)='All',
    @ManufacturerID varchar(50)='All',
    @ModelID int=0, -- 0 means all
    @AssetID int=0, -- 0 means all
    @AssetStatus int=0, --0 is active, 1 is inactive, and 2 is all
    @Status int=0, --0 is active, 1 is inactive, and 2 is all
    @Type varchar(100)='All',
    @Site varchar(100)='All',
    @Department varchar(100)='All',
    @Manager varchar(100)='All',
    @Employee varchar(100)='All',
    @SortExpression varchar(100)='Software',
    @SortOrder int=0
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

SELECT
*
FROM
(
    SELECT DISTINCT
        Program AS Software
    FROM
        AssetProgram ap
    LEFT JOIN
        AssetAssignment aa
    ON
        aa.AssetID = ap.AssetID
    LEFT JOIN
        [MyLinkedServer].MyDB.dbo.Login l
    ON
        l.LoginID = aa.LoginID
    LEFT JOIN
        Asset a
    ON
        a.AssetID = ap.AssetID
    INNER JOIN Model m
    ON
        a.ModelID = m.ModelID
    INNER JOIN
        Category c
    ON
        c.CategoryID = m.CategoryID
    INNER JOIN Manufacturer ma
    ON
        ma.ManufacturerID = m.ManufacturerID
    WHERE
        (
            --Software filters
            (ap.Program = @SoftwareTitle OR @SoftwareTitle='All')

            --Asset filters
            AND (c.CategoryID = @CategoryID OR @CategoryID='All')   --filter category
            AND (ma.ManufacturerID = @ManufacturerID OR @ManufacturerID='All') --filter manufacturer
            AND (m.ModelID = @ModelID OR @ModelID = 0)  --filter model
            AND (a.AssetID = @AssetID OR @AssetID = 0)  --filter by asset name (the actual asset id)
            AND (((a.Inactive=@AssetStatus) OR (@AssetStatus=2)))
            AND (aa.Inactive=0)
            AND (ap.Inactive=0)

            --Employee filters
            /*AND ((l.Inactive=@Status) OR (@Status=2)) --status of employee 2 is all, 1 is inactive, and 0 is active

            AND (@Type='All' OR (@Type='Contractor' AND l.IsContractor=1) OR (@Type='Regular' AND l.IsContractor=0))    --contractor or regular employee
            AND (@Site='All' OR @Site=l.ClientID)   --the site
            AND (@Department='All' OR @Department=l.FunctionalGroupID)  --the department
            AND ((l.Manager = @Manager OR l.FullName=@Manager) OR @Manager='All')   --the manager
            AND (l.FullName = @Employee OR @Employee='All') --the employee
            */
        )) ttt
ORDER BY
            CASE WHEN @SortExpression='Software' AND @SortOrder=0 THEN Software END ASC,
            CASE WHEN @SortExpression='Software' AND @SortOrder=1 THEN Software END DESC

This query has to include a linked server, due to our setup.  The query runs fine and is fast as long as I comment out my employee parameters, namely this section:
--Employee filters
                /*AND ((l.Inactive=@Status) OR (@Status=2)) --status of employee 2 is all, 1 is inactive, and 0 is active

                AND (@Type='All' OR (@Type='Contractor' AND l.IsContractor=1) OR (@Type='Regular' AND l.IsContractor=0))    --contractor or regular employee
                AND (@Site='All' OR @Site=l.ClientID)   --the site
                AND (@Department='All' OR @Department=l.FunctionalGroupID)  --the department
                AND ((l.Manager = @Manager OR l.FullName=@Manager) OR @Manager='All')   --the manager
                AND (l.FullName = @Employee OR @Employee='All') --the employee
                */

The minute I bring even the first line of that section in, for example just this one:
AND ((l.Inactive=@Status) OR (@Status=2))
The entire sproc hangs (times out)....I've properly indexed my tables and I even have an index on the Inactive field within my linked table...If I take that same line above and just say:
AND (l.Inactive=0)
It runs fine, so the OR condition is causing it (boolean).  However, I need this condition as a parameter is passed that needs to be satisfied.  What are my other options, do I have to IF BEGIN... using all these parameters?  It seems cumbersome...For anyones information the AssetProgram table has a total of 50k rows, so that isn't too much.

A: yeah your where clause is crazy, specially with all the "OR"s
try to load your "users" into a temp table (or var table) based on the @Status variable (if it is 1 you load only inactive, if it is 0 you load only actives and so on...) and use the temp table on the join, that will drastically decrease the number of comparisons.


text:
Q: How do I create a multi line text box in asp.net mvc? How do I create a multi line text box in asp.net mvc?
Probably not specific to asp.net mvc but it is what I am using.
Here is what I have.
<%: Html.TextBox("CommentToAdd", null, new
{
@class = "input-medium",
TextMode = "MultiLine",
Columns = "55",
Rows = "10",
type = "text",
required = "required"
})%>

A: I think multiline textbox in MVC is textarea
<%= Html.TextArea("Body", null, new { cols = "55", rows = "10" }) %>

or
<%= Html.TextAreaFor(x => x.Body, 10, 55, null) %>

A: just add this attribute to property.
  [DataType(DataType.MultilineText)]
   public string CommentsToAdd{ get; set; }

A: A multiline textbox is just a textarea.
Any one of these should work.
<%= Html.TextArea("Body", null, new { cols = "100", rows = "5" }) %>

<%= Html.TextArea("Body", null, 5, 100, null) %>

<%= Html.TextAreaFor(x => x.Body, 5, 100, null) %>

A: You want to use a text area, not a text box. Use TextAreaFor to bind it to your model, otherwise use TextArea
<%= Html.TextAreaFor(e => e.CommentsToAdd, 10, 55, null) %>
<%= Html.TextArea("CommentsToAdd", string.Empty, 10, 55, null) %>

Using razor:
@Html.TextAreaFor(e => e.CommentsToAdd, 10, 55, null)
@Html.TextArea("CommentsToAdd", string.Empty, 10, 55, null)

This will be rendered as a <textarea> (multi-line) instead of an <input type="text" /> (single line).


text:
Q: Irreducible action of a solvable ideal in $\mathfrak{gl}(n)$ implies that the ideal has only scalar matrices
Let $\mathfrak{g} \subset \mathfrak{gl}(n)$ a Lie algebra with irreducible action on $\mathbb{C}^n$ and let $a \subset \mathfrak{g}$ a solvable ideal. Prove that $a \subset \mathbb{C} Id$.

First, I observed that by Lie theorem, modulo a change of basis, $a$ is made of upper triangular matrices. Then, I showed that all strictly upper triangular matrices lead to a subrepresentation of $\mathbb{C}^n$ which is isomorphic to $\mathbb{C}^{n-1}$, so the only possibility is that $a$ is made of only scalar matrices. Is that correct?
I am not sure if I should be more formal in proving that strictly upper triangular matrices lead to $\mathbb{C}^{n-1}$: the way I showed it is by observing that any strictly upper triangular matrix when multiplied by a vector in $\mathbb{C}^{n}$ always annihilates the last component of the vector.


text:
Q: pandas reshaping/transform the dataframe I have dataframe df:
col_name    col_month   col_value
abc         2021-01-31  233
abc         2021-02-28  784
abc         2021-03-31  7868
def         2021-02-28  3652
def         2021-03-31  344
def         2021-04-30  87

I need the result as:
col_name    NAME        col1          col2            col3
abc         col_month   2021-01-31    2021-02-28      2021-03-31
abc         col_value   233           784             7868
def         col_month   2021-02-28    2021-03-31      2021-04-30
def         col_value   3652          344             87

what i have tried so far using melt:
pd.melt(df, id_vars=['col_name'], var_name = 'NAME', value_name = 'VALUE')
this give the result:
col_name    NAME        VALUE
abc     col_month   2021-01-31
abc     col_month   2021-02-28
abc     col_month   2021-03-31
def     col_month   2021-02-28
def     col_month   2021-03-31
def     col_month   2021-04-30
abc     col_value   233
abc     col_value   784
abc     col_value   7868
def     col_value   3652
def     col_value   344
def     col_value   87

but i am not still able to get the desired result

A: Here's another way:
df.assign(cols=df.groupby('col_name').cumcount()+1)\
  .set_index(['col_name','cols'])\
  .rename_axis('NAME', axis=1)\
  .stack().unstack(1)\
  .add_prefix('col')\
  .reset_index()

Output:
cols col_name       NAME        col1        col2        col3
0         abc  col_month  2021-01-31  2021-02-28  2021-03-31
1         abc  col_value         233         784        7868
2         def  col_month  2021-02-28  2021-03-31  2021-04-30
3         def  col_value        3652         344          87

Or with, melt:
df.assign(cols=df.groupby('col_name').cumcount()+1)\
  .melt(['col_name', 'cols'], var_name='NAME')\
  .set_index(['col_name', 'NAME', 'cols'])\
  .unstack()['value'].add_prefix('col')\
  .reset_index()

A: Try using groupby and T:
>>> df.groupby('col_name').apply(lambda x: x.drop('col_name', axis=1).reset_index(drop=True).T.rename_axis(index='NAME')).rename(lambda x: f'col{x + 1}', axis=1).reset_index()
  col_name       NAME        col1        col2        col3
0      abc  col_month  2021-01-31  2021-02-28  2021-03-31
1      abc  col_value         233         784        7868
2      def  col_month  2021-02-28  2021-03-31  2021-04-30
3      def  col_value        3652         344          87
>>>

Or try melt with pivot_table:
>>> x = df.melt('col_name')
>>> d = {'': ['col_name', 'NAME']}
>>> x.assign(idx=x.groupby(['col_name', 'variable']).cumcount()).pivot_table(index=['col_name', 'variable'], columns='idx', aggfunc=sum).reset_index().droplevel(0, axis=1).rename_axis(columns=None).rename(lambda x: f'col{x + 1}' if isinstance(x, int) else x, axis=1).rename(columns=lambda x: d.get(x, [x]).pop(0))
  col_name       NAME        col1        col2        col3
0      abc  col_month  2021-01-31  2021-02-28  2021-03-31
1      abc  col_value         233         784        7868
2      def  col_month  2021-02-28  2021-03-31  2021-04-30
3      def  col_value        3652         344          87
>>>

A: Another approach to use melt, groupby and apply:
(
    df.melt('col_name',var_name='NAME')
    .groupby(['col_name','NAME'])
    .value.apply(list)
    .apply(pd.Series)
    .rename(columns = lambda x: f'col{x+1}')
    .reset_index()
)

If the dataset is large, use this version as pd.Series can be slow on large dataset.
(
    df.melt('col_name',var_name='NAME')
    .groupby(['col_name','NAME'])
    .value.apply(list)
    .pipe(lambda x: pd.DataFrame(index=x.index, data=x.tolist()))
    .rename(columns = lambda x: f'col{x+1}')
    .reset_index()
)


text:
Q: Ruby Rails rake db migrate not working or schema file not updating So I created a new table on schema.rb
here is the new code line i put:
  create_table "book", :force => true do |t|
    t.integer  "user_id"
    t.string   "title"
    t.integer   "count"
  end

but after when i run rake db:migrate command schema.rb turns into old file, when i open it my new create_table code just gone any ideas? im new to ruby rails Thanks!
i tried this too:
rake db:drop:all
rake db:create:all
rake db:migrate

but still schema.rb file not updating into new one.

A: That schema.rb file is generated, and any change you make in it will go away the next time it's generated. The normal way to make database changes in Rails is with migrations.

A: Never edit your schema.rb directly.
schema.rb is auto-generated from the current state of the database.
You should create a migration file for doing this.
Read Active Record Migrations.

A: You need to use a migration rather than modifying the schema directly.  You should NEVER modify the schema.rb file directly, since the next time you migrate, it will be overwritten.  Rails generates the schema file.  Try the following in the terminal:
rails generate model Book user_id:integer title:text count:integer

and then run:
rake db:migrate

This should fix your issues. You are now allowing rails to make the model for you (this generates a migration to make the new model), and then migrating it changes the database tables.  Take a look at your schema.rb file afterwords, and it should look correct.
For more info on model generators, take a look here.


text:
Q: Extracting field from multiline text that is piped into Perl I would like to extract a number (7, in this example) from input of the following kind:
 received_tli
--------------
            7
(1 row)

I've seen recipes for the case where the multi-line string exists as a Perl variable. However, I would prefer invoking the expression like this:
psql -c "SELECT received_tli FROM pg_stat_wal_receiver" | \
  perl -e 'print $1 if /<expression>/'

I've tried e.g. \s^received_tli\s*\n-+\n\s*([0-9])+\s*\n(1 row) as expression, but this does not seem to work. How can I parse multiline input that is piped into Perl with a (multiline) regular expression?

A: The problem you're having with your perl -e is that at no point are you reading STDIN, and thus perl isn't 'seeing' your data.
You can use -ne which tells perl to wrap your snippet in a while ( <> ) { } loop. That's maybe of limited use though, because it's working line by line.
So then you need to set the 'end of line delimiter' (-0 flag) and then apply your regex:
perl -0777 -ne 'print $1 if m/received_tli\D*(\d+)/'

Or written in a longer perl script (but hopefully more readable):
#!/usr/bin/perl
use strict;
use warnings;

local $/;
while (<>) {
   print $1,"\n" if m/received_tli\D*(\d+)/;
}

A: There is no need to involve Perl at all. Just use the -t or --tuples-only option in psql:
psql -t -c "SELECT received_tli FROM pg_stat_wal_receiver"

A: From your sample data, it looks like you want the integer on lines that only contain that integer and some white space. So something like this will work:
#!/usr/bin/perl

use strict;
use warnings;

while (<>) {
  /^\s*(\d+)\s*$/ and print $1;
}

You can put that in a file, make it executable and then run it using:
$ psql ... | your_extract_program

But if you really want to retype the Perl code every time, you could use:
$ psql ... | perl -n -e 'print $1 if /^\s*(\d+)\s*$/'


text:
Q: JavaScript why doesn't return exit the encompassing function call? so I'm pretty new to JS and coming from a background of C++ this language really confuses me. I'm having an issue understanding how the return statement and the if/else statements actually function in the code below:
makeGroup= (formGroup) => {
     //checking for duplicate users
    existsInDatabase(this.context.user, formGroup.name).then(
        (result) => {
            if(result != null){
                if(result.group !== formGroup.group){
                    this.setState({
                        showAlert: true,
                        //alert message
                    });
                    return;
                }
            }
        }
    )

    if(this.state.showAlert == true){
        console.log("test");
        return;
    }

    else if (/*group has no members*/) {
        this.setState({
           showAlert: true,
           //alert message
        });
        return;
    }

    else{
        //do something
    }
}

In this code, the program enters the first if statement and prints out "test" to the console as expected. However, it doesn't return and just exit the function. Instead, it moves to the else if statement, executes it, and then moves on to the else statement. First of all, why didn't the initial return statement just straight up exit the function??? If the if statement evaluates to false and the else if statement is true, the return statement exists the function as expected?? Also, why does it move onto the else if and then the else statement if the if statement has already been executed?
I'm stumped.


text:
Q: What adhesive is best to glue strain gauges to metal? I'm trying to use these strain gauges to measure bending of a metallic cantilever (metal TBD). Does anyone know what adhesive I can use to glue the strain gauges? I'd rather not have to use an oven for curation, unless it is my very last resort.
Thanks in advance!

A: I have experience with two-component HBM X60 glue specially made for strain gauges. It's quite expensive, but i can tell, it withstands a lot.
But in general, i would say that any kind of fast cyanoacrylic glue would suit your needs. I have tried 350 ohm, one axis strain gauges with cheap cyanoacrylic glues which you can get on every corner, and it worked well.


text:
Q: get records from current date mongodb I am new at mongodb can someone help me to current my mongodb query,
I want to find date with current date from child object
my query is like
db.users.find({"date.feeReminderDate": {"$gte":new Date("2017-06-28T18:30:00.000Z")} })

A: You can find record of current date/today's date by
db.users.find({"date.feeReminderDate": {$gte: ISODate("2017-07-03T00:00:00Z"), $lt: ISODate("2017-07-03T23:59:59Z")}});


text:
Q: Pycharm ignores new virtual environment after moving existing one or deleting and creating a new one If I allow PyCharm to create a virtual environment when creating the project, then delete or move the venv folder, it won't let me select a new one. I can go into the Python Interpreter menu in the settings and select an existing one that I created myself (note /brokenInterpreter/oldFolder/venv vs /brokenInterpreter/venv):

But nothing happens when I hit "Ok" in the "Add Python Interpreter" dialog. It simply ignores what I entered. When I exit out, PyCharm still attempts to use the old, non-existant interpreter.
How can I get around this?

PyCharm version: 2022.2 Build #PY-222.3345.131, built on July 27, 2022 (Professional Edition)

A: I think this is a bug, but I'll document the fix here.
I had to go into the "Show All" menu, and find the old "[invalid]" entry:

Then once that's removed from the list using the - button, I was able to add the new interpreter.


text:
Q: fatal error: unexpectedly found nil , I define a gesture, this method is the method of gesture binding //fatal error: unexpectedly found nil while unwrapping an Optional value
    let translationInContainerView = gesture.translation(in: transitionContainerView!)

Occasionally crash,not every time.
I want to catch this exception,in the case of such a situation(found nil),don't want the program to crash,who can tell me how to solve this problem.

I try this,but no use:

A: Try this:
guard let transitionContainerView = self.transitionContext?.containerView else {
    print("the containerView of transitionContext is nil. Find out why.")
    return
}

You might need to cast the transitionContainerView object with a specific type. I don't know what the type is supposed to be but it would look something like this:
guard let transitionContainerView = self.transitionContext?.containerView as? MyValueType else {
    print("the containerView of transitionContext is nil. Find out why.")
    return
}

The addition here is the as? MyValueType portion
If you don't hit the code block within the else statement, then it is not nil and you should be able to use your object accordingly. I hope this helps!


text:
Q: How to SELECT DISTINCT on 1 key column when querying multiple columns I am working in SQL Server 2008 R2.  I have a table in which 1 "record" is actually several records due to one of its fields having different values.  This table has a lot of fields itself.  All of the fields for a given "record" will have the same value, except for the one field that has various values.  I want to query all records and return all fields, but I want only 1 instance (the first one) of each "record".  For example, my table looks like:
Field 1    Field 2       Field 3
value a    value x       value 1
value a    value x       value 2
value a    value x       value 3
value b    value y       value 20
value b    value y       value 21
value b    value y       value 22

I want my query to return something like:
Field 1    Field 2       Field 3
value a    value x       value 1
value b    value y       value 20

So, my Field 1 is my key.  Normally, I would just do a SELECT DISTINCT.  However, since I want all fields to return in the query, the DISTINCT will apply to all of the fields in the SELECT, which means that all records will return, rather than just 1 for each key.  What is the best way of accomplishing this?

A: SELECT t.field1,t.field2,t.field3 FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION by Field1 ORDER BY Field1) AS RowNumber
FROM mytable
) t
WHERE t.RowNumber = 1

This method only looks at the distinct aspect of the first column. Order is not guaranteed in SQL. You can set how you define your "First Row" with the "ORDER BY" section of the above code.

A: Supposing you want the minimum value from Field 3:
SELECT [Field 1], [Field 2], MIN([Field 3])
FROM YourTable
GROUP BY [Field 1], [Field 2]

A: You'll want to group by Field 1 & Field 2 and then take the min of Field 3.
select      [Field 1],
            [Field 2],
            MIN([Field 3]) as [Field 3]
from        [SomeTable]
group by    [Field 1], [Field 2]

A: You can use Group By over field 1 and field 2;


text:
Q: QMake message not printing All, I am attempting to work with a monolithic build system given to me by someone else (isn't that always the case?) and wanted to add some debug statements for myself.
The main .pro file uses a subdir template with the concept of:
SUBDIRS += durp-dir

durp-dir.file = Durp/durp.pro

When I add a message("In Durp") to durp.pro it never gets printed. I can't figure out what I'm missing. I'm using QT 4.8 ... Still examining the qmake documentation with no leads.

A: Run qmake -r instead of just qmake


text:
Q: JS how to get the substring between two identical string character I know to get a substring between 2 characters we can do something like myString.substring(myString.lastIndexOf("targetChar") + 1, myString.lastIndexOf("targetChar"));
But how would I get a substring if the two targetChar are the same. For example, if I have something like const myString = "/theResultSubstring/somethingElse", how would I extract theResultSubstring in this case?

A: You could use String#match instead with following regex and positive & negative lookaheads.

const myString = "/theResultSubstring/somethingElse";

const res = myString.match(/(?!\/)\w+(?=\/)/)[0];

console.log(res);

A: Do indexOf and lastIndexOf if there are only two characters in your string:

const myString = "/theResultSubstring/somethingElse";
const subString = myString.substring(myString.indexOf("/") + 1, myString.lastIndexOf("/"));

console.log(subString);

Or split it:

const myString = "/theResultSubstring/somethingElse";
const subString = myString.split("/")[1];

console.log(subString);


text:
Q: Contar o numero de caracteres e inserir um novo em uma determinada posição, em uma string? Tenho as duas strings:
String num_tel1 = "03184872882" e a String num_tel2 = "84872882". Elas tem 11 e 8 caracteres, respectivamente. Como faço para contar esta quantidade de caracteres e, se tiver uma String com 11 caracteres (num_tel1), inserir o número 9, logo após o 031 e, se tiver 8 caracteres, inserir o numero 9, na primeira posição, ou seja, antes do primeiro 8 (num_tel2)?

A: Você pode utilizar o método StringBuilder::Insert para inserir o número 9 na posição que você quer de acordo com o tamanho da sua String.
Podemos fazer assim:
public static void main(String[] args) {
  System.out.println(formatString("03184872882"));
  System.out.println(formatString("84872882"));
}

public static String formatString(String s) {
  StringBuilder sBuilder = new StringBuilder(s);
  sBuilder.insert(s.length() == 11 ? 3 : 0, "9");
  return sBuilder.toString();
}

Output:
031984872882
984872882

Veja que eu utilizei um operador ternário para inserir o número 9 na posição correta de acordo com o tamanho da string. Basicamente, o operador ternário faz isso:
if(s.length() == 11) sBuilder.insert(3, "9"); // Insere o número 9 na quarta posição da `String`, depois do DDD.
else sBuilder.insert(0, "9"); // Insere o número na primeira posição da string.

A: Eu tenho uma função que sempre uso, que é pra validar telefone. Vou colocar aqui o que precisa pra ela funcionar que eu vou tentar te dar uma luz. No caso está tudo static porque é uma classe Util que eu tenho. Modifiquei ela para seu caso blz:
public static final String TELEFONE_REGEX = "([0-9]{4}[0-9]{3}[1-9]9?(\\d{2})?).*";

public static String getTelefone(String telefone, Context context) {
        Pattern phoneRegex = Pattern.compile(TELEFONE_REGEX);

        telefone = reverseStr(telefone.replaceAll("\\D", ""));

        Matcher m = phoneRegex.matcher(telefone);

        if (m.matches())
            telefone = m.group(1);

        telefone = reverseStr(telefone);

        if (telefone.length() == 8)
            telefone = "9" + telefone;
        if (telefone.length() == 11)
            telefone = telefone.substring(0,3) + "9" + telefone.substring(3, telefone.length()-1);

        return telefone;
    }

public static String reverseStr(String input) {
        String output = "";
        for (int i = input.length() - 1; i >= 0; i--) output += input.charAt(i);
        return output;
    }

Essa função valida se o input é um telefone mesmo, e verifica de forma inversa.


text:
Q: Redux Form: Conditional form validations with multiple submit buttons
I am using Redux forms with multiple submit buttons along with redux-form <Field />. I need to control the validation of these fields based on click of these buttons. For ex. I need to set a flag to True/False based on click of these buttons so that I can conditionally validate my fields like below:
        <Field
          name="date"
          component={DateFormField}
          validate={isSaveDraft && [validateRequiredText]}
          floatingLabelText="Date"
          fullWidth
          helpText="blablabla"
        />
        <Field
          name="title"
          component={TextFormField}
          normalizeOnBlur={normalizeTextOnBlur}
          validate={!isSaveDraft && [validateRequiredText]}
          floatingLabelText="Project title"
          fullWidth
          helpText="blablabla"
        />

As you can see from above code, I'm conditionally validating my fields with validate={isSaveDraft && [validateRequiredText]} and validate={!isSaveDraft && [validateRequiredText]}
Here are my two submit buttons:
      <RaisedButton
        label={submitting ? 'Saving Draft...' : 'Save Draft'}
        type="button"
        onClick={handleSubmit(values => onSubmit())}
        disabled={submitting}
        primary
      />
    <RaisedButton
      label={submitting ? 'Submitting Brief...' : 'Submit Brief'}
      type="button"
      onClick={handleSubmit(values => onSubmit())}
      disabled={submitting}
      primary
    />

However, I'm not able to achieve it. Please help.

A: After a lot of headaches and head scratching, I've finally found the solution without making things look ugly. Thanks to a fellow developer for this solution. Original idea was to set a flag on click of the button and conditionally validate the fields. (PS: I'm using Field Level Validations). However, the issue was that the validations are being executed BEFORE the flag setting as the onClick handler wouldn't fire before all the validations are fixed and that logic is buried deep inside redux-forms (perks of unnecessarily overcomplicating simple things by using a library).
Here is the solution:
submit handler
handleSubmit() {
    const { bookingCreate, modalShow, navigateTo } = this.props;
    const { isDraftAction } = this.state; // my flag

    // create record!
    return bookingCreate(isDraftAction)
      .then(responsePayload => {
        ...
      })
      .catch(handleSubmissionError);
 }

isDraftAction is the flag which is set (in local state) when the action is called on onClick of both buttons.
My conditional Field level validations
    <Field
      name="date"
      component={DateFormField}
      validate={isDraftAction && [validateRequiredText]}
      fullWidth
      helpText="blablabla"
    />
    <Field
      name="title"
      component={TextFormField}
      normalizeOnBlur={normalizeTextOnBlur}
      validate={!isDraftAction && [validateRequiredText]}
      fullWidth
      helpText="blablabla"
    />

My 2 buttons for SAVE RECORD and SUBMIT RECORD.
  const submit = handleSubmit(values => onSubmit()); // this is redux-form's submit handler which will in-turn call my own submit handler defined above. (That's where the library hides all the logic and makes developer helpless)

  <RaisedButton
    label={submitting && isDraft ? 'Saving Draft...' : 'Save Draft'}
    type="button"
    onClick={() => {
      this.props.dispatchAction({ draftAction: true }).then(() => {
        submit();
      });
    }}
    disabled={submitting}
    primary
  />
  <RaisedButton
    label={submitting && !isDraft ? 'Submitting Brief...' : 'Submit Brief'}
    type="button"
    onClick={() => {
      this.props.dispatchAction({ draftAction: false }).then(() => {
        submit();
      });
    }}
    disabled={submitting}
    primary
  />

dispatchAction() is my action function which will FIRST set the flag to true/false THEN call redux-forms inbuilt submit handler. Also, I've extracted the redux-form's submit handler as it is above only for more clarity.
dispatchAction()
     dispatchAction={({ draftAction }) =>
        new Promise(resolve => {
          this.setState({ isDraftAction: draftAction }, resolve);
        })
      }

A: use a state variable as isSaveDraft and set it default to false
Add onClick action of button to set state.isSaveDraft = true

A: validate={(isSaveDraft && [validateRequiredText]} will not work since validate expects a function all the time. Also, field level validation happens onTouch, or onBlur etc. which is way too early as you won't know which button will be clicked.
What you need to do is use a extra flag prop to hold which button was clicked and then use that in the form level validation.
So your Fields will look like this (no more Field level validation):
<Field
    name="date"
    component={DateFormField}
    floatingLabelText="Date"
    fullWidth
    helpText="blablabla"
/>
...
<RaisedButton
    label={submitting ? 'Saving Draft...' : 'Save Draft'}
    onMouseDown={() => this.setDraftFlag(true)}
    ...
/>
<RaisedButton
    label={submitting ? 'Submitting Brief...' : 'Submit Brief'}
    onMouseDown={() => this.setDraftFlag(false)}
    ...
/>

I'm using onMouseDown to capture the flag since you're already using onClick for submitting the form. Besides, we need to do the validation before submit anyway.
And then in your form's validate (based on SyncValidation example)
const validate = values => {
    const errors = {}
    const {isDraft, ...rest} = values

    if(isDraft) {
        // draft validations
    } else {
        // other validations
    }
    return errors
}

export default reduxForm({
    form: 'myForm', // a unique identifier for this form
    validate, // <--- validation function given to redux-form
})(MyForm)

setDraftFlag can be an action or you can make it part of your Form component like so (I find this easier since you already get change bound to your form):
setDraftFlag(value) {
    this.props.change('isDraft', value));
}


text:
Q: initMap is not a function in using google maps API

I'm new to scripting . This is my code to display the map. But it throws an uncaught error "initMap is not a function". Can anyone help ??

A: Late late answer but you might want to check this answer. The main problem is that you are not putting the script after defining the map. Code simply is looking for a web element before it's created on the page.

A: Rename showMap to initMap. Google is expecting to call a function named initMap because of the callback=initMap URL parameter you've passed them when loading in the Maps API.  But you don't have a function with that name, you've only got a function called showMap.
Also, by specifying that callback parameter, you don't need to then explicitly call initMap  or showMap yourself.  So remove onload="initMap()" from the  tag.
Also, when you load in the Maps API, you've got a typo in the URL, instead of:
jskey=YOUR_API_KEY

it should be:
js?key=YOUR_API_KEY

And finally, you're missing any  section, which I've added, and I've moved the function into the  so it should be defined by the time the callback function gets called.
So this should work:

A: Moving the google.map API call

after function initMap() is defined fixed this problem for me. I guess Javasrcipt runs sequentially so it can't see the initMap() function when it is defined in the google.map callback.

A: Hi i'm playing too with google maps and i see this error occurs when you open the same file in different tabs of the navigator...
I'm talking about " Uncaught: Vb "
When you reboot your computer this error deseapear so for not reboot you can press 'F12' and then go to 'Network' tab ( F5 ), right click over anything then 'clear browser chache' & 'clear browser cookies'..
If the error Uncaught: Vb still press F5 Two or Three times
Other reference for this question:
GoogleMaps does not load on page load
Anyways your error is thrown cause you don't specify YOUR_API_KEY and the paramater in the URL is not well formatted ( js?key= )
Check this:
https://developers.google.com/maps/documentation/embed/get-api-key

A: To us google maps you have to first include reference to google maps javascript file.
Include this script below your body.

Please also read documentation of google maps. You might need api keys too.

A: Put this script tag in you head section.

Make sure you replace YOUR_API_KEY label with your key which you can get from here..
https://developers.google.com/maps/documentation/javascript/


text:
Q: How to make underline tabs position in center? i want to customize the tabs underline on center.
the result
i already use alignItem, justifyContent and its not working. thanks
*here is my code
<Footer>
<Tabs tabBarUnderlineStyle={{ backgroundColor: '#00CBFF', width: 100}}>
<Tab1>
<Tab2>
</Tabs>
</Footer>

A: You can set the following property to your parent view.
flexDirection: 'row',
justifyContent: 'space-evenly',

It will set your layout with the same space for both tab and it will set in the center.

A: If the underline is what the style is being applied to, you would need to use alignSelf.
alignItem and justifyContent effects all children components, not the component itself.

A: Use marginHorizontal like this:
<Tabs
      tabContainerStyle={styles.topTabBG}
      tabBarBackgroundColor="#f0f0f0"
      tabBarUnderlineStyle={{
        width: 50,
        height: 3,
        marginHorizontal: Dimensions.get('window').width / 9.5,
        backgroundColor: '#5e7584',
      }}>


text:
Q: Windows host tunnel through a middle linux server to another linux host with limited ports Addendum:
I've seen question "Windows HTTP tunnel through 2 Linux hosts?" and trying to learn something about the answers. I learned. I will start giving my problem, and then talking a little about my tests with answers of that question.
I'm trying to connect my windows host to a linux host, using a middle linux (the only one with external IP).
What's my problem:
My windows host doesn't have the ports I want open (game and traffic ports).
I have a linux host that have the ports I want open.
So, the problem would be solved if I could make a ssh tunnel through my windows hostto my linux host. The problem is that both of then only have an internal IP (one is on my company, another is on my university).
The salvation: I have acces to my company's linux server, that has an external IP (200.X.X.X).
So, I'd like to use this linux server as an intermediate though my windows host and my linux host.
The complicating:

My linux server only has the port 110 open. I can only connect through ssh to it using the 110 port.
In other words: I'm needing an example such that I can make:
windows host's firefox, proxified to use localhost:9999
redirects its access to linux server,
that redirects its access to my linux host.
One (but not the only one) idea is reverse tunneling my linux host to my linux server, and then direct tunneling my windows host to my linux server, making this linux server redirect my windows host access to my linux host.
But I do not know the commands to try that.
I tried, but with no success:
linux host: ssh -R 20000:localhost:22 middle_user@200.X.X.X -p110
windows host: ssh -L 9999:localhost:20000 middle_user@200.X.X.X -p110
How can I do that?
My environment, in another words:

Windows host (internal IP == 10.X.X.X ; all ports open)
going through
Linux Server (external IP == 200.X.X.X ; can only connect using ssh to it on port 110, the port 110 is the only open)
redirecting windows host traffic to
Linux Host (internal IP == 192.X.X.X ; ports open, can connect using ssh on port 22)

Another addendum:
This would work if, on my linux server,  I could (in a perfect world) access my linux host (what is impossible, given that I have an internal IP on my linux host)
windows host: ssh -L 9999:localhost:9999 -D 9999 -p 110 middle_user@200.X.X.X
linux server: ssh -D 9999 linux_host_user@linux_host_ip

A: Adapted from answer How to ssh to an unreachable remote machine by tunneling through a server that everyone can reach?
The "solution" that worked is:

*

*on linux-user, I did ssh -R 1234:localhost:22 server_user@200.X.X.X -p110

*on windows-user, I did ssh -L 1235:localhost:1234 server_user@200.X.X.X -p110
then,

*

*on windows-user, I did ssh -D 9999 -p 1235 linux-user@localhost
and then, on windows-user, I could configure firefox to use proxy socks localhost:9999, and could access a server running on my linux-user machine.
P.S.: For ssh on windows, I used cygwin to install openssh, to facilitate things.


text:
Q: How to load the navigation property with EF Core? In EF6 we had such option:
context.Set<TEntity>().Attach(entity);
context.Entry(entity).Collection("NavigationProperty").Load();

Since EF Core "goes 100% strictly typed" they have removed Collection function. But what should be used instead?
Added:
I mean how to load includes/"navigation collection properties" for ATTACHED entity?

A: You have 3 methods:
1. Eager loading
e.g.
var blogs = context.Blogs
    .Include(blog => blog.Posts)
    .ToList();

2. Explicit loading
e.g.
var blog = context.Blogs
    .Single(b => b.BlogId == 1);

context.Posts
    .Where(p => p.BlogId == blog.BlogId)
    .Load();

3. Lazy loading (as of EF Core 2.1)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);

You can read more about it here : Loading Related Data
Update :
You can use TrackGraph API for that use case.Here is the link : graph behavior of Add/Attach
Another link : DbSet.Add/Attach and graph behavior

A: Explicit Loading was added in Entity Framework Core v1.1.
See Microsoft Docs
From the docs:
using (var context = new BloggingContext())
{
    var blog = context.Blogs
    .Single(b => b.BlogId == 1);

    context.Entry(blog)
        .Collection(b => b.Posts)
        .Load();

    context.Entry(blog)
        .Reference(b => b.Owner)
        .Load();
}

A: See below Code,
I'm inserting data in UserRef table as well another table which we have many 2 many relationships.
public void AddUser(User user, IEnumerable<UserSecurityQuestion> securityQuestion, string password)
    {
        var userModel = _mapper.Map<User, UserRef>(user);
        userModel.CreateTime = DateTime.Now;

        userModel.UserNewsLetterMaps.ToList().ForEach(u => this._context.UserNewsLetterMaps.Add(u));
        this._context.RoleRefs.Attach(new RoleRef() { RoleId = (int)user.UserRole, UserRefs = new List<UserRef> { userModel } });
        userModel.ResidenceStatusRefs.ToList().ForEach(u => this._context.ResidenceStatusRefs.Attach(u));
        this._context.UserRefs.Add(userModel);
        this.Save();
    }