text:
Q: Fetching data from async api call using react redux I'm having problem with an api call in my React Redux project. Here's the code snippet from the project.
poiAction.js
export function poiSuccess(pois) {
  // The log detail is below
  console.log("POI: ", pois);
  return {
      pois,
      type: POI_FETCH_SUCCESS
  };
}
export function poiFetch(pois) {
  return {
    pois,
    type: POI_FETCH_ATTEMPT
  };
}

export function fetchPoi(token) {
  return dispatch =>
    axios({
      method: 'get',
      url: 'http://localhost:9090/poi',
      headers: {
        'x-access-token': token
      },
    })
    .then((pois) =>{
      // let poi = pois.data[0];
      // console.log("POIS: ", pois.data[0]);
      dispatch(poiSuccess(pois));
    })
    .catch((error) => {
      throw(error);
    })
}

console log output:

poiReducer.js
export default function poi(state = [], action){
  switch(action.type){
    case POI_FETCH_ATTEMPT:
    return state;
    case POI_FETCH_FAILED:
    return state;
    case POI_FETCH_SUCCESS:
    // The console log output is same as poiAction
    console.log("Reducer: ", action.pois);
    return [action.pois, ...state];
    break;

    default:
      return state;
  }
}

The console log output is same as poiAction
Root Reducer
const rootReducer = combineReducers({
  LoginReducer,
  PoiReducer
});

The component to display the list from the api call:
Dashboard.js
class Dashboard extends Component {
  constructor(props) {
    super(props);

    this.state = {
      poi: '',
      token: null
    };
  }
  componentWillMount() {
    let token = sessionStorage.getItem("token");
    this.setState({token});
    this.props.actions.fetchPoi(token);
  }
  render() {
    console.log("POIS: ", this.props.pois);
    return (

Dashboard

    );
  }
}

Dashboard.propTypes = {
  pois: PropTypes.array.isRequired,
  actions: PropTypes.object.isRequired,

};

function mapStateToProps(state) {
  console.log("State: ", state);
  return {
    pois: state.poiReducer
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(poiAction, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

Here this.props.pois is undefined and the value of state from mapStateToProps is:

What am I missing? How do I access the list that's returning from the api call ?
Thanks

A: When you combine your reducers, you do this
const rootReducer = combineReducers({
  LoginReducer,
  PoiReducer
});

which means
const rootReducer = combineReducers({
  LoginReducer : LoginReducer,
  PoiReducer : LoginReducer
});

And that's not what you want.
it should be
const rootReducer = combineReducers({
  loginReducer : LoginReducer,
  poiReducer : LoginReducer
});

Also, for some reason, you got a rootReducer inside your root reducer, which is a little weird.
So the way to access to poiReducer would be
function mapStateToProps(state) {
  console.log("State: ", state);
  return {
    pois: state.rootReducer.poiReducer
  };
}


text:
Q: NullPointerException behavior on using Annotations EDIT (Show the real problem instead of a sample code Annotation code)
I created my own way of loading fxml files in Javafx 8 by using Annotation instead of using the fx:controller tag using this blog, Designing JavaFX Business Applications

I came up with this idea for dealing with Javafx fxml files.
@Target(value = {ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FXMLConfig {

    public String path();

}

So if I have a Javafx controller SampleController, it would look like this
@FXMLConfig(path = "/path/to/SampleController.fxml")
public class SampleController implements Initializable { ... }

To load the GUI I used a class named JavafxWindow
public class JavafxWindow {

    private Stage stage;
    private Scene scene;
    private FXMLLoader loader;

    public void setup(Object controller) throws IOException {
        FXMLConfig config = controller.getClass().getAnnotation(FXMLConfig.class);
        this.loader = new FXMLLoader(controller.getClass().getClassLoader().getResource(config.path()));
        this.loader.setController(controller);
        Parent parent = (Parent) loader.load();
        this.scene = new Scene(parent);
        this.stage = new Stage();
    }

    public void show() {
        this.stage.show();
    }

}

Now the java.lang.NullPointerException lies with in the lines
FXMLConfig config = controller.getClass().getAnnotation(FXMLConfig.class);
this.loader = new FXMLLoader(controller.getClass().getClassLoader().getResource(config.path()));

I tested the code and it worked fine but NPE behavior occurs in the production which is a very annoying bug to users. Exception is thrown at getAnnotation() or config.path() at times of heavy usage. But the production code is deployed using OSGi, Apache Felix 4.6.0 across multiple bundles. I am also using Reflection on other parts but no NPE is thrown.
Can you give me an implementation that comes with a level of checking to remove the abnormal java.lang.NullPointerException behavior?

*

*java version "1.8.0_45"

*Java(TM) SE Runtime Environment (build 1.8.0_45-b14)

*Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

*Apache Felix 4.6.0

*Ubuntu 14.04 / Windows 7 / Windows 8 / Windows 8.1

Thanks for the community's positive response.

A: Here is a a Minimal Complete Verifiable example. I haven't seen NPE of such type, so I'll post here the exact same way I always create my custom annotation for reference. Further questions welcome.

Custom Annotation Class(interface)

import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)

@interface BasicBenefits {
    String bId() default "B-101";
    String bName() default "General Class A Employee";
}

Class using the custom annotation(no need of any imports):

@BasicBenefits(bId="B-400", bName="General Plus Class A Employee")
public class Employee {
    String eId;
    String eName;
    public Employee(String eId, String eName){
        this.eId = eId;
        this.eName = eName;
    }

    public void getEmployeeDetails(){
        System.out.println("Employee ID: "+eId);
        System.out.println("Employee Name: "+eName);
    }
}

Driver class to test out the above.

import java.lang.annotation.Annotation;
public class TestCustomAnnotationBasicBenefits {
    public static void main(String[] args) throws Exception{
        Employee emp = new Employee("E-100", "user3320018");
        emp.getEmployeeDetails();
        Class reflectedClass = emp.getClass();
        Annotation hopeBenefitAnn = reflectedClass.getAnnotation(BasicBenefits.class);
        BasicBenefits bBenefits = (BasicBenefits)hopeBenefitAnn;
        System.out.println("Benefit ID: "+bBenefits.bId());
        System.out.println("Benefit Name: "+bBenefits.bName());
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'pytesseract.pytesseract' has no attribute 'pytesseract' - Attribute error I am using Spyder4 for python.
I have done almost all the required things:

*

*Installed pytesseract package using (!pip install --user pytesseract)

*Downloaded and installed Tessaract-ocr and my tessaract.exe location is  (C:\Users**\AppData\Local\Tesseract-OCR\tesseract.exe)

*I have added the same location(tessaract-ocr) in Path Environment variables

still i am getting the error like "AttributeError: module 'pytesseract.pytesseract' has no attribute 'pytesseract' "
The following is my code
from passporteye import read_mrz
from pytesseract import pytesseract

pytesseract.pytesseract.tesseract_cmd = r'C:\\Users\\*<username>*\\AppData\\Local\\Tesseract-OCR\\tesseract.exe'

# Process image
mrz = read_mrz("C:\\Users\\*<username>*\\Documents\\UiPath\\imageExtract\\Data\\image1.jpeg")

# Obtain image
mrz_data = mrz.to_dict()

# Printing extracted data
print('Nationality :'+ mrz_data['nationality'])
print('Given Name :'+ mrz_data['names'])
print('Surname :'+ mrz_data['surname'])
print('Passport type :'+ mrz_data['type'])
print('Date of birth :'+ mrz_data['date_of_birth'])
print('ID Number :'+ mrz_data['personal_number'])
print('Gender :'+mrz_data['sex'])
print('Expiration date :'+ mrz_data['expiration_date'])

What i am expecting is 'After successful execution the code should display the feilds extracted from image' but continuously i am getting the same error Attribute not found.
Please help me in solving the above problem.
Thank you in advance


text:
Q: Check if variable is within an associative array in jQuery I have this code that loops through a HTML structure and builds an array based on its data attributes. I want to execute a conditional statement within a foreach loop and want to check if my count variable is within the array. I looked at inArray() but I'm not sure it works with associative arrays?
Here is the HTML
<div class="dfp" data-adposition="<?php echo $dfpPos; ?>" data-dfpcode='<?php echo $dfpCode; ?>'>

<div class="dfp" data-adposition="<?php echo $dfpHalfPos; ?>"  data-dfpcode='<?php echo $dfpHalfCode; ?>'>

Here is the JS that builds the array.
var dfpObj = { "adverts" : [] };

$(".dfp").each(function(){  // PROCESS DFPS
    var code = $(this).data("dfpcode");
    var position = $(this).data("adposition");
    var dfp = {
        "code": code,
        "position": position
    }
    dfpObj.adverts.push(dfp);
});

And my IF statement.
if($.inArray(count, dfpObj.adverts) !== -1) {
    var dfp = $('.dfp[data-adposition=' + count + ']');
    var dfpcode = $(dfp).data("dfpcode");
    var dfppos = $(dfp).data("adposition");
    myfunction(dfpcode, dfppos);
}
// count is within a foreach loop so at the end of the loop is $count++

A: You can use the following.
$.grep(dfpObj.adverts, function(obj) { return obj.code == "122"; })

This will give you that object or else gives you empty array.


text:
Q: SQL server - Client Connection works in one network not on another We cannot access from a client computer (Client) to a SQL Server computer (Server) on network A but successfully on another B. The Server computer has SQL Server 2019 installed, the Client computer has SQL Native Client 11.0 installed. We can connect from this client to the server in on network A either using sqlcmd, udl interface, or Telnet. But on a different network B, we cannot connect from the same Client to the same Server! What network configuration can avoid a SQL Server connection?
Server Parameters:
1. We defined firewall rules to allow inbound connection on ports 1433 for TCP and 1434 for UDP. We verified that that is the case on the Server by using "netstat -aon". We disabled the Norton Smart Firewall.

2. We have set this rule to apply to all profiles: Domain, Public, Private.

3. We ensured that all protocols for SQLEXPRESS are allowed and enabld in the SQL Server Configuration Manager, specifically TCP/IP.

4. We have enabled SQL Server Browser.

5. We have restarted all services multiple times after our configuration changes. We have even restarted the machine.

6. We made sure that the Server is accessible remotely and using SQL Server Authentication.

7. We reset both the modem and the router for both Networks before testing.

8. We confirmed both the Computer and the SQL Instance names in the SMSS logins and logs.

Tests we did on Network A:

1. We can ping the Client from the Server, the Server from the Client both with IP addresses and computer names (On Server: "ping -a ClientIP/ComputerName", On Client: "ping -a ServerIP/ComputerName". Both results with "Reply...").

2. We can access the database in the Server using SSMS both with Windows Authentication and SQL Server Authentication.

3. We cannot access to Server from the Client by Windows Authentication either by using "sqlcmd -S Server\sqlexpress -E".

4. We cannot access to Server from the Client by SQL Server Authentication by using "sqlcmd -U User -P Password -S Server\SQLExpress".

On the other hand, when these computers are in Network B, without changing anything we can connect to Server from the Client.

Here are the error messages we get:
sqlcmd -U User -P Password -S Server\SQLExpress

A: By default named instances use dynamic ports, which you're not allowing through the firewall.
The best solution is probably to simply configure the SQL Server instance to listen on the fixed port 1433, then you don't need to use an Instance Name or explicit port to connect.
To do this us SQL Server Configuration Manager to configure the instance to listen on port 1433 on all IPs.  It should look like this:

With Dynamic Ports blank, and 1433 in the TCP IP port.
Then restart the SQL Server instance and in the SQL Server Logs you should see a message like
Server is listening on [ 'any' <ipv4> 1433].

Then try to connect like
sqlcmd -U User -P Password -S Server

And you can test with Powershell
  PS C:\> test-netconnection Server -port 1433

If you do this you won't need the SQL Browser Service or the firewall rule for port 1434.


text:
Q: MySQL int field resets automatically in DGNews hit counter I am using a customized version of DGNews (now defunct) script in my site. In that script, there is a simple method to count the number of hits:
$queryfull = "SELECT * FROM news_publish WHERE id='$newsid'";
$qryfull = @mysql_query($queryfull,$connect) or die ("Wrong Query");
$rowfull = mysql_fetch_array ($qryfull);

$c=$rowfull[click];
$c++;
$d=$c;
@mysql_query("update news_publish set click='$d' where id=$newsid");

I know this script is using outdated mysql query methods, and I am currently not in a position to do a complete upgrade.
But my problem is, 'click' (int) field in all the rows of database, resets to 1 once in a while. I can't figureot how it happens. It happens only once in a year or so. Is this a result of some kind of attempted mysql injection or something? can somebody figureout what is going on here?
thank you
UPDATE
It resets the said field on ALL the rows, not in a single row

A: $queryfull = "SELECT * FROM news_publish WHERE id='$newsid'";
$qryfull = @mysql_query($queryfull,$connect) or die ("Wrong Query");
$rowfull = mysql_fetch_array ($qryfull);

$c=$rowfull['click'];
$d=$c++;
@mysql_query("update news_publish set click='$d' where id=$newsid");

But you can run only update query as suggested  Barmar in comments
@mysql_query("update news_publish set click=click+1 where id=$newsid");

And thats All

A: I can't exactly know where the overflow is happening but this will help you.
alter news_publish modify click bigint

bigint is much much greater than int.


text:
Q: how to make dotted progress indicator component with react hooks? I want to make a dotted progress indicator with react-hooks.
So I have four dots which indicate progress. it's going from full to empty, if it's four dots it's green, three yellow, two - redish and one is red.
I want to control the color and number of dots lit up with props and do it with react-hooks.
The only thing close to it I could find was "Dotted progress bar" on codepen, but it's still different from what I want.
I am expecting the output to be that if I pass 0-25% it lights only one dot with red color, on 50-75% yellow and so on.
I've been trying for some time now, the furthest I've gone is this:
const OnGoingRequest = ({ image, name, profession, progress, color }) => {
  const [dotColor, setDotColor] = useState('#c4c4dd')
  if (progress > 0 && progress <= 25) {
    setDotColor('red')
  } else if (progress > 25) {
    setDotColor('blue')
  }
  return (
    <EachReview>
      <UserContainer>
        <UserImage src={image} />
        <UserInfoContainer>
          <UserName>{name} </UserName>
          <UserProffession>{profession} </UserProffession>
        </UserInfoContainer>
      </UserContainer>
      <ReviewStatusContainer>
        <Box>
          <Score />
          <Bar>
            <Progress progress={progress} color={dotColor} />
            <Dot />
            <Dot />
            <Dot />
            <Dot />
          </Bar>
        </Box>
        <ReviewStatusReachout>REACHOUT AGAIN</ReviewStatusReachout>
      </ReviewStatusContainer>
    </EachReview>
  )
}
export default OnGoingRequest

const EachReview = styled.div`
  display: grid;
  grid-template-columns: 2.5fr 1fr;
  padding: 25px 20px 15px 20px;
`
const UserContainer = styled.div`
  display: flex;
  align-items: center;
`
const UserImage = styled.img``
const UserInfoContainer = styled.div`
  display: flex;
  flex-direction: column;
  margin-left: 10px;
`
const UserName = styled.p`
  font-family: SFUIDisplay-Regular;
  font-size: 16px;
  font-weight: 500;
  font-stretch: normal;
  font-style: normal;
  line-height: 1.19;
  letter-spacing: normal;
  text-align: left;
  color: #000000;
  margin-bottom: 5px;
`
const UserProffession = styled.p`
  font-family: SFUIDisplay-Regular;
  font-size: 14px;
  font-weight: 500;
  font-stretch: normal;
  font-style: normal;
  line-height: 1.21;
  letter-spacing: normal;
  text-align: left;
  color: #6b737d;
  margin: 0;
`
const ReviewStatusContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
`
const ReviewStatusReachout = styled.p`
  font-family: SFUIDisplay-Regular;
  font-size: 12px;
  font-weight: 500;
  font-stretch: normal;
  font-style: normal;
  line-height: 1.17;
  letter-spacing: normal;
  text-transform: uppercase;
  text-align: right;
  color: #30aabc;
  margin: 0;
`
const Box = styled.div`
  width: 200px;
  height: 150px;
  background: #63a3e3;
  text-align: center;
`
const Score = styled.div`
font-size: 48px;
line-height: 88px;
color: #fff;
}
`
const Bar = styled.div`
  background: #c4c4dd;
  position: relative;
  height: 20px;
  width: 80%;
  margin: 0 auto;
  text-align: left;
`
const Progress = styled.div`
  position: absolute;
  height: 100%;
  transition: width 0.4s ease-in;
  width: ${props => props.progress};
  background-color: ${props => props.color};
  z-index: 1;
`
const Dot = styled.div`
  position: relative;
  width: 5%;
  height: 20px;
  margin-left: 16%;
  background-color: rgba(99, 163, 227, 1);
  /* background-color: rgba(199,12,127,.8);*/
  /*display: inline-block; */
  float: left;
  z-index: 2;

progress is passed as props, and I am checking according to it but I get an error of too many re-renders. guess it's because of checking before the return.

A: I found the solution. I recieve 1,2,3 or 4 as props and I am rendering according to it.
const OnGoingRequest = ({ image, name, profession, progress }) => {
  return (
    <EachReview>
      <UserContainer>
        <UserImage src={image} />
        <UserInfoContainer>
          <UserName>{name} </UserName>
          <UserProffession>{profession} </UserProffession>
        </UserInfoContainer>
      </UserContainer>
      <ReviewStatusContainer>
      {
        progress == 1 &&(
        <DotsContainer>
          <Dot color={'red'} />
        </DotsContainer>)
      }
      { progress === 2 && (
        <DotsContainer>
          <Dot color={'purple'} />
          <Dot color={'purple'} />
      </DotsContainer>
      )
      }
      {
        progress === 3 && (
          <DotsContainer>
            <Dot color={'yellow'} />
            <Dot color={'yellow'} />
            <Dot color={'yellow'} />
        </DotsContainer>
        )
      }
      {
        progress == 4 && (
        <DotsContainer>
          <Dot color={'green'} />
          <Dot color={'green'} />
          <Dot color={'green'} />
          <Dot color={'green'} />
        </DotsContainer>)
      }
        <ReviewStatusReachout>REACHOUT AGAIN</ReviewStatusReachout>
      </ReviewStatusContainer>
    </EachReview>
  )
}
export default OnGoingRequest

const EachReview = styled.div`
  display: grid;
  grid-template-columns: 1.5fr 1fr;
  padding: 25px 20px 15px 20px;
`
const UserContainer = styled.div`
  display: flex;
  align-items: center;
`
const UserImage = styled.img``
const UserInfoContainer = styled.div`
  display: flex;
  flex-direction: column;
  margin-left: 10px;
`
const UserName = styled.p`
  font-family: SFUIDisplay-Regular;
  font-size: 16px;
  font-weight: 500;
  font-stretch: normal;
  font-style: normal;
  line-height: 1.19;
  letter-spacing: normal;
  text-align: left;
  color: #000000;
  margin-bottom: 5px;
`
const UserProffession = styled.p`
  font-family: SFUIDisplay-Regular;
  font-size: 14px;
  font-weight: 500;
  font-stretch: normal;
  font-style: normal;
  line-height: 1.21;
  letter-spacing: normal;
  text-align: left;
  color: #6b737d;
  margin: 0;
`
const ReviewStatusContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
`
const ReviewStatusReachout = styled.p`
  font-family: SFUIDisplay-Regular;
  font-size: 12px;
  font-weight: 500;
  font-stretch: normal;
  font-style: normal;
  line-height: 1.17;
  letter-spacing: normal;
  text-transform: uppercase;
  text-align: right;
  color: #30aabc;
  margin: 0;
`

const DotsContainer = styled.div`
background: #fff;
position: relative;
height: 20px;
margin: 0 10px 0 0;
text-align: left;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
justify-content: space-evenly;
align-items: center;
`

const Dot = styled.div`
  position: relative;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: ${props => props.color};
  /*display: inline-block; */
  float: left;
  z-index: 2;
  margin-right: 10px;
  &:last-of-type{
    margin-right: 0;
  }
`


text:
Q: Convert datatype using parameter - ChangeType() scope issue I want to convert a var based on the Type of another variable.
The reason for this is that I have an extension method that will apply a calculation on T providing T is a double, float or decimal (I test for the correct Type at the beginning of the method).
So anyway, testing the conversion with the following code snippet throws an error:
      List<double> source = new List<double>();
      source.Add(1);
      Type typ = source.First().GetType();
      var newVal = Convert.ChangeType(source.First(), typeof(typ));  //error: typ not found

The type or namespace name 'typ' could not be found (are you missing a
  using directive or an assembly reference?)

However, this works fine:
      List<double> source = new List<double>();
      source.Add(1);
      Type typ = source.First().GetType();
      var newVal = Convert.ChangeType(source.First(), typeof(double));

A: note that a Type object and a reference to a type are not the same thing.
While Type typ creates an object of type Type, typeof(T) returns a Type object based on the T, which is known at compile time (for generics, this is JIT-compile time, but it works the same).
Thus, you cannot use a Type object for a generic parameter directly, because it's an object, not a type reference.
Note, however, that since typeof returns a Type object, this case can be solved by using typ directly.
  List<double> source = new List<double>();
  source.Add(1);
  Type typ = source.First().GetType();
  var newVal = Convert.ChangeType(source.First(), typ);


text:
Q: How to call a function from another one with optional third parameter? I'm learning python from this tutorial. I'm trying to solve 3rd exercise (under 7.16. Exercises, on this page). If anybody can help me and give some tips because it's not that I don't know how, but I'm not sure I get what actually I have to do ("HOW TO DO" is not the problem, problem is "WHAT TO DO").
This is the code I have so far (from the 2nd exercise, since these two exercises are linked):
def count_letters(string, letter):
    count = 0
    for char in string:
        if char == letter:
            count+=1
    print count

A: An optional parameter is a parameter you can either provide or leave out, in the latter case, there's a default value assigned.
Given the second find in http://openbookproject.net/thinkcs/python/english2e/ch07.html#optional-parameters
def find(strng, ch, start=0):

start is an optional parameter. In case you in invoke find like
find('foobar', 'o')

start is implicitly set to 0, thus find starts finding at index 0, thus at the beginning of that string, in case you invoke it like
find('foobar', 'o', 3)

start = 3 would we used, and try start finding letter 'o' at index 3 (and fail).

Exercise 7.16.3 simply wants you to find starting at 0, get the index for the first match, use that index to figure out a new value to continue searching at, find again... and repeat and count matches until the find fails.

A: The optional third parameter refers to the start parameter of the string.find method that allows you to specify the starting index for the search.


text:
Q: Express.js : Can't set a correct format of data in json file I have a json file with data, which I should load to array in the following format:
var jobs = [
  { ID: 'grt34hggdggf', Employer: 'A1', Title: 'tobi1', Location: 'Los Angeles, CA', Department: 'department', OpeningDate: '2012-12-26T01:29Z', ClosingDate: '2013-04-26T01:29Z', MinSalary: '30000', MaxSalary: '60000', Description: 'bla-gghrf-bla' },
  { ID: 'grt34hgwerwgf', Employer: 'A2', Title: 'tobi2', Location: 'Los Angeles, CA', Department: 'department', OpeningDate: '2012-12-26T01:29Z', ClosingDate: '2013-04-26T01:29Z', MinSalary: '30000', MaxSalary: '60000', Description: 'bla-gghrf-bla' }
];

so, this format is right for me and works with views.
Which format should have my json file. I try the following:
{
    "jobs":[
  { "ID": "grt34hggdggf", "Employer": "A1", "Title": "tobi1", "Location": "Los Angeles, CA", "Department": "department", "OpeningDate": "2012-12-26T01:29Z", "ClosingDate": "2013-04-26T01:29Z", "MinSalary": "30000", "MaxSalary": "60000", "Description": "bla-gghrf-bla" },
  { "ID": "grt34hggdggf", "Employer": "A2", "Title": "tobi1", "Location": "Los Angeles, CA", "Department": "department", "OpeningDate": "2012-12-26T01:29Z", "ClosingDate": "2013-04-26T01:29Z", "MinSalary": "30000", "MaxSalary": "60000", "Description": "bla-gghrf-bla" }

  ]
}

but when I try to do "forEach" in view I get an error:
TypeError: F:\tmp\express-master\examples\ejs\views\result.html:5
    3|
    4|

 >> 5|   <% jobs.forEach(function(job){ %>
    6|

    7|
    8|             <a href="/job/<%= job.ID %>"><%= job.Title %>

Object #<Object> has no method 'forEach'

so, seems, json file has another format than expected. How to do it correctly?

A: I found correct format in my case:
[
  { "ID": "grt34hggdggf", "Employer": "A1", "Title": "tobi1", "Location": "Los Angeles, CA", "Department": "department", "OpeningDate": "2012-12-26T01:29Z", "ClosingDate": "2013-04-26T01:29Z", "MinSalary": "30000", "MaxSalary": "60000", "Description": "bla-gghrf-bla" },
  { "ID": "fgert", "Employer": "A2", "Title": "tobi2", "Location": "Los Angeles, CA", "Department": "department", "OpeningDate": "2012-12-26T01:29Z", "ClosingDate": "2013-04-26T01:29Z", "MinSalary": "30000", "MaxSalary": "60000", "Description": "bla11-ggh777rf-bla" }
]


text:
Q: Difference of Dates in R I'm working on a dataset that comprises information about children aged 0-4. I would like to calculate the date they turned the age of 5.
My dataset looks like this:
  data = data.frame(
  id = c(1:4),
  Date_of_Birth = as.Date(c("2005-10-10", "2006-11-05", "2007-11-15", "2008-12-12"))

)

Then, I need to create a new variable 5y_birthday that gives me the exact date that those children turned 5y.
Can anyone help me to solve that?


text:
Q: Array of objects return the label associated to a specific ID I have the following array:
"facilities":[
  {
    "name": "Gratis",
    "id": "FACILITYCATEGORYFREE",
    "facilities":[
       {"name": "Free city maps", "id": "FREECITYMAPS"},
       {"name": "Free parking", "id": "FREEPARKING"},
       {"name": "Free Wifi", "id": "FREEWIFI"}
    ]
  }
]

I need to append the free facilities inside a "ul" in a specific order:

*

*Free wifi

*Free city maps

I have the following:
for (i =0; i < json.facilities[0].facilities.length; i++) {
  $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
}

however this will only print based on how they are positioned in the array
I have tried this but not there yet:
for (i =0; i < json.facilities[0].facilities.length; i++) {
  if(json.facilities[0].facilities[i].name.length && json.facilities[0].facilities[i].id === 'FREEWIFI'){
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
  if (json.facilities[0].facilities[i].id === 'BREAKFASTINCLUDED') {
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
  if (json.facilities[0].facilities[i].id === 'FREEINTERNETACCESS') {
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
  if (json.facilities[0].facilities[i].id === 'TOWELSINCLUDED') {
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
  if (json.facilities[0].facilities[i].id === 'LINENINCLUDED') {
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
  if (json.facilities[0].facilities[i].id === 'FREECITYMAPS') {
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
  if (json.facilities[0].facilities[i].id === 'FREEPARKING') {
    $("#facilities").append("
" + json.facilities[0].facilities[i].name + "
");
  }
}

A: If you don't know how many facilities there are going to be in the list, you could you do something like this:
id_order = ["FREEWIFI", "FREECITYMAPS"].reverse();
facility_cmp = function (a, b) {
    var a_idx = id_order.indexOf(a.id);
    var b_idx = id_order.indexOf(b.id);
    if (a_idx == b_idx) return 0;
    return (a_idx > b_idx) ? -1 : 1;
}

This is a comparison function that you can use to sort the array to give you facilities in the right order. The reverse is so that you can specify the ids in a natural way, but the resuilting list is in the order that works when sorting ids that don't appear in the list without having to have a special case for an index of -1.
The you can do:
var these_facilities = json.facilities[0].facilities
    .slice(0)               // get a copy of the array
    .sort(facilities_cmp);  // and sort it
these_facilities.forEach(function (facility) {  // forEach is easier IMHO than writing a for loop over .length
    $("#facilities").append("
" + facility.name + "
");
});

A: If you can re-organise your JSON in a different way you could do something like;
"facilities":[
  {
    "name": "Gratis",
    "id": "FACILITYCATEGORYFREE",
    "facilities":{
       "FREECITYMAPS":{"name": "Free city maps"},
       "FREEPARKING":{"name": "Free parking"},
       "FREEWIKI":{"name": "Free Wifi"}
    }
  },
]

var firstLi = "
" + json.facilities[0].facilities.FREEWIFI +"
"
var secondLi = "
" + json.facilities[0].facilities.FREECITYMAPS +"
"
var thirdLi = "
" + json.facilities[0].facilities.FREEPARKING +"
"

$("#facilities").append(firstLi + secondLi + thirdLi);

Since you can't edit the JSON we need to start with this:
"facilities":[
  {
    "name": "Gratis",
    "id": "FACILITYCATEGORYFREE",
    "facilities":[
       {"name": "Free city maps", "id": "FREECITYMAPS"},
       {"name": "Free parking", "id": "FREEPARKING"},
       {"name": "Free Wifi", "id": "FREEWIFI"}
    ]
  },
]

you could do:
var firstLi, secondLi, thirdLi = ""

for (var i = 0; i < json.facilities[0].facilities.length; i++){

  if (json.facilities[0].facilities[i].id === "FREEWIFI"){

    firstLi = "
" + json.facilities[0].facilities[i].name +"
"

  }else if (json.facilities[0].facilities[i].id === "FREECITYMAPS"){

    var secondLi = "
" + json.facilities[0].facilities[i].name +"
"

  }else if (json.facilities[0].facilities[i].id === "FREEPARKING"){

    var thirdLi = "
" + json.facilities[0].facilities[i].name +"
"

  }
}

$("#facilities").append(firstLi + secondLi + thirdLi);

Another possibile way, since array order is preserved you can rely on the order of the facilities sub array and do this:
if (json.facilities[0].facilities.length === 3){
  var firstLi = "
" + json.facilities[0].facilities[2].name +"
"
  var secondLi = "
" + json.facilities[0].facilities[0].name +"
"
  var thirdLi = "
" + json.facilities[0].facilities[1].name +"
"
  $("#facilities").append(firstLi + secondLi + thirdLi)
}


text:
Q: Unable to plot the pdf I am unable to plot the pdf because the matrix that contains the values holding the probabilities is not functioning as I would want it to. Below is the code that I have written, please let me know where  am going wrong.
mu=c(1,-1)
covar=matrix(c(1,-1.6,-1.6,4),2,2,byrow=TRUE)
pdff= function(z){
pdf= ((exp(-t(z-mu)%*% solve(covar) %*% (z-mu))/2)/(6.283* sqrt(det(covar))))
return(pdf)
}

x=seq(3,5,length=50)
y=seq(2,4,length=50)
prob=matrix(NA, 50, 50)
for(i in x){
  for(j in y){

    prob[i,j]= as.vector(pdff(c(i,j)))
  }
}

prob matrix here is not getting filled up with probabilities. There are a lot of values that are still NA.
I need a solution  that helps in finding the prob matrix with all the values filled.


text:
Q: Обрезать  js Имеется <link>, нужно <link href="http://сайт.ру/odeyala/?filter_ocfilter=43:4078;42:484" rel="canonical" 1=""> обрезать ссылку, то есть href="http://сайт.ру/odeyala/ получить такого вида href
$(function() {
    $("#aaa").each ( function() {
        alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).split('/?') ) );
    });
});

A: По предыдущему комментарию, если правильно понял то будет:
$('#aaa').attr('href', $('#aaa').attr('href').split('/?') [0])

В вашем случае
$(function() {
    $("#aaa").each ( function() {
        alert ( $(this).attr('href', $(this).attr('href').split('/?')[0]));
    });
});

A: <link id="aaa" href="http://site/odeyala/?filter_ocfilter=43:4078;42:484" rel="canonical" 1="">


text:
Q: How to get the list of process running in android device using Selendroid Can any one help me in getting the list of running process in Android using Selendroid?

A: You can do that using ADB connection:
driver.getAdbConnection().executeShellCommand("ps > file");
driver.getAdbConnection().executeShellCommand("pull file localfile");


text:
Q: Probability that an event will happen given continuous probability distribution This question actually came from watching a weather report, so here's the weather related analogy:
Let's say that the probability of rain today is  $f(t)$, where max of f is 0.4 and min is 0, with time t in hours.  If $t \in [0, 24]$ Can I claim that the probability of rain in the next 24 hours is just max of f?
I feel that it isn't, since $f$ is a continuous distribution while the question in asking is discrete, but I don't know how to mix the to.

A: No. The discrete analogy would be the following. Suppose that $f$ is discrete with probability of rain at hour $i$ equal $i/100$. Then, we have $0\%$ probability that it rains at midnight and $23\%$ that it rains at $11$ pm, but you cannot claim the probability of rain today is $23\%$. The real way to do this is to condition at the specific time of day, so you get
$$
\begin{split}
\mathbb{P}[\text{rain today}]
 &= 1 - \mathbb{P}[\text{no rain today}]\\
 &= 1 - \prod_{h = 0}^{23}
             \left(1- \mathbb{P}[\text{rain now}|\text{now is } t]\right) \\
 &= 1 - \prod_{h = 0}^{23} \left(1 - \frac{h}{100}\right) \\
 &= 1 - \frac{1}{100^{24}} \prod_{h = 0}^{23} (100-h) \\
 &= 1 - \frac{100!}{76! \cdot 100^{24}} \\
 &\approx 1 - 0.049 \\
 &= 95.1\%
\end{split}
$$


text:
Q: How to get Android custom adapter element position How to retrieve position of an element from a custom adapter based on element name.. I have a cityAdapter that contains city name and id in key value format. I am trying to retrieve position by the following code
SpinnerModel model=new SpinnerModel();
            model.setKey(""+currentLocation);
            model.setValue(currentLocationValue);
            int position = cityAdapter.getPosition(model);

Position is returning as -1.
Can any one please guide me how to solve the issue.

A: You can easily get position of a particular item on click of a list,
is there any particular reason so that you don't want to get item position on list click?


text:
Q: How To get Facebook Follower using Graph Api and Graph Secret? i recently used Graph Api and Graph Secret  and get Full Friends list from facebook. Now  how to get Followers from facebook using graph api and secret ? any idea about it? previous i  have using for get friend list using php sdk? please any one guide  me? how to get facebook using Graph api and secret ?

A: Please refer to the Facebook docs before posting such a broad question. You're not able to get the subscribers anymore, because it was deprecated with Graph API v2.0.
Furthermore, starting with v2.0 you'll also not be able to get all friends of a user anymore, only those which are also using your app. Additionally, this will never be possible with an app access token as you write, only with an user access token.
See

*

*https://developers.facebook.com/docs/apps/changelog#v2_0

*

*/me/subscribers and /me/subscribedto have been removed.

*The /me/friends endpoint no longer includes the full list of a person's friends. Instead, it now returns the list of that person's friends who are also using your app.

A: To get the followers of the friend, you can use subscriber:
https://graph.facebook.com/<user_id>/subscribers

Get all the list of friends in an array, pass the each friend user id to above Graph API which will list all the profiles that are following this friend to another array.

A: You will need to pass access token while getting all the followers list.
It would be like this:
graph.facebook.com/me/subscribers?method=get&access_token={urtoken}
To get other user followers, you'll have to use his access token not yours.
And make sure that you use https:// at the start of api url.


text:
Q: Get notified of reference changes in JavaScript Is there a way to be notified of a reference change?
I feel I need to be clear about what I mean:
var a = { aa: 1 };
a = { aa: "allowed" }; // `a`'s reference was modified
a.aa = "foo"; // `a` was mutated, but the reference was not modified. Don't care.

It's that reference change I'm interested in. In Swift this is a didSet block. I'd like to observe changes to the reference that a points to.
Full example:
var reel = [];
function print(message) {
  reel = reel.concat([message]); // non-mutating push changes "reel" reference to this new object.
}

Object.SOME_FUNCTION(reel, onChangeReel); // not a real function

function onChangeReel() { /* update the DOM */ }

A: By "reference change", you seem to mean a change in a variable's value.
No, there is no existing or proposed way to do that.
What can be watched--either with the moribund Object.observe proposal or with proxies, is changes in a property's value.


text:
Q: Modifying a table to handle SPID I have a table where new data gets filled each time a user clicks an option on my website. I created this table via Management Studio and I want to clarify that neither I am creating this table each time via stored procedure nor I am using any type of in-memory temporary tables.
Whenever user clicks an option on my website, old records from this table are deleted first and new records are filled. I am worried about the concurrency issue that may arise when many users click the same option from my website. I am not aware of how SQL Server is going to handle multiple delete and inserts into this table.
I read somewhere that SQL Server Services automatically handle this issue with a separate session-wise copy of the table for each session.
Is there a need to add SPID in my table or it is automatically taken care of? Do I need to change the isolation level from Read Committed to Serializable?

A: The general answer to the question you're asking is that yes you will need to have some sort of session identifier column in your table and pass the value in it for each user/session  along to all stored procedures and/or SQL statements that operate on that table.
The alternative is that yes, you could set the isolation level to Serializable and have your users queue up one behind the other waiting until everyone in front of them is done and let SQL Server handle it, but that's almost never what you want to do.
So roughly, for the first option, you'll end up with something like :
YourTable
  ID     DataCol1    DataCol2   DataCol3 .... User/SessionID

So a User logs in/starts a Session on your site. You use their ID or generate a SessionID for them and pass it to
StoredProc1ClearSession @UserSessionID
StoredProc2InsertNewData  (AnyOtherParamsYouHave),@UserSessionID
StoredProc3RetrieveData   (AnyOtherParamsYouHave),@UserSessionID

you get the idea.
Basically as long as every SQL statement you use to touch the table has as part of the WHERE clause or insert statement:
UserSessionID or @UserSessionID

then you're probably well on your way to having a table that can be safe shared by several users at the same time as you described.
For the second option, please
read this so you realize what you're getting yourself into.  :)
Then put code like this
CREATE PROC yourstoredproc
paramaterslisted
AS
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;

YOURCODE TOUCHING TEMPTABLE HERE

COMMIT TRANSACTION;

Just in case you don't read the link:
SERIALIZABLE
Specifies the following:
This blocks other transactions from updating or inserting any rows that would qualify for any of the statements executed by the current transaction. This means that if any of the statements in a transaction are executed a second time, they will read the same set of rows. The range locks are held until the transaction completes. This is the most restrictive of the isolation levels because it locks entire ranges of keys and holds the locks until the transaction completes. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction.

A: The "separate copy per session" you mentioned sounds like snapshot isolation, which is not enabled by default.
Although the specifics depend somewhat on what other transactions you have going on at the same time, in general it should be good enough to simply wrap your DELETE and INSERT commands in a single transaction. You should not need to increase the isolation level.
BEGIN TRAN
DELETE ...
INSERT ...
COMMIT TRAN


text:
Q: How do I back up On Premise Microsoft SQL Server 2008 to Azure cloud I have a 50 GB hosted SQL Server database at SoftLayer.
I want to do backups to cloud storage, as the SoftLayer managed SQL Server backups are ridiculously priced. Eventually we will totally move away from their hosting model to pure cloud, but that is a topic for another question.
For the time being, I want to automate backup of "on premise" SQL Server databases to a cloud storage provider. Ideally, I would stay with Microsoft Azure, but I am open to S3 or other options if they are available.

A: A SSIS package to move the data would be the route I'd go. This SO thread has many suggestions of solutions users tried apart from SSIS, incl 3rd party tools.


text:
Q: Java webservice in tomcat using axis I would like to ask a few questions to make sure that I understand things.
When creating a web service using tomcat and axis, I create an interface defining the methods that I am going to expose. so far so good. I have a couple more classes as well. I compile my classes (.class files no jars) an store them in WEB-INF\classes ..right??  I hardcode my deploy.wsdd file and by using Admin or AdminClient (axis helper classes) I integrate the deploy.wsdd to the server-config.wsdd file.
everything is working fine.
Questions:

*

*Is it ok to have classes (.class files) in WEB-INF\classes directory?? should i create a jar or war file and store it somewhere???

*I have tried using java2wsdl (giving it the interface.class as input) to produce a wsdl file and then wsdl2java. I did that in order to generate deploy.wsdd file and then integrate it in server-config.wsdd file. The deploy.wsdd file generated is not correct and my service is not working properly. What am i missing here?? is there a different way to generate the deploy.wsdd file?????
Help???
Thanx in advance.
Theo

A: *

*It's perfectly okay to have .class files in WEB-INF/classes, as long as they're in packages.  Tomcat doesn't like using the default package.

*I'm not sure, because I'm not an Axis fan.  This is all a lot easier with Spring "contract first" web services.  You aren't tied to Axis if you use it (but you are tied to Spring).


text:
Q: How to toggle accordion menu using a check box and only that checkbox? okay, so I got to disable other checkbox when one is active and managed to keep the transition animation for the panel of my accordion, however i can't figure out how to toggle the panel once i click on the "YES" checkbox.
what it does is when you click the "YES" checkbox, you still need to click the first accordion panel to open it. what I was looking for is when I click on the the "YES" checkbox, it should toggle the panel.
so far here's what I got

button.accordion_1{
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}

button.accordion_1.active, button.accordion:hover {
background-color: #ddd;
}

div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}

button.accordion_main{
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}

button.accordion_main.active, button.accordion:hover {
background-color: #ddd;
}

div.panel_main{
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}

  <button class="accordion_main" id="check_holder"> TOTALLY RANDOM TEXT FOR TESTING

     <form name="aForm" action="">

       <input class="checkbx" id="check_main" name="Role" type="checkbox" value="yes"/>YES

       <input class="checkbx" name="Role" type="checkbox" value="no"/> NO

     </form>

  </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <button class="accordion_1">Section 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <button class="accordion_1">Section 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

again, thanks guys in advance, I've been working on this for two days now, any help is well appreciated!

A: Give the class related to the button for section 2 and section 3 a different name.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
button.accordion, button.accordionn {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
}

button.accordion.active,
button.accordion:hover {
  background-color: #ddd;
}

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}

    <button class="accordion" style="align:right;"> TOTALLY RANDOM TEXT FOR TESTING

                    <input type="checkbox" id="check1" />
                    YES

                    <input type="checkbox" id="check2" />
                    NO

        </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordionn">Section 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordionn">Section 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

A: I got it guys!
for reference here's what I was trying to do.

            <button class="accordion_main" id="check_holder"> TOTALLY RANDOM TEXT FOR TESTING

                        <form name="aForm" action="">

                                <input class="checkbx" id="check_main" name="Role" type="checkbox" value="yes"/>YES

                                <input class="checkbx" name="Role" type="checkbox" value="no"/> NO

                        </form>

            </button>

A

B

C

D

E

F

instead of using the same transition effects for the other 2 panels i used this instead
$('#panel_main').toggle("fast","linear");

if you noticed i removed my css for div.panel.
tat was my major mistake, my the css was a conflict for the js. thanks guys!


text:
Q: Convert file into BytesIO object using python I have a file and want to convert it into BytesIO object so that it can be stored in database's varbinary column.
Please can anyone help me convert it using python.
Below is my code:
f = open(filepath, "rb")
print(f.read())

myBytesIO = io.BytesIO(f)
myBytesIO.seek(0)
print(type(myBytesIO))

A: Opening a file with open and mode read-binary already gives you a Binary I/O object.

Documentation:
The easiest way to create a binary stream is with open() with 'b' in the mode string:
f = open("myfile.jpg", "rb")

So in normal circumstances, you'd be fine just passing the file handle wherever you need to supply it. If you really want/need to get a BytesIO instance, just pass the bytes you've read from the file when creating your BytesIO instance like so:
from io import BytesIO

with open(filepath, "rb") as fh:
    buf = BytesIO(fh.read())

This has the disadvantage of loading the entire file into memory, which might be avoidable if the code you're passing the instance to is smart enough to stream the file without keeping it in memory. Note that the example uses open as a context manager that will reliably close the file, even in case of errors.


text:
Q: List> | AddRange with arrays Im wondering about how to add arrays to a List<Tuple<double, double>>.
My (short) code:
double[] var1 = new double[5] { 1, 2, 3, 4, 5 };
double[] var2 = new double[5] { 1.5, 1.5, 2.5, 1.2, 1.1 };

List<Tuple<double, double>> tup = new List<Tuple<double, double>>();

I would like to fill tup with my arrays. Unfortunately for that I would need to instanciate a Tuple for each entry. Dont know how to do this.
In general I could just use a loop, but this looks dirty for me. My question is about performance and clean code.
if(var1.Length == var2.Length)
{
    for (int i = 0; i < var1.Length; i++)
    {
        tup.Add(new Tuple<double, double>(var1[i], var2[i]));
    }
}

Isnt there a shorter way to archive this? Any way with AddRange maybe?

A: You could use LINQ's Enumerable.Zip extension method. Per the docs, this:

Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

In this case, we can use Tuple.Create as the function to create a tuple from both elements.
var tup = var1.Zip(var2, Tuple.Create).ToList();

Though note that this could give a slightly different result to your code in the case where the sequences are not the same length.  Per the docs again:

If the input sequences do not have the same number of elements, the method combines elements until it reaches the end of one of the sequences

Check out this fiddle for a working demo.

A: Well, you could use Zip to project the collections to a list of tuples:
var tup = var1.Zip(var2, (v1, v2) => new Tuple<double, double>(v1,v2))
              .ToList();

But personally I find your original method easier to read and to understand the intent.  There should be very little performance difference.  Shorter code isn't always better code.

A: You have to loop yourself or let LINQ loop, Enumerable.Zip joins by index:
 List<Tuple<double, double>> tup = var1.Zip(var2, (d1, d2) => Tuple.Create(d1, d2))
    .ToList();

So this isn't more efficient but might be more readable.


text:
Q: img in div float left with text centered vertically and horizontally I feel like this should be (and probably is) answered somewhere, but either that's not the case, I'm not searching the right way, or it's some closely guarded national secret, because I cannot find an answer that works.  Specifically, I cannot find an answer that accommodates the image on the left side of my div.
What I'm trying to effect is for the text to be centered horizontally with regards to the entire screen and vertically within the 'header' div.  I don't want to use my logo as a background, because I'm using it as a home anchor.  I have tried to using 'display: table-cell' and 'vertical-align: middle' to disastrous result.  Please, any advice/help/link is appreciated.
CSS:
#header{
    width: 85%;
    min-width: 500px;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    background-color: #fff;
    border-bottom-width: 10px;
    border-bottom-style: double;
    border-bottom-color: #000;
}

#title{
    width: 85%;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
    display: table-cell;
    vertical-align: middle;
}

#logo{
    float: left;
    padding-right: 1em;
    width: 150px;
}

HTML:

Site Title

Also, I'm completely new to using CSS (and pretty useless with xhtml/html5).  I'm working on my current project as a means to familiarize myself with CSS/PHP/HTML/JScript, and so far, the CSS/HTML is the only part that I'm having problems with.  Any pointers to a good beginner's, but not remedial/'for dummies', guide would also be appreciated.

A: I'd recommend making your logo absolutely positioned. That will take it out of the flow of the html elements (like a background image does) while keeping it still clickable.
#logo {
position: absolute;
top: 5px;
left: 10px;
width: 150px;
}

That will make it easier to center your title. Here's the full example with a few adjustments to your code:
http://jsfiddle.net/gqvUv/
Your "text-align: center;" keeps everything centered horizontally, and adjusting the line-height of your h1 will work to center it vertically, as long as the title is just one line.
It's easy to get confused by relative and absolute positioning, but this tutorial makes it clear: http://www.barelyfitz.com/screencast/html-training/css/positioning/
Finally, this is my go-to article on centering things with CSS: http://designshack.net/articles/css/how-to-center-anything-with-css/


text:
Q: Distance of equally distributed points on a sphere Let $S^d = \{x \in \mathbb{R}^{d+1}: \|x\|_2 = 1\}$ be the unit sphere in $\mathbb{R}^{d+1}$.
Given $n \in \mathbb{N}$, I want to understand how far apart each point from $S^d$ will be to its closest neighbor and how small the maximum of these distances may become across all points. I am trying to find:
$$\min_{\{x_1, ..., x_n\} \in S^d} \max_{i \in [n]} \min_{j \neq i} \|x_i - x_j\|$$
This will depend on $n,d$ of course and I guess it will be optimal to space the points equally across the sphere.
I am mostly interested in asymptotic bounds on this expression.
In two dimensions it should be easy to get them because we can simply cut an arc of length $2\pi$ into $n$ equal parts.

A: This is not a full answer and if anyone knows more about this topic, please feel free to add further information.
Having followed some of the links suggested in the comments, I at least got the asymptotic bound I was mostly interested in.
It turns out that for every $d \in \mathbb{N}$ there exists a constant $K>0$ and a sequence of partitions $\mathcal{P}_N$ of the unit sphere $S^d \in \mathbb{R}^{d+1}$ into $N$ regions of equal area such that for all $N \in \mathbb{N}$ we have
$$ \sup_{P \in \mathcal{P}_N} \; diam(P) \le K \cdot N^{-1/d}$$
where the diameter of a region $P$ is defined as $$diam(P) = \sup_{x,y \in P} \|x-y\|_2$$
The existence of such a partition was asserted by Stolarsky and a construction was given by Feige and Schechtman.


text:
Q: "You can't eat that" vs "You mustn't eat that" What's the difference between the two sentences:

You can not eat that

and

You must not eat that

A: While they could be used for anything where eating the object is forbidden, on their own "You can not eat that" would be applicable to things that you literally could not eat (Like a rock, or a plate of food too large for you to stomach), while "You must not eat that" is more applicable to something that is wholly edible, but forbidden.
"Cannot" has connotations regarding ability, while "must not" is more about authority and requirements.

A: Perhaps some examples would help.
You can't eat that (because it's physically impossible):

*

*a bowling ball

*the ocean

*argon gas

You mustn't eat that (because doing so would be wrong or inappropriate):

*

*your sibling's birthday cake

*another diner's food in a restaurant

*the offerings at a shrine

You can't eat that (without suffering health consequences), therefore you mustn't eat that:

*

*expired or tainted meat

*something to which you are allergic

*a kitchen sponge

A: The meaning is actually quite similar. In both sentences the speaker is telling the addressee that eating that food is a bad idea. More specifically:
You can not eat that: It may imply a prohibition, e.g. as in a mother to her child. But it could also mean that the speaker does not necessarily have authority over the addressee, e.g. as in a friend to another friend (one telling the other not to eat chocolate because he has diabetes).
You must not eat that: It definitely implies a prohibition uttered by a speaker who has the authority to forbid the addressee to do that action (see mother/child example above).
Generally speaking, must not sounds much more constraining than can not ('authority' is the key word). Saying "You can not" might as well sound like simply stating a fact rather than giving an order.


text:
Q: How do Facebook, Google and other large applications do their CSS and JavaScript files? Facebook: http://static.ak.fbcdn.net/rsrc.php/v1/yh/r/u2OL99TwlfU.css

Google: http://ssl.gstatic.com/gb/js/sem_cf9545d69b4bd3d22ed10206010c8b23.js
There are other sites, like Tagged which also uses this kind of method.
How do these sites and other large applications do these files? I assume when they update their file, the URL actually changes so that the cache doesn't recognise the URL and reloads the new file.
I'm actually more confused about Facebook's rsrc.php, but I still don't quite understand the rest. It appears Google's random string is an MD5 of something.
I do want something like this on my websites, large applications use it so it must be useful to use - even if I didn't decide to use, the knowledge of it may be beneficial in the near future.

A: (I am the original author of rsrc.php and Facebook's Haste static resource management system.)
You can find a description of some of the challenges Facebook encountered with static resource management and how it solved them here, in the Phabricator documentation:
https://secure.phabricator.com/book/phabflavor/article/soon_static_resources/
To the specific question, the rsrc.php URIs are like that (with "rsrc.php" in them) specifically because we didn't have a global Apache rewrite rule in 2007 when I wrote rsrc.php and adding, deploying and testing one for some more elegant URI didn't seem worth bothering with (in PHP, you can read the remainder of the URI after the "x.php" file part at runtime). So that part is just a PHP implementation artifact.
The other path components have been used for various things over the years, like an emergency version number we can bump globally to break everyone's caches if something goes wrong with the cache pipeline, a hash checksum so we can distinguish between valid and garbage requests for logging, internal flags which alter the cache policy of the returned resource for development, and flavors of a resource (e.g., tailored to a specific browser or localized to a specific language).

A: Facebook and Google both use a md5 suffix in their static resource file name.
First, it's a general optimization for performance, we can versioning a static resource use the md5 of its file content (after minification) and set the cache-control = 10 years (nginx or apache). If you press forward/back button on your browser or view the page second time, the file will be retrieved from your local disk, not through the network (except you press the reload button, there will be a 304).
Second, when you publish code online, you can first push all static resource, they will not conflict with old ones. And then you push all server-side code, all user will not have error access to your page.


text:
Q: Can't install evdev on python 3.9 I'm trying to make a program in which I need to emulate a key press from a gamepad, I looked for it a lot but the only module I found is python-evdev. I have tried to install it through the use of

pip install evdev

but there isn't any matching version. Also I have tried to download the module and manually move it into the site-packages folder (I have no idea if this is correct or not) but when i try to import the module i get this error:

ImportError: cannot import name '_ecodes' from partially initialized module 'evdev' (most likely due to a circular import).

Is there something I did wrong or maybe is there another library which does the same thing?


text:
Q: Get mobile version in iframe I have an iframe on my website and on the PC is everything fine. But when I open the site on my mobile phone I get the "mobile" site but the iframe parts are still like on the PC.
The iframes are just links to a big site that has an own mobile version and when I open this site on my mobile phone i get the mobile version, but not when its linked in my iframe.
I want that it change in the iframe.
I tried some stuff but it doesn't work.
Do you have some tips?
max

A: For others coming here via Google:
You have to set the viewport in the parent as explained in iFrame and media query issue


text:
Q: How to search and extract values from a Hashmap Stored in Arraylist List<Map<String, String>> personList = new ArrayList<HashMap<String, String>> ();
String tempcnic = SBox.getText().toString();
HashMap<String,String> temp = new HashMap<>();
for (int i = 0; i < personlistcopy.size(); i++) {
    temp = personlistcopy.get(i);
    if (temp.get(TAG_CNIC) == tempcnic) {
        Toast.makeText(History.this, temp.get(TAG_CNIC), Toast.LENGTH_SHORT).show();
        personList2.add(temp);
    }
    temp = null;
}

I have an ArrayList containing HashMaps,
HashMap contains 4 keys with corresponding values.

*

*name

*Cnic

*Date

*Time

Kindly help me in doing "Search and find all HashMaps in ArrayList with given cnic and add them to a new ArrayList. The new ArrayList will have all records with that cnic."

A: Here's how to do it with Java 8's stream:
List<Map<String, String>> personList = new ArrayList<>(); //Your list

List<Map<String,String>> filtered = personList.stream()
    .filter(p -> "your_cnic".equals(p.get("cnic")))
    .collect(Collectors.toList());

If you want case insensitive comparison, you can use equalsIgnoreCase instead of equals.
Here is non-stream solution (for Java 5, 6 and 7):
List<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>(); //Your list
List<HashMap<String,String>> filtered = new ArrayList<HashMap<String,String>>();

for(HashMap<String, String> person : personList){
    if("your_cnic".equals(person.get("cnic"))){
        filtered.add(person);
    }
}


text:
Q: Algorithm that solves a system of linear equations over finite fields when a parameter is needed I was reading Kipnis' and Shamir's paper on Cryptanalysis of the HFE Public Key Cryptosystem by Relinearisation and I wanted to implement the example at the end in Octave without using any additional packages (e.g symbolic ...). I would like to create an algorithm that solves systems of linear equations over finite fields (q = 7 in this case)
where you have more variables than equations (in this case I am going to need one parameter).
I'm pretty new to this topic so I tried setting $y_{12} = z$ (example from the paper) and subtracted the $y_{12}$ vector from the solution for $z = ${$1, 2$} and solved the system of equations for the two new solutions to try to find the slope of the parametric solutions:
$ y_{11} = 2 + 5z \\
  y_{12} = z \\
  y_{13} = 3 + 2z \\
  ... $
This didn't seem to work for reasons which I think I know and now I'm clueless on what to do. I'd appreciate your help.
To save you a bit of time copying the equations onto Octave, I'll leave you with this:
eq = [3 5 5 2 6 4 5; 6 1 4 4 5 1 6; 5 2 6 2 3 2 5; 2 0 1 6 5 5 0; 4 6 2 5 1 4 0];


text:
Q: How to Change the Confirm box buttons and Display the error logo using asp.net 2.0? i am developing one asp.net application,i am using one gridview and bind the data and one delete button also displayed, so click the delete button first display the confirm message box.(Do u want Delete?) ,confirm box display the ok and cancel buttons but my problem is i want to display the Yes and No buttons and display the error image . How to write the code in RowDeleting Event or Any javaScript, pls tel me it is very urgent
Thank u
hemanth

A: You can use the the Ajax Control Toolkit's confirm button extender have a look here Confirm Button  Extender also math berseths post also will you help you with the code. Look here Including Yes/No in gridview


text:
Q: JUnit examples to teach I need good examples of Junit tests for Java classes, to spend in training, anyone have suggestions of good examples?

A: Here is a good one which shows you step by step what you have to do, including screenshots with Eclipse also.

A: From memory, I think Kent Beck's Test Driven Development walks through some good examples. Probably a good book to refer to in testing training courses. http://www.amazon.co.uk/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530

A: You can have a look at open source software - maybe a library which you use for yourself. They often contain unit tests, e.g.:

*

*Apache Commons lang test code

*Google guava libraries test code

*and for sure a lot more....

I do not know what you mean with 'to spend in training' but if you will use it for other purpose than to train yourself check the license first.

A: JUnit tests are somehow based on your procedures. It depends what do you want to test. For example, if you want to test if for specific input, you receive specific output, you can use assertEquals. For writing a simple step by step JUnit test in Java in Eclipse, look at "Write Simple JUnit Test".
For thorough information, look at "Unit Test Tutorials".


text:
Q: Take an input single dimensional array [1,2,3,4] and output the product of the integers excluding the current index [24,12,8,6]; Guys I need your opinion; I've encountered this earlier during my interview, I just want to confirm I understood the question right and I got the answer correctly. Thank you. Please check the question and my answer below:
Take an input single dimensional array [1,2,3,4] and output the product of the integers excluding the current index [24,12,8,6];
//My answer
function calculate(values:Array):Array {
    var resultArray:Array = new Array();
    for(var i:int = 0; i < values.length; i++) {
        var getVal1:Number = 1;
        for(var k:int = 0; k <= values.length; k++) {
            if(i != k) {
                var getVal2:Number = values[k];
                getVal1 *= getVal2;
            }
        }
        resultArray.push(getVal1);
    }
    return resultArray;
}

A: Nested loops seems like a very messy way to go.
Assuming relatively up-to-date browser (IE 8 and below are out) or suitable shim:
var resultArray = sourceArray.map(function(val,ind,arr) {
    arr = arr.slice(0); // create copy of array to work on here
    arr.splice(ind,1); // remove current item from array
    return arr.reduce(function(prev,curr) {return prev*curr;},1);
});

Array.prototype.map
Array.prototype.reduce
EDIT Here's another way that should be more efficient:
var product = sourceArray.reduce(function(prev,curr) {return prev*curr;},1);
var resultArray = sourceArray.map(function(val) {return product/val;});

A: Your solution gives the correct answer, but there is a much more efficient method to calculate the new array:
function calculate(values:Array):Array {
    var resultArray:Array = new Array();
    var product:int = 1;

    for(var i:int = 0; i < values.length; i++) {
        product *= values[i];
    }

    for(var i:int = 0; i < values.length; i++) {
        resultArray.push(product / values[i]);
    }

    return resultArray;
}

This solution has O(n) execution time, while your code has O(n²) execution time.

A: That should work. You can do it easier and more efficiently by multiplying all items first:
function calculate(values) {
  var prod = 1;
  for (var i = 0; i < values.length; i++) prod *= values[i];
  var result = [];
  for (i = 0; i < values.length; i++) result.push(prod / values[i]);
  return result;
}

A: I believe that my code below is very easy to read. And has no nested loops, but two consecutives. My answer would be:
function calculate(array){
    var total = array.reduce(function(a, b){
        return a * b;
    });

    return array.map(function(element){
        return total / element;
    });
}

A: Though I like @Kolink's short-and-efficient solution best, here's another way to solve the task - not using division but still being in O(n):
function calculate(values) {
    var acc = 1,
        l = values.length,
        result = new Array(l);
    for (var i=0; i<l; i++) {
        result[i] = acc;
        acc *= values[i];
    }
    acc = 1;
    while(i--) {
        result[i] *= acc;
        acc *= values[i]
    }
    return result;
}

Or, the same thing but a little obfuscated*:
function calculate(values) {
    var acc = 1,
        i = 0,
        l = values.length,
        result = new Array(l);
    if (l)
        result[i] = 1;
    while( ++i < l)
        result[i] = acc *= values[i-1];
    i -= acc = 1;
    while (i--)
        result[i] *= acc *= values[i+1];
    return result;
}

*: I like shorthand operators!


text:
Q: Laravel post request doesn't return correct data My form is not updating the information when I manually change the textbox fields. When i get a confirmation email I get the wrong calculation in this example. When i process the information in my controllers it gets put correct in the database but incorrect in the email to my customer. even though it uses the same information.
$('#two-inputs').dateRangePicker(
    {
        separator : ' tot ',
        startDate: '{{$start_date->start_date}}',
        endDate: '{{$end_date->end_date}}',
        beforeShowDay: function(date){
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [ disabled.indexOf(string) == -1 ]
        },
        getValue: function()
        {
            if ($('#date-range200').val() && $('#date-range201').val() )
                return $('#date-range200').val() + ' to ' + $('#date-range201').val();
            else
                return '';
        },
        setValue: function(s,s1,s2)
        {
            var total = 0;
            var temp_s1 = s1.split("-");
            var temp_s2 = s2.split("-");
            $('#date-range200').val(temp_s1[2] + "-" + temp_s1[1] + "-" + temp_s1[0]);
            $('#date-range201').val(temp_s2[2] + "-" + temp_s2[1] + "-" + temp_s2[0]);
            var start_date = s1;
            var s1 = s1.split('-');
            var s1 = new Date(s1[0], s1[1] - 1, s1[2]);
            var s2 = s2.split('-');
            var s2 = new Date(s2[0], s2[1] - 1, s2[2]);
            //alert(datediff(s1, s2));
            if(obj[$('#date-range200').val()] == null){
                var prijs = {{$highest_price->name}};
            } else {
                var prijs = obj[$('#date-range200').val()];
            }

            var extra_kosten = {{$blog->schoonmaak}};
            total += extra_kosten;
            total += datediff(s1, s2)*prijs;

            $("#aantal_nachten").val(datediff(s1, s2));
            $("#prijs_per_nacht").val(prijs);
            $("#totaal_prijs_nachten").val(total);
            $("#prijs").html(prijs);
            $("#nachten").html(datediff(s1, s2));
            $("#prijs_nachten").html(datediff(s1, s2)*prijs);
            $("#extra_kosten").html(extra_kosten);
            $("#totaal_prijs").html(total);
            //alert(start_date);
            //alert(obj[$('#date-range200').val()]);
            $("#prijstable").slideDown( "slow");

        }
    });

Screenshot of the input fields

Screenshot of what i get in the email i receive

Screenshot of how it shows in my database


text:
Q: "if" statement based on command? I understand from Python's documentation that I can check conditions with the format:
if x < 0:
else:
    print('Else code')

I want to run a command and check whether that command is successful, but I get a "SyntaxError: invalid syntax" error.  Help!
My format is roughly:
if myCommand(parameters):
    print("It worked")
else:
    print("It failed")
    if mySecondCommand(parameters):
        print("2nd command worked")
    else:
        print("2nd command failed")

And here's my actual code using the Netmiko library:
from netmiko import ConnectHandler
if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword'):
    print("Domain login succeeded.")
else:
    print("Domain login failed.")
    if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='StandardUsername', password='StandardPassword'):
        print("Standard login worked")
    else:
        print("Standard login failed")

The output I get is:
if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.444', username='domain.login', password='DomainPassword'):
               ^
SyntaxError: invalid syntax

A: Considering the comments provided to this question, it seems that what you essentially need is how to know if the connection failed. Since a failed connection raises an exception, if-statements are not enough / needed to achieve what you want. Instead, you would like to do this:
from netmiko import ConnectHandler
try:
    net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword')
    print("Domain login succeeded.")
except:
    print("Domain login failed.")

    try:
        net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44',username='StandardUsername', password='StandardPassword')
        print("Standard login worked")
    except:
        print("Standard login failed")

If you have not come across "try-except" statements in Python, I suggest you looked them up.

A: Your original snippet will raise a syntax error, you can't run this (thanks to KyrST):
if x < 0:
else:
    print('Else code')

you'd want this:
if not x < 0:
    print("Not X < 0 code")

The issue that caused the error lies here:
if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword'):

In Python, you cannot assign a value inside a condition, and even if you did, what would you compare it to?
what you should do is instead of the above:
net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword'):
if net_connect == some_check_here:

some_check_here being some value you can use to compare if something goes wrong, I'm not sure how netmiko handles errors, my guess is that you'll have to catch exceptions.

A: You are trying to assign a variable within an if statement (not allowed in Python), instead of checking for equality.
Try:
 if net_connect == ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword'):
    ...

and notice the use of == instead of =.

A: Unfortunately, Python can't have variable assignment inside an if statement - it can't be used as an expression.
with the = operator, you're attempting to assign the net_connect variable, rather than compare it.
the == operator is the correct operator for comparison, so:
if net_connect == ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword'): is correct, as you're comparing the two.
Your original, if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.444', username='domain.login', password='DomainPassword'):, the ConnectHandler to net_connect.


text:
Q: Why explicit string conversion is required in .format method in python is required? The following code is giving TypeError.
from sklearn.model_selection import KFold
kf = KFold(n_splits=5,shuffle=False).split(range(25))

print('{} {:^61} {}'.format('Iteration','Training set observations','Testing set observations'))
for iteration, data in enumerate(kf, start=3):
    print('{:^9} {} {:^25}'.format(iteration, data[0], data[1]))

TypeError: unsupported format string passed to
  numpy.ndarray.format

The code gives correct output when we use str(data[1])
Why is this explicit string conversion required ?

A: From, e.g., https://docs.python.org/3.4/library/string.html#format-specification-mini-language:

A general convention is that an empty format string ("") produces the same result as if you had called str() on the value. A non-empty format string typically modifies the result.

So, when :^25 is matched to data[1], it calls the __format__() method of data[1] object, which is a numpy.ndarray. These objects follow Python's list behavior of raising a TypeError when format string is non-empty. An empty format string results in str() being called on data[0] (in your example) so that would work. A non-empty format string (i.e., :^25 for data[1]) fails on lists in Python because a standard list in Python can be a collection of heterogenous objects and therefore a single format specification might not work for a list like this one: [1, 2.3, 'four']. numpy simply follows the same convention.

Also see https://github.com/numpy/numpy/issues/5543 for an open issue on numpy's GitHub page. It seems that issue is concerned about the same issue that you mention in your post.


text:
Q: Is the cardinals of $P(P(\Bbb{N}))$ $C$ or $2^C$? Let us look at $P(P(\Bbb{N}))$. Is the cardinals $C$ or $2^C$? Really confusing...

A: The cardinality of $\mathcal P(X)$ is $2^{|X|}$. So we do this in steps:$$|\cal P(P(\Bbb N))|=2^{|P(\Bbb N)|}=2^\frak c.$$

A: The cardinal of the powerset of the natural numbers is the cardinality of the continuum. When you take again the powerset you get the cardinality of the power set of the continuum, that is $2^C$.
In any case, the cardinality of a powerset of a set is always larger than the cardinality of the set. This also applies to the case that the set is $P(\mathbb{N})$.


text:
Q: How to enable large partition key option on existing container in Azure cosmos db I see that cosmosDb now supports large partition keys (up to 2kbs) but by default it uses 100 bytes to store that data.
In microsoft docs i've found how this option can be enabled for existing containers - link
Is there a way to enable this somehow for already existing containers ? And is there any risk in doing that ?

A: You will need to migrate all documents to a new collection with the option enabled.
Because this option changes the result of the hash operation against the partition key documents could end up hashed into different partitions with new and old schemes so it can't be done on an existing collection (in the same way as changing the partition key itself can't be done to an existing collection).
Regarding risks I'm not aware of any other than listed in the documentation that you yourself posted.

unless you need support for an older Cosmos SDK or application that does not support this feature, it is always recommended to configure your container with support for large partition keys. .... Currently, you cannot use containers with large partition key within
in Power BI and Azure Logic Apps. You can use containers without a
large partition key from these applications.


text:
Q: Equality of Hausdorff dimension Definitions: Let $A\subseteq\mathbb{R.}$
Define the diameter of $A$ by
$$|A| = \sup_{x,y\in A}|x-y|.$$
For $A\subseteq\mathbb{R}$ with $|A|<\infty$ and $\alpha>0,$ define the $\alpha$-cover length of $A$ by
$$H_\alpha(A) = \inf\bigg\{ \sum_{n=1}^\infty |S_n|^\alpha:\{S_n\}_{n\in\mathbb{N}} \text{ is a countable cover of }A \bigg\}.$$
The Haudorff dimension of $A$ is defined by
$$\dim_H(A)=\inf \{\alpha >0:H_\alpha(A)=0\}.$$
..............................................................................................................................................................
In class, we have proven that
$$\dim_H(A) = \sup\{\alpha\geq 0:H_\alpha(A)>0\}.$$

Question: To prove $\dim_H(A) = c\in\mathbb{R},$ is it enough to prove that there exists a single countable cover such that $H_\alpha(A)>0$ if $\alpha<c, H_\alpha(A)=0$ if $\alpha>c?$

For example, let us consider the following propostion.

Proposition: Let $C$ be the Cantor Middle Third set.
  Prove that
  $$\dim_H(C)=\log_32.$$

To prove the above proposition, one can let $\alpha = \log_32$ and consider $\alpha'>\alpha.$
For $n\geq 1,$ let $I_1,...,I_{2^n}$ be the set of subintervals that made up of $C_n,$ where
$$C=\bigcap_{n=1}^\infty C_n.$$
Clearly $\{I_1,...,I_{2^n}\}$ is a cover for $C.$
Note that
$$\sum_{k=1}^{2^n}|I_k|^{\alpha'} = \sum_{k=1}^{2^n}(3^{-n})^{\alpha'} = 2^n(3^{-n\alpha'}) = e^{n(\ln 2-\alpha' \ln3)} = e^{n \ln 3(\alpha - \alpha')}.$$
Since $\alpha - \alpha' <0,$ as $n\to\infty,$ the above sum tends to $0.$
So it implies that
$$\dim_H(C) \leq \log_32.$$
After this, one needs to prove that $\dim_H(C)\geq \log_32$ also holds.
But by using supremum definition of $\dim_H(C)$ and the cover $\{I_1,...,I_{2^n}\},$ can we conclude that
$$\dim_H(C) = \log_32?$$
More precisely, for any $\alpha<\alpha',$ one can use the same cover and calculation above to obtain
$$\sum_{k=1}^{2^n}|I_k|^{\alpha'} = e^{n\ln 3(\alpha-\alpha')}.$$
Since $\alpha-\alpha'>0,$ therefore
$$\dim_H(C) \geq \log_32.$$

A: No, a single cover won't do. In order to show that $\dim_H (C) \geq \log_3 2$ using the result proved in class you have to show that $H_{\alpha} (C) >0$ for some $\alpha  \geq \log_3 2$ and  $H_{\alpha} (C) $ is defined as an infimum over all covers. For this you have to consider an arbitrary cover.


text:
Q: Dom string doesn't change after manipulation with jQuery attr I'm making a js-based epub reader as a weekend project and I'm trying to change the src attribute of the images on each of the book's pages from image urls to data URI's loaded from the epub zip. Here's my function:
//page contents is just an html string of the book's page
pageContents = GlobalZipLoader.load('epub.zip://' + pageLocation);
pageContents = replaceImages(pageContents)

...

function replaceImages(pageContents){
  $(pageContents).find('img').each(function(){
    var domImage = $(this);

    //this is something like ".../Images/img.jpg"
    var imageLocation = domImage.attr('src');

    //this returns the proper data-uri representation of the image
    var dataUri = GlobalZipLoader.loadImage('epub.zip://' + imageLocation);

    //this doesn't seem to "stick"
    domImage.attr('src', dataUri);
  });
  return pageContents;
}

The returned pageContents from the replaceImages functions still has the old src attributes. I can provide more detail if needed but any help would be very much appreciated.
Correct answer thanks to The System Restart and Ilia G:
function replaceImages(pageContents) {
    newContent = $(pageContent);
    ... manip ...
    return newContent;
}

A: You don't need to clone it. Simply set pageContents = $(pageContents);, then perform your image replacement on pageContents, then return pageContents.html();

A: you should try to change the image src after image load complete;
and I think this is happening with in loadImage function.
According to your update question:
You don't need any clone(), I think. Just store pageContents in a tempContents variable and use that variable

A: Since pageContents is just a string, you'll need to return the modified version of it. Try this:
function replaceImages(pageContents){
  // save jQuery object
  var $pageContents = $(pageContents);

  $pageContents.find('img').each(function(){
    var domImage = $(this);

    //this is something like ".../Images/img.jpg"
    var imageLocation = domImage.attr('src');

    //this returns the proper data-uri representation of the image
    var dataUri = GlobalZipLoader.loadImage('epub.zip://' + imageLocation);

    //this doesn't seem to "stick"
    domImage.attr('src', dataUri);
  });

  // return contents of the modified jQuery object
  return $pageContents.html();
}


text:
Q: Can the Google Calendar API events watch be used without risking to exceed the usage quotas? I am using the Google Calendar API to preprocess events that are being added (adjust their content depending on certain values they may contain). This means that theoretically I need to update any number of events at any given time, depending on how many are created.
The Google Calendar API has usage quotas, especially one stating a maximum of 500 operations per 100 seconds.
To tackle this I am using a time-based trigger (every 2 minutes) that does up to 500 operations (and only updates sync tokens when all events are processed). The downside of this approach is that I have to run a check every 2 minutes, whether or not anything has actually changed.
I would like to replace the time-based trigger with a watch. I'm not sure though if there is any way to limit the amount of watch calls so that I can ensure the 100 seconds quota is not exceeded.
My research so far shows me that it cannot be done. I'm hoping I'm wrong. Any ideas on how this can be solved?

A: AFAIK, that is one of the best practice suggested by Google. Using watch and push notification allows you to eliminate the extra network and compute costs involved with polling resources to determine if they have changed. Here are some tips to best manage working within the quota from this blog:

*

*Use push notifications instead of polling.

*If you cannot avoid polling, make sure you only poll when necessary (for example poll very seldomly at night).

*Use incremental synchronization with sync tokens for all collections instead of repeatedly retrieving all the entries.

*Increase page size to retrieve more data at once by using the maxResults parameter.

*Update events when they change, avoid re-creating all the events on every sync.

*Use exponential backoff for error retries.

Also, if you cannot avoid exceeding to your current limit. You can always request for additional quota.


text:
Q: unclosable application Without Process First excuse my for my bad English language
i'm Writing a security application for my company and i want to prevent users from opening specific program like torrent in my application. but this is not the problem. the problem begin where users can close my application some how....
they can end process and ...
i need some solution to Hide my application from users or make it Unclosable
i was thinking to something like Network Notify icon or Clock in windows, i read about Explorer extensions but they don't help me because they already Closable
by the way i need application start working on computer start-up Automatically
thanks Everybody

A: Execute your watcher as a windows service and provider a user gui that only give some visual feedback to the user from the service by using some kind of inter-process communication. If the user closes the gui, the service still runs in the background.
But if your users have local administrator rights they can always stop your program (or service) somehow, otherwise they wouldn't be administrators of the system anymore.


text:
Q: A couple of inequality / similarity that don't make sense to me. I was reading thru the proof for a combinatorics problem, but there were a couple places in there that gave me pause. In particular, one part of the proof had the following:
$${n \choose t}\frac{2}{2^{t \choose 2}} \leq \frac{n^t}{t!} \frac{2}{2^{t \choose 2}} $$ (where $n$ is some arbitrarily large number and $t=2log_2 n$)
Another part of it had the following similarity:
$$\frac{2n}{(2log_2n)!} \approx \frac{2n}{({2log_2n}/{e})^{2log_2n}}$$
There was no explanation provided for either of the above. I'd appreciate any help.

A: The first one is easy. If you compare the two sides, it's really just asserting that
$${n\choose t} \leq\frac{n^t}{t!}$$
But that follows quickly from the fact that
$${n\choose t}=\frac{n!}{t!(n-t)!}=\frac{\overbrace{n(n-1)(n-2)\cdots(n-t+1)}^{t{\textrm{ factors}}}}{t!}$$
since each of the factors in the last numerator are no more than $n$.

A: What you're seeing is that$\frac{n!}{(n-t)!}$ is best understood as having $n$ terms above and $n-t$ of those are cancelled by the denominator. So this expression is a product of $t$ terms all of which are less than $n$. Hence $\frac{n!}{(n-t)!}\leq n^t$ and so $\binom n t =\frac{n!}{(n-t)!t!}\leq \frac{n^t}{t!}$.
The second similarity is by the Sterling approximation.


text:
Q: How to remove gogletab.com from Firefox/Chrome/IE in Windows 10? I have my system affected by gogletab.com new tab page virus which doesnt let me to use google.co.in in any browser (Firefox, Chrome, IE). It also generates and redirects me to some ad websites and third party spam websites.
Help me in removing this.
Methods Tried:

*

*Browser addon checks

*Reinstalled each browser

*Register Clean up

*Services clean up

*Task Manager unwanted program clean up

A: Generally, You need to use an adware removal tool to remove gogletab.com,
which can detect every part of the hijacker nd uninstall it quickly
and cleanly.
Delete gogletab.com/en From Windows 10

*

*Right click on Windows 10 Start button and select the "Control Panel"
option.

*Now got to the "Programs" category and click "Uninstall a Program" option.

*Select the gogletab.com/en from the list of installed programs.

*Finally Click on Uninstall or Remove button to delete the threat.

*Click on Yes button if Windows ask for confirmation.

Eliminate gogletab.com/en From Windows 8/8.1
Windows 8/8.1 users just follow the below steps to eliminate this nasty virus manually from your PC.

*

*At first drag mouse pointer and right-click edge at screen to get
Quick Access Menu where need to choose search.

*Now Type Control Panel from list or right click at the bottom left
corner (Start button) thereby to select Control Panel.

*Now click on Uninstall a program option after Control Panel Window get opened.

*After that, Programs and Features or Uninstall a Program screen emerged where you would view programs list as well as software, which currently installed on PC.

*Find gogletab.com/enthen press 'Uninstall" after clicking on it.


text:
Q: CMake : build only tests In my CMakeLists.txt, I have the following tests:
  enable_testing()

  add_executable(first_test tests/first.cpp)
  target_link_libraries(first_test CppUTest)
  add_test(NAME FIRST COMMAND first_test)

  add_executable(second_test tests/second.cpp)
  target_link_libraries(second_test CppUTest)
  add_test(NAME SECOND COMMAND second_test)

So to build my tests, I run:
make -Cbuild first_test
make -Cbuild second_test

I'm looking for a generic command to build all tests defined in the CMakeLists.txt.
Something like this will be perfect but does not work:
make -Cbuild *_test


text:
Q: Direct BeginUmbracoForm action to another page I am trying to set up a global search box that posts to a search page in umbraco 7. This template uses a shared partial containing Html.BeginUmbracoForm() that points to a SurfaceController.
Since this is a global control, I want the form to be posted to the /search page instead of the current page. BeginUmbracoForm only seems to be able to post to the current page unless I'm mistaken.
I want something like RedirectToUmbracoPage(id), but clears this post values on redirect.
Is there a way to get an ActionResult like CurrentUmbracoPage which keeps the post values?

A: I would not try using surfacecontrollers for that purpose.  Surfacecontrollers are auto routed.  They are created to (e.g.) make @Html.Action(...) work on every umbraco page.  Including postbacks on these actions or macros.
If you only need a "redirect" to the /search page, you don't need a surface controller.  A simple partial will do the job.
<form action="/search" method="get">
  Search <input type="search" name="q" />
</form>

Of course you can replace the url using some Umbraco logic like @Umbraco.TypedContentSingleAtXPath("//Search") or other Umbraco magic.
In the umbraco documentation project is an example where Html.Action is used.


text:
Q: For all $m\ge 2$, the last digit of $ 2^{2^m} $ is 6 How to prove that for  $ \forall m\in \Bbb N $ such that $m\ge 2$, the last digit of $  2^{2^m} $ is 6?

A: $$2^{(2^m)}=(2^4)^{(2^{m-2})}=(16)^{(2^{m-2})}\equiv6^{(2^{m-2})}\pmod{10}$$
Now, $6^{n+1}-6=6(6^n-1)\equiv0\pmod {10}$ as $6^n-1$ is divisible by $(6-1)=5$ if integer $n\ge 0$
$\implies 6^r\equiv6\pmod{10}$ if $r\ge1$
So we need  $2^{m-2}\ge1\implies m-2\ge 0\implies m\ge2$

A: Hint: The last digit of a number is determined by what it is modulo 10. Also, use induction.

A: Use Fermat's little theorem to show that $2^{2^m} \equiv 1 [5]$ and deduce from Chinese remainder theorem that $2^{2^m} \equiv 6[10]$.


text:
Q: Can I map $\Gamma(z+\frac{1}{2})$ to $f(z)\Gamma(z)$? I am looking for a similar property $\Gamma(z+1)=z\Gamma(z)$ but with $\Gamma(z+\frac{1}{2})$. I suspect it has something to do with "duplication formula", maybe.

A: For $z>1$, you could write
$$f(z)=\sqrt z \,\sum_{n=0}^\infty \frac{a_n}{b_n} z^{-n}$$ where the
$a_n$ and $b_n$ form respectively sequences $A143503$ and $A061549$ in $OEIS$.
But, using the Gaussian hypergeometric function, there is an identity (have a look here)
$$\color{blue}{f(z)=\sqrt{\left(z-\frac{1}{2}\right) \,
   _2F_1\left(-\frac{1}{2},-\frac{1}{2};z-\frac{1}{2};1\right)}}$$


text:
Q: Borrar Registro LINQ to ENTITY Intento borrar un registro de esta forma:
 var cSelect = from x in contexto.BloqueoExcursion
                      where x.BLE_BloqueoID == BloqueoID
                      select x;

        foreach (var item in cSelect)
        {
            var eSelect = new BloqueoExcursion { BloqueoExcursionId = item.BloqueoExcursionId, BLE_BloqueoID = item.BLE_BloqueoID, BLE_ExcursionId = item.BLE_ExcursionId, BLE_PrecioExc = item.BLE_PrecioExc };
           contexto.Entry(eSelect).State = System.Data.Entity.EntityState.Deleted;

        }

Luego he intentado así:
contexto.ChangeObjectState(eSelect, System.Data.EntityState.Deleted);

Y también así:
contexto.BloqueoExcursion.Remove(eSelect);

Las dos primeras opciones me dan el siguiente error:

System.InvalidOperationException: 'Error al adjuntar una entidad de tipo 'Gerente_Mayorista.Models.BloqueoExcursion' porque otra entidad del mismo tipo ya tiene el mismo valor de clave principal. Esto puede ocurrir cuando se usa el método 'Attach' o cuando se establece el estado de una entidad en 'Unchanged' o 'Modified' si algunas entidades del gráfico tienen valores de clave en conflicto. Puede deberse a que algunas entidades son nuevas y no han recibido todavía los valores de clave generados por la base de datos. En este caso, use el método 'Add' o el estado de entidad 'Added' para hacer un seguimiento del gráfico y establezca después el estado de las entidades que no son nuevas como 'Unchanged' o 'Modified', según corresponda.'

Si uso esta instrucción:
contexto.BloqueoExcursion.Remove(eSelect);

Me dice esto:

System.InvalidOperationException: 'El objeto no se puede eliminar porque se encontró en el ObjectStateManager.'

RECALCO QUE:

*

*No uso entidades relacionadas.

*No tengo relaciones en las tablas.

*El Linq si trae datos (2 registros).

Gracias por la ayuda.

A: Prueba lo siguiente:
var cSelect = from x in contexto.BloqueoExcursion
                  where x.BLE_BloqueoID == BloqueoID
                  select x;

contexto.BloqueoExcursion.RemoveRange(cSelect);
contexto.SaveChanges();

O mejor aún:
contexto.BloqueoExcursion.RemoveRange(contexto.BloqueoExcursion.Where(x => x.BLE_BloqueoID == BloqueoID));
contexto.SaveChanges();

En el caso de contexto.BloqueoExcursion.Remove(eSelect); el error se debe a que tratas de borrar una entidad que no está en el DbSet porque la acabas de instanciar. Debes referirte a las mismas entidades que sacaste del contexto.


text:
Q: Finding all invariant measures for a (continiuous) Markov chain given by a Q-matrix Let $0<p<1$. I want to find all invariant measures $\pi$ for the asymmetric random walk on $Z$ given by the Q-matrix, that is defined as follows:
$q(x,x-1)=1-p, ~~q(x,x)=-1, ~~q(x,x+1)=p~~$ and zero elsewhere
For me a measure $\pi$ on $Z$ is invariant if
$\forall y\in Z, t>0: \pi(y)=\sum_{z\in Z}\pi(z) p_t(z,y)$,
where $p_t(z,y)$ is the probability that the Markov chain starting in $z$ takes the value $y$ at time $t$.
Except of the trivial one, that is $\pi\equiv c$ for $c\geq 0$ I can't find anything. But I'm quite sure that at least there exists no invariant distribution here.
Thanks in advance.


text:
Q: Communication between unix commands in Java In one commend , I'm trying to send data to System.out like this:
And in another command I'm trying to get this data from System.in.
It's strange because, it works once of many tries. I can try to run it 10 times and it's still inReader.ready() == false, and when I run it for example 11th time , it works.
Why ? How can I fix this? How to make it work everytime ?
Thanks, in advance !

A: You can't read your InputStream that way, since the data may not have been arrived at the second process yet. You can either read character by character, with something like:
InputStreamReader inReader = new InputStreamReader(System.in);
int data = inReader.read();
while (data != -1){
    ...
    data = inReader.read();
}

or simple read the input line by line, using:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

while ((String line = br.readLine()) != null) {
    ...
}

A: If your objective is to execute a shell command, don't use System.out but Runtime.getRuntime().exec(cmd) instead. Check out this question for more details.