Q:

Reactjs: Warning: React.createElement: type should not be null or undefined

this the full error

Warning: React.createElement: type should not be null or undefined. It should be a string (for DOM elements) or a ReactClass (for composite components).

and this is all I have in this view
import React, { Component } from 'react';
import Router, {Link, RouteHandler} from 'react-router';
import { Grid, Row, Column, List, ListItem } from '../../components/Layout';
import { RaisedButton, Paper } from 'material-ui';

const videosInformation = {
  time      : 25,
  gameId    : 15665,
  date      : '12 10 2015',
  gameName  : "Black Jack"
};

export default class Home extends Component {

  static contextTypes = {
    router  : React.PropTypes.func
  }

  render () {
    return <Grid>
      <Row>
        <Column>
          <Paper>
            <List subheader="Player Info">
              <ListItem primaryText={`Name: ${videosInformation.time}`} />
              <ListItem primaryText={`Nickname: ${videosInformation.date}`} />
              <ListItem primaryText={`Age: ${videosInformation.gameId}`} />
              <ListItem primaryText={`Language: ${videosInformation.gameName}`} />
            </List>
          </Paper>
        </Column>
        <Column>
          <iframe width="560" height="315" src="https://www.youtube.com/embed/Ta4xuThmAsQ" frameBorder="0" allowFullScreen></iframe>
        </Column>
      </Row>
    </Grid>;
  };

}

I am using Material-UI

A:

It is likely that your Layout file is not exporting one of the variables from this line
import { Grid, Row, Column, List, ListItem } from '../../components/Layout';

The warning would happen if one of those is undefined.

A:

I know the right solution has been found here but I just wanted to share another possible reason for the ReactJS React.createElement: type should not be null or undefined warning to trigger.
It can also happens when you have a circular dependency in your modules. Then, doing a console.log() of your imported module would return an empty object.
For further details, have a look at this other stackoverflow thread: Require returns an empty object

A:

Just in case anyone has run into this issue and the above solutions are not helping, all I had to do was move my top-level ReactDOM.render() function below the rest of the JavaScript to ensure all variables were initialized before being called. I was following the tutorial at https://reactjs.net/getting-started/tutorial_aspnet4.html


Q:

Set multiple datepickers' value based on one datepicker's selected date

I have follow jQuery UI Datepicker sample code
<!doctype html>

    <meta charset="utf-8">
    <title>jQuery UI Datepicker - Default functionality</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

    <link rel="stylesheet" href="/resources/demos/style.css">

Date1: <input type="text" id="datepicker1">

Date2: <input type="text" id="datepicker2">

Date3: <input type="text" id="datepicker3">

Date4: <input type="text" id="datepicker4">

I want to set date pickers 2,3 and 4's value based on value selected in datepicker1.
Let say if #datepicker1 have valud 12/05/2013 then I would like to show +1 date for each other jQuery datepickers like below
datepicker1 => 12/05/2013 then
datepicker2 => 12/06/2013
datepicker3 => 12/07/2013
datepicker4 => 12/08/2013

I tried above.
Can you please help?

A:

You can use the onSelect event and call setDate method:
$("#datepicker1, #datepicker2, #datepicker3, #datepicker4").datepicker();
$("#datepicker1").datepicker("option", "onSelect", function (dateText, inst) {
    var date1 = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);

    var date2 = new Date(date1.getTime());
    date2.setDate(date2.getDate() + 1);
    $("#datepicker2").datepicker("setDate", date2);

    var date3 = new Date(date1.getTime());
    date3.setDate(date3.getDate() + 2);
    $("#datepicker3").datepicker("setDate", date3);

    var date4 = new Date(date1.getTime());
    date4.setDate(date4.getDate() + 3);
    $("#datepicker4").datepicker("setDate", date4);
});

Demo here

The onSelect passes the date as a string so we convert it to JavaScript Date object for convenience, using the following jQuery UI datepicker utility function:
$.datepicker.parseDate( format, value[, settings] )

The expression:
inst.settings.dateFormat || $.datepicker._defaults.dateFormat

means use the dateFormat value specified on the datepicker, if there is one; otherwise use the dateFormat from datepicker defaults (which is "mm/dd/yy").


Q:

select range & copy/paste to notepad - Almost done

After a lot of work and testing (very pathetic indeed), I finally managed to select a range in worksheets, then copy/paste it in Notepad. The file shall be thereafter readen by another app. Unfortunately, the app reject the file and there is no way for me to debug why. The only message I have is an error occuring at last line.
Surprisingly, when I copy-paste to notepad by hand, it works. As far as my eyes can see, both txt files (the one writen with my sub() and the one from CP by hand) are exactly the same. I guess my eyes are wrong. I suspect there is at the end of last line or below last row maybe some white space I can not see. The only part of code I do not fully understand is, according to me, the place of the current issue.
Find below part of my code:
[code]
' RngSelect is a Variant and effectively a range of cells
' Txt is a Variant
' LastRow is a Long equal to last row number of my range

With RngSelect
For Lg1 = 1 To LastRow
    Txt = Txt & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(Lg1).Value)),vbTab)   ' copy each row
Next
End With

Open FilePath For Output As #1
Print #1, Mid$(Txt, Len(vbCrLf) + 1)
Close #1

RngSelect = Null
Txt = Null

End Sub

If it can help, my file to be imported by the other app can be in a csv format. Currently, my delimiter is Tab.
Thank you for help.

A:

Following this post, I finally managed to erase the last blank line at the bottom of my text . The the correct line now is : Print #1, Mid$(txt, Len(vbCrLf) + 1) ;
I then had to modify my LastRow, as it is the row number on my spreadsheet but not the last row number on my text file.
I shall now find a way to append the text in the text file.


Q:

Is there ever a valid reason to have a static method inside a non-static class?

The title is pretty much my entire question.
I'm doing a code review for an off-shore developer who has several static methods inside a non-static class. Before I challenge the developer and mark this as "needs changing", I just want to make sure.
I understand the purpose of a static class: It can not be instantiated and can be used directly. But I can't see any reason to have a static method in a non-static class.  Is there any valid use-case for this?
The methods in question are all private and are called from non-static methods.
Here's an example:
    public ViewResult ClaimDetails(ClaimDetails claim)
    {
        if (claim.ClaimNumber != 0)
        {
            claim = Get_ClaimDetails(claim);
        }
        return View("ClaimDetails", claim);
    }

    private static ClaimDetails Get_ClaimDetails(ClaimDetails claim)
    {
        ClaimsRepository claimsRepository = new ClaimsRepository();
        _claimDetails = new ClaimDetails();
        _claimDetails = claimsRepository.GetClaimDetails(claim.ClaimNumber);
        return _claimDetails;
    }

A:

There are a few things that would raise an eyebrow with me, but the method signature is fine.
static is a keyword that makes sure the method does not use instance members. That's great. It clearly signals this to other developers. I would have argued for the opposite side: a method should be marked static, except when needed otherwise.
Many tools and even Visual Studio itself would flag it if you did not mark it static: CA1822: Mark members as static.
Quoting Microsoft:

Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at run time for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

So to summarize it: it's perfectly fine as it is.

Reading all the additional comments: it seems the real problem is that an injected repository already exists and the whole method should scrapped and replaced by the line claim = this.injectedClaimsRepository.GetClaimDetails(claim.ClaimNumber);. But that's a whole other problem. The keyword static is perfectly fine if used correctly, the posted code did not show it wasn't.


Q:

Appium Android click on element in WebView crashes code, but is executed in the emulator

I am developing Appium tests for an Android app. The problem happens during the login to facebook which works through a WebView. The login to facebook is necessary for the app login and the app registration. The login to facebook is in both cases (app login and app registration) the same, so I execute in both cases the same method:
private void logInAtFacebook(String email, String password) {
    findElementWithTimeout(By.className("android.webkit.WebView"), 10);
    Set<String> contextHandles = driver.getContextHandles();
    for (String s : contextHandles) {
        if (s.contains("WEBVIEW")) {
            driver.context(s);
        }
    }

    findElement(By.xpath("//input[@name='email']")).sendKeys(email);
    findElement(By.xpath("//input[@name='pass']")).sendKeys(password);
    findElement(By.xpath("//button[@name='login']")).click();
    findElement(By.xpath("//button[@name='__CONFIRM__']")).click();

    driver.context("NATIVE_APP");
}

It is weird, that the app login with facebook works, but the app registration with facebook crashes. The second last line in the above method...
findElement(By.xpath("//button[@name='__CONFIRM__']")).click();

...doesn't return, but the button is clicked in the UI. In other words, the execution stops at this line, so that the next line...
driver.context("NATIVE_APP");

... is never executed. I am really confused. Why is the same code working for the app login, but not for the registration?!
Iv'e copied the logs from Android Studio:
First, the last lines before it crashes during app registration:
01-30 14:18:25.016 24439-24439/de.blabla W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.103 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.184 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.260 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.322 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.401 24439-24450/de.blabla  I/art: Background partial concurrent mark sweep GC freed 133(8KB) AllocSpace objects, 3(18MB) LOS objects, 13% free, 24MB/28MB, paused 9.861ms total 80.852ms
01-30 14:18:44.416 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.516 24439-24475/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df02443c260: ver 2 0 (tinfo 0x7df02440ce80)
01-30 14:18:44.633 24439-24439/de.blabla  W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 24439
01-30 14:18:44.807 24439-24475/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df02443c260: ver 2 0 (tinfo 0x7df02440ce80)
01-30 14:18:45.111 24439-24475/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df02443c260: ver 2 0 (tinfo 0x7df02440ce80)

And the same lines of the working app login:
01-30 14:21:17.179 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.464 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.573 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.640 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.644 25078-25089/de.blabla  I/art: Background partial concurrent mark sweep GC freed 156(6KB) AllocSpace objects, 2(12MB) LOS objects, 11% free, 30MB/34MB, paused 3.293ms total 143.091ms
01-30 14:21:30.717 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.843 25078-25112/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df024436640: ver 2 0 (tinfo 0x7df02440c900)
01-30 14:21:31.002 25078-25078/de.blabla  W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 25078
01-30 14:21:31.153 25078-25112/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df024436640: ver 2 0 (tinfo 0x7df02440c900)
01-30 14:21:31.564 25078-25112/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df024436640: ver 2 0 (tinfo 0x7df02440c900)
01-30 14:21:31.721 25078-25248/de.blabla ... *no it continues the test as it should*

A:

I found an inconvenient workaround, but it works for now:
private void logInAtFacebook(String email, String password) {
    findElementWithTimeout(By.className("android.webkit.WebView"), 10);
    Set<String> contextHandles = driver.getContextHandles();
    for (String s : contextHandles) {
        if (s.contains("WEBVIEW")) {
            driver.context(s);
        }
    }

    findElement(By.xpath("//input[@name='email']")).sendKeys(email);
    findElement(By.xpath("//input[@name='pass']")).sendKeys(password);
    findElement(By.xpath("//button[@name='login']")).

    driver.context("NATIVE_APP");

    driver.findElementByAccessibilityId("Continue").click();
}

The problem had something to do with the click within the WebView, so I decided to go back to context "NATIVE_APP" before the last click on the "Continue-Button" happens.
I'm still hoping for a better way to fix this!


Q:

Fluent NHibernate - Use Stored Proc for Delete

We've implemented Fluent NHibernate, but we have a need to execute a stored proc when deleting a row for a couple of tables.
Is there anyway to accomplish this without creating a command object and enlisting it with the session's transaction?

A:

Yes, this is possible using the SqlDelete(sprocName) call in your mapping class constructor.


Q:

Zend Framework: Method after controller action, but before view rendered

I'm new to Zend framework and can't find a clear answer on this. I essentially want some code to execute after a controller's logic for a page, but before the layout and view are rendered.
For example, I want to auto-refresh the flash messages and provide them to the layout/view automatically, so that I don't need to do so in every controller. This obviously needs to happen after the controller code has executed since it might add messages.
$this->view->messages = $this->_helper->flashMessenger->getMessages();

A:

The easiest way to do this is with a controller plugin, see http://framework.zend.com/manual/1.12/en/zend.controller.plugins.html. The postDispatch() method runs after your controller code but before the page is rendered.


Q:

XAML tostring in ContentControl

I am new to the XAML world and I'm fumbling my way through a lot of tutorials. One thing i'm stuck on is calling the .tostring on an object.
Here is mysetup
I have a listbox that is bound to a list of objects
I have a contentControl bound to the same list that displays the selected item from the listbox.
My ContentControl is as follows:
 <ContentControl Grid.Row="1" Margin="0,3,5,204" Name="Detail"
  Content="{Binding Source={StaticResource listingDataView}}"
  ContentTemplate="{StaticResource myContentTemplate}"
   HorizontalAlignment="Right" Width="231"/>

in myContentTemplate I have:
<DataTemplate x:Key="myContentTemplate">
            <StackPanel>
                <TextBlock Text="{Binding Path=Name}" />
                <!-- want to call .tostring here-->
            </StackPanel>
        </DataTemplate>

In the template I'd like to call .tostring on the object that is currently selected but i cant figure out how to do that?
thanks
Steph

A:

well looks like i asked this too soon. I found the answer in another question
How to reference current object in XAML
Quoting the answer from that thread:

According to the Data Binding
  Overview, you can use the "/" to
  indicate the current item. You can
  then navigate up and down the tree as
  needs be using the following type
  syntaxes:

Button Content="{Binding }" />
Button Content="{Binding Path=/}" />
Button Content="{Binding
Path=/Description}" />

Hope this helps someone else :)


Q:

how to handles if-else in groovy?

Here I'm passing the skipfolders variable in input if the skipfolders is true then it prints all files from Parent path and skip the sub folders.
otherwise it returns all files from all folders include sub folders as well. Here I wrote if-else conditions. When I execute this code in FileMaker
it executes without any errors and displayed result.but the if-else conditions does't working here.
Problem :
If-else conditions doesn't working here.it prints all files from FTP include subfolders.skipfolders condition doesn't working.
                       at this return allFiles.join('\n') + '\n'+ allFolderFiles.join('\n')+ '\n' prints directly and skipfolders condition doesn't working.
                       Please help how to use if-else conditions properly in fileMaker groovy.
start()
def start(){

        boolean skipfolders = false
        def store;
        def ftpClient = new FTPClient()
        ftpClient.connect(server)
        // println(ftpClient.replyString)
        ftpClient.login(user,pass)
        ftpClient.enterLocalPassiveMode()
        FTPFile[] fileslist = ftpClient.listFiles("/")
        FTPFile[] folderfileslist = ftpClient.listFiles("/sample")

  if(skipfolders == false){

       def allFiles = [];
       for(int i=0; i<fileslist.length; i++){
       String file_name = fileslist[i].getName()
       String file_timestamp = fileslist[i].getTimestamp().getTime()
       String s = '|' + file_name+ '|' + '/' +file_name+'|'  +file_timestamp
       allFiles << s
   }
      def allFolderFiles = [];
      for(int i=0; i<folderfileslist.length; i++){
      String folderfile_name = folderfileslist[i].getName()
      String folderfile_timestamp = folderfileslist[i].getTimestamp().getTime()
      String s1 = '|' +folderfile_name+ '|' + '/sample' +'|'+folderfile_name+'|'  +folderfile_timestamp
      allFolderFiles << s1
 }
  ftpClient.disconnect()
  return allFiles.join('\n') + '\n'+ allFolderFiles.join('\n')+ '\n'

}
else{
       def allFiles = [];
       for(int i=0; i<fileslist.length; i++){
       String file_name = fileslist[i].getName()
       String file_timestamp = fileslist[i].getTimestamp().getTime()
       String s = '|' + file_name+ '|' + '/' +file_name+'|'  +file_timestamp
       allFiles << s
   }
   ftpClient.disconnect()
   return allFiles.enter code herejoin('\n')
  }
}

    enter code here

if anybody having idea please let me know thanks.

A:

If i am understanding the question correctly, you want to set the skipfolders variable as a parameter.
As it is you have declared:
boolean skipfolders = false;

So the else is never reached as mentioned by user daggett in the question comment.
If you do something like this instead:
start(true) or start(false)
def start(boolean input){
    boolean skipfolders = input;
    ...
}

Then you can reach the else statement depending on your input.


Q:

Bedeutung und Grammatik von "wie nebenbei"

Aus dem Spiegel-Magazin:

Freunde als sozialpolitische Notwendigkeit also, als Ersatz für die traditionellen Institutionen fürsorglichen Zusammenlebens? Es klingt, als könne das Modell des pensionierten Politikers zumindest einige Probleme der modernen Gesellschaft wie nebenbei lösen.

Was bedeutet "wie nebenbei"? Hier und hier kann ich die Phrase nicht finden. Wie ist diese Verwendung konsequent mit der Tatsache, dass "nebenbei" ein Adverb ist?

A:

"Wie nebenbei" soll vermutlich "mühelos" bedeuten. Etwas ist so einfach, dass man es nebenbei machen kann.
Siehe auch: "Die Zeit vergeht wie im Flug." Anstelle eines Adverbs wird ein Vergleich hergestellt.


Q:

Offline conversion with Google client ID not as eCommerce transaction in Analytics

I am working on a project to measure offline conversions with the new Universal Analytics from Google.
When a lead gets the status "order" in my custom made lead management system, we sent the earlier grabbed Google client ID with the code below to Universal Analytics. The upload is working, although Analytics sees it as an ecommerce transaction.
Does anyone know how I can modify the code or Analytics settings to make sure that Google Analytics sees it not as eCommerce transaction?
My code for uploading the Google Client ID to Analytics:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.google-analytics.com/collect');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.2; .NET CLR 2.0.50727)");
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1&tid=UA-XXXXXXXX-42&cid=379445656".urlencode('.')."1380816256&t=transaction&tr=123.00&ti=43388&z=".time());
curl_close ($ch);

A:

It sees it as a eCommerce transaction because the hit type you're sending t=transaction is for transactions. If you're wanting to send an alternative hit type, take a look at google's documentation for the other alternatives - Measurement Protocol Developer Guide - Sending Common Hit Types.


Q:

Before launch, run external tool asynchronously?

Is it possible to create run configurations where it doesn't wait for the external tool to exit before launching?
I'm currently trying to get Dart's pub serve to run on my project directory before opening the Dartium browser on localhost:8080 but it seems that it's just waiting for pub to exit before it does. Which won't happen as pub serve continues to show output from the local server.
Any ideas?

A:

Probably not the best answer, but this should work:
Create a wrapper script, say pub_async.bat, that asynchronously calls pub.bat with correct command line arguments and returns immediately.
You may lose the ability to "stop" the process, and so shutting down / cleaning up may need to be handled in a different way.


Q:

Release Management vNext Component Deployment Bottleneck

We're using Release Management 2015 with vNext release templates. We have a Powershell DSC based component deployment for each of the portions of our application, and in fact, we have two distinct applications being deployed and that are in active development and are often deployed at nearly the same time.
We very frequently get the following error during deployments:

OperationFailedException: New deployment is not allowed as an another deployment is in progress. Retry the deployment after sometime.

The full stack trace shows that the error is coming not from Powershell itself, but from Release Management's system that's in charge of execution of the powershell script on the target machine:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.TeamFoundation.Release.Common.Helpers.OperationFailedException: New deployment is not allowed as an another deployment is in progress. Retry the deployment after sometime.
   at Microsoft.TeamFoundation.Release.EnvironmentProvider.OnPrem.Implementation.OnPremDeploymentProvider.ReadDeploymentResponse(DeploymentResponse response)
   at Microsoft.TeamFoundation.Release.EnvironmentProvider.OnPrem.Implementation.OnPremDeploymentProvider.RunScript(String scriptPath, String configurationPath, MachineSpecification machine, StorageSpecification storage, Dictionary`2 configurationVariables)
   at Microsoft.TeamFoundation.Release.MonitorServices.Dsc.OnPrem.OnPremDeploymentActions.InvokePlatform(String activityId, MachineSpecification machineSpecification, StorageSpecification storageSpecification, String scriptPath, String configurationPath, Dictionary`2 configurationVariables)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.TeamFoundation.Release.DeploymentAgent.Services.Deployer.Dsc.DscComponentInstaller.InvokeMethodByReflection(String methodArguments)

The above error causes the entire deployment to fail, and we're forced to retry the stage or the entire deployment to have it finish.
There are two scenarios that cause this:

Two release templates execute their powershell scripts on the same target server at the same time
A single release template has a parallel control flow which contains two different components that both execute scripts on the same target server

In other words, the mechanism that Release Management uses to execute a powershell script on a remote server can only seem to ever execute a single script at a time, and has no ability to wait/hold for others to complete.
This kinda/sorta makes sense if the script in question as actively modifying the server on which it's executing, but in our case, the server acts as basically a staging area to run the script. The "real" target of the script has nothing to do with the server on which the powershell happens to be executing.
Aside from having a server-per-simultaneously-deployed-component (wow), what's the work around here? It seems like a major oversight and it's seriously making me consider dropping Release Management altogether.

A:

I was having an issue was well with running Powershell scripts on remote servers. I ended up going a slightly different route. Instead, I just run a normal Powershell command with an Invoke-Command block. I believe you should be able to run this in parallel.
Function Get-PSCredential($User,$Password) {
    $SecPass = ConvertTo-SecureString -AsPlainText -String $Password -Force
    $Creds = New-Object System.Management.Automation.PSCredential -ArgumentList $User,$SecPass
    Return $Creds
}

$credential = Get-PSCredential -User $deployUser -Password $deployPass
$session = New-PSSession YourServerName -Credential $credential

Invoke-Command -Session $session -ScriptBlock {
    # do your work here
}

If you are running as a service account that has access to the machine, you should be able to eliminate the credential stuff and just go with
$session = New-PSSession YourServerName

I only started using Release Management this week so this seemed the best way to go in that short amount of time.
Also, If you've never used Invoke-Command before, everything inside the script block is actually in its own scope so you need to pass your variables into it using -ArgumentList if you have any. Check out this article if you have any more questions about that.

A:

As I explained in another post today, MS Release Management's way of deploying is a bit counter-intuitive: Rather than just executing your Powershell deployment script against the target server using PSRemoting, it uses PSRemoting to install a Windows Service (VisualStudioRemoteDeployer.exe) on the target server. This service then runs your deployment script locally, and the MSRM server regularly polls this Windows service (see here) to see if it is finished deploying.
I suspect this strange setup has something to do with avoiding the double-hop issue - so that it allows your script to make a 2nd hop from the target server to another server, e.g. for a webservice call.
Anyway, this Windows service probably forms the bottleneck, because there can be only one such instance running per server - hence the fact that parallel deployments of components to the same server appear to collide.
I think your problems originate from the fact that you chose a setup where "the server acts as basically a staging area to run the script" - MS Release Management 2013/2015 doesn't play well in this scenario (as you found out), you should really deploy your components directly to the target servers on which they need to be installed, thus avoiding the staging area bottleneck.
The next version of MS Release Management will be using deployment agents that will serve as a staging point from which the components will be deployed to the other servers. This helps reducing the number of connections you have to allow on your firewall between the MS Release Management and the target servers (which is probably why you chose the staging area setup), while still allowing parallel (or at least queued) deployments.


Q:

While trying to send POST request in HTTPCLIENT -JAVA, getting 400 Bad Request

I am trying to POST a request using JAVA HTTPCLIENT, and while doing so, I am getting 404 Bad Request.
I tried writing the JAVA code in Eclipse and got 404 Bad Request and tried sending the request through POSTMAN and received HTTP Status 500
package com.apex.customer.service;

public class CustServicePostTest {

    public static void main(String[] args) throws ClientProtocolException, IOException {

        String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/102";
        //create the http client
        HttpClient client = HttpClientBuilder.create().build();
        //create the post message
        HttpPost post = new HttpPost(url);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("ID", "102"));
        urlParameters.add(new BasicNameValuePair("FIRSTNAME", "Apex"));
        urlParameters.add(new BasicNameValuePair("LASTNAME", "Consultancy"));
        urlParameters.add(new BasicNameValuePair("STREET", "Shell Blvd"));
        urlParameters.add(new BasicNameValuePair("CITY", "Fremont"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);

        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println("Parameters : " + urlParameters);
        System.out.println("Response Code: " + response);
        System.out.println(response.getStatusLine().getReasonPhrase());

    }

}

I am looking for 200 OK request.

A:

The issue here is due few mistakes:

First is related to the input format. The code you're using tries to map key and values, but as I could see from this guide, it expects a XML format in a plain text as input.
The second mistake is that you are trying to post over an existing ID. In this case, to create a resource you should use http://www.thomas-bayer.com/sqlrest/CUSTOMER/

So in this case in order to make it work, try something like this:
        String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);

        String xml = "<resource>";
        xml += "<ID>102</ID>";
        xml += "<FIRSTNAME>Apex</FIRSTNAME>";
        xml += "<LASTNAME>Consultancy</LASTNAME>";
        xml += "<STREET>Shell Blvd</STREET>";
        xml += "<CITY>Fremont</CITY>";
        xml += "</resource>";

        post.setEntity(new StringEntity(xml));
        HttpResponse response = client.execute(post);

        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println("Response Code: " + response);
        System.out.println(response.getStatusLine().getReasonPhrase());

It is also very useful to learn another way to test it with tools like curl command line utility. For example you can POST a product like this:
curl -X POST  http://www.thomas-bayer.com/sqlrest/PRODUCT/ -d '<resource><ID>103</ID><NAME>X</NAME><PRICE>2.2</PRICE></resource>'

Once you solve this, it will be important to get used with HTTP codes. For example a 500 error means something wrong on the server side while a 404 usually means that you're hitting an invalid endpoint (it does not exists).
Finally, I'll not discuss why are you using this project to send HTTP requests to a server - but keep in mind that this is not a very common way to go. Currently the REST with JSON would be much more interesting and enjoyable :) In case you're interested on it, take a look on Spring Boot REST


Q:

How to pack angular library for new version tgz?

I have angular library project that version is 1.0.0 in package.json file. So I am running npm pack command. It generates a tgz file my-lib-1.0.0.tgz. And I do some changes in library and change version number of package.json to 1.0.1, and running npm pack again. But the generated tgs file does not change  my-lib-1.0.0.tgz.

A:

You should build your library with prod parameter and run npm pack. If you do not buil, old files are packaging in dist folder.


Q:

How do the Son'a torpedoes hit the Enterprise so quickly?

In Star Trek: Insurrection, there's an encounter between the USS Enterprise E (under Riker's command) and two Son'a ships.The dialogue goes like this:

OPS OFFICER: Commander, I'm showing two Son'a ships on an intercept course.
RIKER: How long till they reach us?
OPS OFFICER: Eighteen minutes.
GEORDI: We won't be able to get a transmission out of here for at least another hour.
LT. DANIELS: They're hailing us. [Daniels is the tactical officer]
RIKER: Tell them our transceiver assembly is down, we can send messages but not receive them.
LT. DANIELS: I don't think they believe us.
RIKER: Why not?
[AN EXPLOSION ROCKS THE SHIP]
RIKER: Photon torpedo. Isn't that the universal greeting when communications are down?
GEORDI: I think it's the universal greeting when you don't like someone.

How can the Son'a hit the Enterprise with a torpedo from 18 minutes away?
Sub-questions:

Are torpedos really that much faster than ships?
Was the Son'a torpedo launced much earlier and just not detected in time?
Is this somehow related to the environment inside the "briar patch"?

A:

Photon torpedoes are warp-capable munitions, so while at sublight speeds the Son'a ships might be 18 minutes away from interception (whatever that means in 3D space), this is not a restriction for photon torpedoes. @Valorum rightly points out that photon torpedoes not fired at warp will not cross the warp threshold, but instead travel at high-sublight speeds. How high probably varies by writer, but it might not be impossible for one to travel "18 minutes" (in ship speed) in a fraction of that. Also, it is possible (though probably unlikely) that the Son'a had self-warp-capable photon torpedoes.
Why don't the Son'a ships warp in (or just go faster) to get to the Enterprise faster?
This is due to the technobabble in the Briar Patch preventing them to do so. A photon torpedo, being tiny and not filled with people, is an expendable way to attack a ship quickly in the badlands, as if the torpedo goes off course or is destroyed by a gravitational eddy, there is no real loss.


Q:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary

I receive the above error message when performing a unit test on a method.  I know where the problem is at, I just don't know why it's not present in the dictionary.
Here is the dictionary:
var nmDict = xelem.Descendants(plantNS + "Month").ToDictionary(
    k => new Tuple<int, int, string>(int.Parse(k.Ancestors(plantNS + "Year").First().Attribute("Year").Value), Int32.Parse(k.Attribute("Month1").Value), k.Ancestors(plantNS + "Report").First().Attribute("Location").Value.ToString()),
    v => {
             var detail = v.Descendants(plantNS + "Details").First();
             return new HoursContainer
             {
                 BaseHours = detail.Attribute("BaseHours").Value,
                 OvertimeHours = detail.Attribute("OvertimeHours").Value,
                 TotalHours = float.Parse(detail.Attribute("BaseHours").Value) + float.Parse(detail.Attribute("OvertimeHours").Value)
             };
         });

var mergedDict = new Dictionary<Tuple<int, int, string>, HoursContainer>();

foreach (var item in nmDict)
{
    mergedDict.Add(Tuple.Create(item.Key.Item1, item.Key.Item2, "NM"), item.Value);
}

var thDict = xelem.Descendants(plantNS + "Month").ToDictionary(
    k => new Tuple<int, int, string>(int.Parse(k.Ancestors(plantNS + "Year").First().Attribute("Year").Value), Int32.Parse(k.Attribute("Month1").Value), k.Ancestors(plantNS + "Report").First().Attribute("Location").Value.ToString()),
    v => {
             var detail = v.Descendants(plantNS + "Details").First();
             return new HoursContainer
             {
                 BaseHours = detail.Attribute("BaseHours").Value,
                 OvertimeHours = detail.Attribute("OvertimeHours").Value,
                 TotalHours = float.Parse(detail.Attribute("BaseHours").Value) + float.Parse(detail.Attribute("OvertimeHours").Value)
             };
         });

foreach (var item in thDict)
{
    mergedDict.Add(Tuple.Create(item.Key.Item1, item.Key.Item2, "TH"), item.Value);
}
        return mergedDict;

}
and here is the method that is being tested:
protected IList<DataResults> QueryData(HarvestTargetTimeRangeUTC ranges,
        IDictionary<Tuple<int, int, string>, HoursContainer> mergedDict)
{
    var startDate = new DateTime(ranges.StartTimeUTC.Year, ranges.StartTimeUTC.Month, 1);
    var endDate = new DateTime(ranges.EndTimeUTC.Year, ranges.EndTimeUTC.Month, 1);
    const string IndicatorName = "{6B5B57F6-A9FC-48AB-BA4C-9AB5A16F3745}";

    DataResults endItem = new DataResults();
    List<DataResults> ListOfResults = new List<DataResults>();

    var allData =

    (from vi in context.vDimIncidents
    where vi.IncidentDate >= startDate.AddYears(-3) && vi.IncidentDate <= endDate
        select new
        {
            vi.IncidentDate,
            LocationName = vi.LocationCode,
            GroupingName = vi.Location,
            vi.ThisIncidentIs, vi.Location
        });

    var finalResults =

            (from a in allData
            group a by new { a.IncidentDate.Year, a.IncidentDate.Month, a.LocationName, a.GroupingName, a.ThisIncidentIs, a.Location }
                into groupItem
            select new
            {
                Year = String.Format("{0}", groupItem.Key.Year),
                Month = String.Format("{0:00}", groupItem.Key.Month),
                groupItem.Key.LocationName,
                GroupingName = groupItem.Key.GroupingName,
                Numerator = groupItem.Count(),
                Denominator = mergedDict[Tuple.Create(groupItem.Key.Year, groupItem.Key.Month, groupItem.Key.LocationName)].TotalHours,
                IndicatorName = IndicatorName,
            }).ToList();

    for (int counter = 0; counter < finalResults.Count; counter++)
    {
        var item = finalResults[counter];
        endItem = new DataResults();
        ListOfResults.Add(endItem);
        endItem.IndicatorName = item.IndicatorName;
        endItem.LocationName = item.LocationName;
        endItem.Year = item.Year;
        endItem.Month = item.Month;
        endItem.GroupingName = item.GroupingName;
        endItem.Numerator = item.Numerator;
        endItem.Denominator = item.Denominator;
    }

    foreach(var item in mergedDict)
    {
        if(!ListOfResults.Exists(l=> l.Year == item.Key.Item1.ToString() && l.Month == item.Key.Item2.ToString()
                && l.LocationName == item.Key.Item3))
        {
            for (int counter = 0; counter < finalResults.Count; counter++)
            {
                var data = finalResults[counter];
                endItem = new DataResults();
                ListOfResults.Add(endItem);
                endItem.IndicatorName = data.IndicatorName;
                endItem.LocationName = item.Key.Item3;
                endItem.Year = item.Key.Item1.ToString();
                endItem.Month = item.Key.Item2.ToString();
                endItem.GroupingName = data.GroupingName;
                endItem.Numerator = 0;
                endItem.Denominator = item.Value.TotalHours;
            }
        }
    }
    return ListOfResults;
}

The error occurs here:
 Denominator = mergedDict[Tuple.Create(groupItem.Key.Year, groupItem.Key.Month, groupItem.Key.LocationName)].TotalHours,

I do not understand why it is not present in the key.  The key consists on an int, int, string (year, month, location) and that is what I have assigned it.
I've looked at all of the other threads concerning this error message but I didn't see anything that applied to my situation.
I was unsure of what tags to put on this but  from my understanding the dictionary was created with linq to xml, the query is linq to sql and it's all part of C# so I used all the tags.  if this was incorrect then I apologize in advance.

A:

The problem is with comparisons between the keys you are storing in the Dictionary and the keys you are trying to look up.
When you add something to a Dictionary or access the indexer of a Dictionary it uses the GetHashCode() method to get a hash value of the key.  The hashcode for a Tuple is unique to that instance of the Tuple.  This means that unless you are passing in the exact same instance of the Tuple class into the indexer, it will not find the previously stored value.  Your usage of mergedDict[Tuple.Create(... creates a brand new Tuple with a different hash code than is stored in the Dictionary.
I would recommend creating your own class to use as the key and implementing GetHashCode() and the Equality methods on that class.  That way the Dictionary will be able to find what you previously stored there.
More:
The reason this is confusing to a lot of people is that for something like String or Int32, String.GetHashCode() will return the same hash code for two different instances that have the same value.  A more specialized class such as Tuple doesn't always work the same.  The implementor of Tuple could have gotten the hash code of each input to the Tuple and added them together (or something), but running Tuple through a decompiler you can see that this is not the case.


Q:

Bli Neder Loophole

Who came up with the Bli Neder loophole of:

Bli neder I will help you do X

Or

Bli neder I will etc...

And the list can go on and on.
Who came up with addingBli Neder which basically means "Without a promise" to things that seem like promises?!
Does that remove one from the obligation of the promise?
I have even heard people say:

I promise Bli Neder....

Really now?
How does all of this work, and what are the ramifications in halacha?

Side points and references:

Here is a whole article on nedarim on general
Quote from here:

Bli Neder
  A "neder" is a formal commitment. "B'li Neder" means "without making a formal commitment." Not to be true to ones word is itself considered a sin in Judaism. Therefore, not to become entrapped in the sin of violating ones commitments, one adds this expression (B'li Neder) when committing oneself to an action or behavior such as in this calendar. To avoid confusion - one must truly intend to keep ones word in order for this qualifier (or this calendar for that matter) to have any real meaning. This expression is not valid in business contracts and legal obligations

A:

According to Alex's answer here (which I asked for this very purpose):

"A neder, by definition, is either declaring something to be
  forbidden to oneself, or taking on an obligation to bring a korban or
  give tzedakah (Rambam, ibid. 1:1-2 and Matnos Aniyim 8:1)."

So even if saying bli neder CAN circumvent a vow, logic dictates that it would only work on a neder, and not on a shevua. The cases you bring up in your question pertain to shevu'ot (except for the last one when referring to tzedaka), and since the wrong term is used, bli neder may not apply.
On the other hand, the Rambam writes (Hilchot Shevuot 2:12) that when one makes a shevua, his intentions must match up with what he says. For example, if one says that he will give a 180 dollar donation, while really he means to say 180 shekel hadash, he is not tied down to his oath. I would presume that similarly here, just because one says he will do something, if he does not intend for it to be binding, it may not apply. Assuming this logic is true, the words "bli neder" would not actually have to be said, as long as they are his intent.

A:

I read it in sefer Kisur Shulhan Aruch of Rav Gansfried with Rav Mordechai Eliyahu, that he brings a Tosafot in Besa 20A that says you must say Beli Neder before you say what you are trying to say.
EDIT: The earliest source I have seen is this Tosafot.


Q:

Why "unequal" but "inequality"?

The opposite of "equal" is "unequal", yet there is no word "unequality". Why do we use "inequality" instead?

A:

The prefixes in- and un- both have the effect of negating the meaning of the word. The prefix in- comes from Latin and almost exclusively applies to words borrowed from Latin, which in many cases were borrowed from Latin with the in- prefix already attached. The prefix un-, on the other hand, is a native English prefix, and so, in general, can apply to any English adjective.
The Online Etymology Dictionary tells us that inequality was borrowed from Latin (via French) with the prefix in- already attached, so we get the word with the prefix in-:

1484, "difference of rank or dignity," from O.Fr. inequalité  (14c.), from M.L. inæqualitas,  from inæqualis  "unequal," from in-  "not" + æqualis  "equal"

The word unequal, on the other hand, does have the same Latin root of æqualis, but the prefix un- doesn't seem to have been applied to it until after it became an English word.
There exists this phenomenon called blocking, where two seemingly equally valid ways of saying something conflict, so the existence of one blocks the other. Since the word inequality already existed from having been borrowed from French with the negative prefix already attached, the process to form the word unequality was blocked. The word unequality does exist though, but its usage is far eclipsed by inequality.


Q:

want to perform custom action while installing APK?

I want to perform some custom  operation  while installing the APK. These operation include copying of shared object(.so) to /system/lib ,creating some shared preferences so my application can directly use it.( Like in windows we can create registry entry while Installing the application.) Do we can execute any script while installing APK which can perform those operation ?

A:

You cannot do this. App installation is not something you can "hook" into.
With shared Preferences you would supply a default value to be used in the case of a preference not having been created yet.
If you wish to share objects between apps, you would need to use external storage\SD Card or run both apps in the same process.
You would need to copy your shared object to external storage when the app runs. It could not be done during installation.


Q:

Expression return weird error

I'm trying to use an expression block:
var branches = [for (branchName in process.toString().split("\n")) {
    {label: branchName};
}];

Vscode.window.showQuickPick(branches); // <-- this line 25, 26 is empty line

but I get:
/src/Main.hx:26: characters 8-35 : Constraint check failure for showQuickPick.T
/src/Main.hx:26: characters 8-35 : { label : String } should be vscode.QuickPickItem
/src/Main.hx:26: characters 8-35 : { label : String } should be { label : String, ?detail : Null<String>, description : String }
/src/Main.hx:26: characters 8-35 : { label : String } has no field description

Expression block does not allow to return an object?

A:

This line outlines the problem:
/src/Main.hx:26: characters 8-35 : { label : String } has no field description

Your object needs a String description field, as that field is not optional.
See: https://github.com/vshaxe/vscode-extern/blob/master/src/vscode/QuickPickItem.hx


Q:

Why JsonConverter.WriteJson() never gets called, although JsonConverter.ReadJson() does get called?

Why my custom JsonConverter.WriteJson() method doesn't get called ?
class MyType{
    [JsonConverter(typeof(DocumentXamlDeserializer))]
    public string GuiData { get; set; }

    public string SimpleString;
}

Although the ReadJson does get called:
public class DocumentXamlDeserializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(Gui.Handler.SerializeData());
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var xaml = reader.Value as string;
        Gui.Handler.DeserializeData(xaml);
        return xaml;
    }

    public override bool CanConvert(Type objectType) { return typeof(string).IsAssignableFrom(objectType); }
}

The serialization call: JsonConvert.SerializeObject(dataModel, Formatting.Indented);
The deserialization call: JsonConvert.DeserializeObject<Model>(raw);

A:

Apparently this is because GuiData is null... I guess I could specify:
TypeNameHandling = TypeNameHandling.Objects

But I want to serialize only GuiData even if it's null (I set its value during serialization), without serializing all null-properties... well, if I don't find better way, I guess I'd have to suffice with it...


Q:

Techniques to reduce data harvesting from AJAX/JSON services

I was wondering if anyone had come across any techniques to reduce the chances of data exposed through JSON type services on the server (intended to supply AJAX functions) from being harvested by external agents.
It seems to me that the problem is not so difficult if you had say a Flash client consuming the data.  Then you could send encrypted data to the client, which would know how to decrypt it.  The same method seems impossible with AJAX though, due to the open nature of the Javascript source.
Has anybody implemented a clever technique here?
Whatever the method, it should still allow a genuine AJAX function to consume the data.
Note that I'm not really talking about protecting 'sensitive' information here, the odd record leaking out is not a problem.  Rather I am thinking about stopping a situation where the whole DB is hoovered up by bots (either in one go, or gradually over time).
Thanks.

A:

The first thing to prevent bots from stealing your data is not technological, it's legal.  First, make sure you have the right language in your site's Terms of Use that what you're trying to prevent is actually disallowed and defensible from a legal standpoint.  Second, make sure you design your technical strategy with legal issues in mind.  For example, in the US, if you put data behind an authentication barrier and an attacker steals it, it's likely a violation of the DMCA law.  Third, find a lawyer who can advise you on IP and DMCA issues... nice folks on StackOverflow aren't enough. :-)
Now, about the technology:
A reasonable solution is to require that users be authenticated before they can get access to your sensitive Ajax calls.  This allows you to simply monitor per-user usage of your Ajax calls and (manually or automatically) cancel the account of any user who makes too many requests in a particular time period. (or too many total requests, if you're trying to defend against a trickle approach).
This approach of course is vulnerable to sophisticated bots who automatically sign up new "users", but with a reasonably good CAPTCHA implementation, it's quite hard to build this kind of bot. (see "circumvention" section at http://en.wikipedia.org/wiki/CAPTCHA)
If you are trying to protect public data (no authentication) then your options are much more limited.  As other answers noted, you can try IP-address-based limits (and run afoul of large corporate proxy users) but sophisticated attackers can get around this by distributing the load.  There's also likley sophisticated software which watches things like request timing, request patterns, etc. and tries to spot bots. Poker sites, for example, spend a lot of time on this. But don't expect these kinds of systems to be cheap.  One easy thing you can do is to mine your web logs (e.g. using Splunk) and find the top N IP addresses hitting your site, and then do a reverse-IP lookup on them. Some will be legitimate corporate or ISP proxies. But if you recognize a compeitor's domain name among the list, you can block their domain or follow up with your lawyers.
In addition to pre-theft defense, you might also want to think about inserting a "honey pot": deliberately fake information that you can track later.  This is how, for example, maps manufacturers catch plaigarism: they insert a fake street in their maps and see which other maps show the same fake street.  While this doesn't prevent determined folks from sucking out all your data, it does let you find out later who's re-using your data.  This can be done by embedding unique text strings in your text output, and then searching for those strings on Google later (assuming your data is re-usable on another public website). If your data is HTML or images, you can include an image which points back to your site, and you can track who is downloading it, and look for patterns you can use to bust the freeloaders.
Note that the javascript encryption approach noted in one of the other answers won't work for non-authenticated sessions-- an attacker can simply download the javascript and run it just like a regular browser would. Moral of the story: public data is essentially indefensible.  If you want to keep data protected, put it behind an authentication barrier.
This is obvious, but if your data is publicly searchable by search engines, you'll both need a non-AJAX solution for them (Google won't read your ajax data!) and you'll want to mark those pages NOARCHIVE so your data doesn't show up in Google's cache.  You'll also probably want a white list of search engine crawler IP addreses which you allow into your search-engine-crawlable pages (you can work with Google, Bing, Yahoo, etc. to get these), otherwise malicious bots could simply impersonate Google and get your data.
In conclusion, I want to echo @kdgregory above: make sure that the threat is real enough that it's worth the effort required.  Many companies overestimate the interest that other people (both legitimate customers and nefarious actors) have in their business.  It might be that yours is an oddball case where you have particularly important data, it's particularly valuable to obtain, it must be publicly accessible without authentication, and your legal recourses will be limited if someone steals your data.  But all those together is admittedly an unusual case.
P.S. - another way to think about this problem which may or may not apply in your case. Sometimes it's easier to change how your data works which obviates securing it. For example, can you tie your data in some way to a service on your site so that the data isn't very useful unless it's being used in conjunction with your code. Or can you embed advertising in it, so that wherever it's shown you get paid?  And so on. I don't know if any of these mitigations apply to your case, but many businesses have found ways to give stuff away for free on the Internet (and encourage rather than prevent wide re-distribution) and still make money, so a hybrid free/pay strategy may (or may not) be possible in your case.

A:

First, I would like to clear on this:

It seems to me that the problem is not
  so difficult if you had say a Flash
  client consuming the data. Then you
  could send encrypted data to the
  client, which would know how to
  decrypt it. The same method seems
  impossible with AJAX though, due to
  the open nature of the Javascrip
  source.

It will be pretty obvious the information is being sent encrypted to the flash client & it won't be that hard for the attacker to find out from your flash compiled program what's being used for this - replicate & get all that data.
If the data does happens to have the value you are thinking, you can count on the above.
If this is public information, embrace that & don't combat it - instead find ways to capitalize on it.
If this is information that you are only exposing to a set of users, make sure you have the corresponding authentication / secure communication. Track usage as others have said, and have measures that act on it,


Q:

VBE How do you use Filldown with the WEEKNUM Function

I want cell E2 to pull the WEEKNUM from cell D2, and then repeat for the length of my data set.
Sub WeekNumTest()
Range("E2").Select
ActiveCell.FormulaR1C1 = "=WEEKNUM(RC[-1])"
Range("E2").Select
Selection.FillDown
End Sub

The weeknum is pulling correctly for cell E2, but the formula is not continuing for the rest of my data.

A:

Use variables and find the extent of range.
Then set all the formulas at once.
Sub WeekNumTest()
Dim rng As Range
Dim ws As Worksheet

Set ws = ActiveSheet

Set rng = ws.Range(ws.Cells(2, 5), ws.Cells(ws.Cells(ws.Rows.Count, 4).End(xlUp).Row, 5))

Rng.FormulaR1C1 = "=WEEKNUM(RC[-1])"

End Sub


Q:

replace a particular value in a string of key - values

I have a large string which is a collection of key (space)+ value, i.e key followed by one or more space and then value.
Now i need to change the value of a particular key using sed, awk, grep etc. in unix environment.
eg. of string: -Key1       Value1    -Key2    Value2   -Key3  Value3
I need a new string that is same as above only Value2 will be replaced by NewValue3

A:

echo "-Key1 Value1 -Key2 Value2 -Key3 Value3" | \
    sed -r -e "s/(-Key2\s+)([^-\s]+)(\s+)/\1<newvale>\3/g"
-Key1 Value1 -Key2 <newvale> -Key3 Value3


Q:

Razor View if/else statement in javascript

Is it possible to do this in the razor View . I want to inject below JavaScript only if statement is true else not. How can i do this.
            @if (Model.EmployeeInterviews != null)
            {
                $("#select-Candidate")[0].selectize.setValue(@Html.Raw(JsonConvert.SerializeObject(Model.CandidateId)));
                var employee = @Html.Raw(JsonConvert.SerializeObject(selectedempobj));
                var val = "[";
                for (i = 0; i < employee.length; i++)
                {
                    val += employee[i].EmployeeID + ",";
                }
                val = val.substring(0, val.length - 1) + "]";

                $("#select-Employee")[0].selectize.setValue(JSON.parse(val));
                $('#txtScheduledOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.ScheduledOn)');
                $('#txtCompletedOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.CompletedOn)');
                $('#hdnEmployeeId').val(JSON.parse(val).toString());
                $('#hdnCandidateId').val('@Html.Raw(JsonConvert.SerializeObject(Model.CandidateId))');
            }

A:

Something like this
<script type="text/javascript">
    $(document).ready(function () {
        //... some common javascript

        @{
            if (Model.EmployeeInterviews != null) {
            <text>
            $("#select-Employee")[0].selectize.setValue(JSON.parse(val));
            $('#txtScheduledOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.ScheduledOn)');
            //... specific javascript
            </text>
            }
        }
    });
</script>


Q:

amazon S3 database options and using EC2 as a REST api from S3

I am hosting my website on S3.
On my local host I am using backboneJS above a PHP Rest API that uses mySQL as a database.
So i opened an EC2 to host my Rest API but then realized this means cross domain AJAX.
How can i use EC2 as a Rest API if my index.html sits on S3?
What are my other DB options for S3?
many thanks,

A:

Your JavaScript is being executed on web pages served from S3, and it has to access a REST API from a server you run on EC2. Unless the web pages and server are in the same domain (say, example.com), this will be a cross-origin request, prohibited by browsers by default.
Solution 1: have your S3 pages and your EC2 server in the same domain. S3 allows static website hosting that makes your S3 objects (web pages) available at the address of your choice. Put them and your EC2 server at addresses on the same domain, and it can work.
Solution 2: have your REST API server allow cross-origin requests. Since you control this EC2 server you can modify it to tell web browsers to allow pages from other domains to make such requests to your server. This involves setting several headers on your responses, and usually requires your server to respond to HTTP OPTIONS requests properly, too. See the CORS specification to get started on that.
You also ask about other DB options. If you keep your own EC2 server to provide the REST API it can use pretty much any kind of database you like, either running on the same or other EC2 instances, or database-as-a-service offerings like AWS RDB or AWS DynamoDB. But if you want to connect to the database directly from your web pages' JavaScript you would have to use a service that provides an HTTP API directly and that supports CORS. RDB does not provide an HTTP API at all, and DynamoDB does not seem to support CORS at this time, so neither of them would work.


Q:

How do I assemble a  using jQuery append()?

I'm trying to use the append function and encountered this:
$("#details").append('
');
for (var i = 0; i < 10; i++) {
    $("#details").append('
something
');
}
$("#details").append('
');

It appears that the
 elements renders OUTSIDE the
 tag.
Is this a jQuery bug?

A:

Nope, you can't use it like that. append is an atomic operation, which creates the element directly.
// The
 element is added to #details, then it is selected and the jQuery
// selection is put in the "list" variable.
var list = $('
').appendTo('#details');
for (var i = 0; i < 10; i++) {
    // New
 elements are created here and added to the
 element.
    list.append('
something
');
}

Alternatively, generate the HTML and add it all at once (this will be more similar to your original code):
var html = '
';
for (var i = 0; i < 10; i++) {
    html += '
something
';
}
html += '
';
$('#details').append(html);

This code is noticeably faster when dealing with many elements.
If you need a reference to the list, just do the following instead of $('#details').append(html);:
var list = $(html).appendTo('#details');

A:

No, it's a programmer bug.
s are attached to their
 or
, not to its container.  And appending a close tag is nonsensical.
You're basically working as if what you were appending were raw HTML, and it's not; you're actually working with the DOM.
Try this:
var list = $("#details").append('

').find('ul');
for (var i = 0; i < 10; i++)
    list.append('
something
');

Note: please see (and upvote) Blixt's answer, which expands on a couple different options that are superior for various purposes.  It deserves attention and hasn't been getting it.

A:

I think there's a problem in your loop
for (var i = - i < 10; i++)
    $("#details").append('
something
');

should be I think
for (var i = 0; i < 10; i++)
    $("#details ul").append('
something
');

and lose the following from the end
$("#details").append('
');

Working Demo
EDIT:
Based on George IV's comment, in order to avoid appending
 elements to any
 that may be a child of the element with id "details", simply give the
 element an id when you append it-
$("#details").append('
');

for (var i = 0; i < 10; i++)
    $("#appended").append('
something
');

you may also find this article interesting - 43,439 reasons to use append() correctly


Q:

Is this possible to detect a colour is a light or dark colour?

Consider these two pink square:

And this:

As you may know, one is lighter and one is darker or more sharp.
The problem is, I can tell it by human eyes, but is this possible to use a system way or programme way to detect this information? At least, is this possible to have a value that tell me that colour is more like white or that colour is less like white? (Assume I got the RGB code of that colour.) Thanks.

A:

Since you haven't specified any particular language/script to detect the darker/lighter hex, I would like to contribute a PHP solution to this
Demo
$color_one = "FAE7E6"; //State the hex without #
$color_two = "EE7AB7";

function conversion($hex) {
    $r = hexdec(substr($hex,0,2)); //Converting to rgb
    $g = hexdec(substr($hex,2,2));
    $b = hexdec(substr($hex,4,2));

    return $r + $g + $b; //Adding up the rgb values
}

echo (conversion($color_one) > conversion($color_two)) ? 'Color 1 Is Lighter' : 'Color 1 Is Darker';
//Comparing the two converted rgb, the greater one is darker

As pointed out by @Some Guy, I have modified my function for yielding a better/accurate result... (Added Luminance)
function conversion($hex) {
    $r = 0.2126*hexdec(substr($hex,0,2)); //Converting to rgb and multiplying luminance
    $g = 0.7152*hexdec(substr($hex,2,2));
    $b = 0.0722*hexdec(substr($hex,4,2));

    return $r + $g + $b;
}

Demo 2

A:

Below is the Python code to determine light or dark color. The formulation is based on the HSP value. HSP (Highly Sensitive Poo) equation is from http://alienryderflex.com/hsp.html used to determine whether the color is light or dark.
import math
def isLightOrDark(rgbColor=[0,128,255]):
    [r,g,b]=rgbColor
    hsp = math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))
    if (hsp>127.5):
        return 'light'
    else:
        return 'dark'


Q:

Loss data after space in EJS form

There is an EJS file with a form, that has a <select> drop-down list.
   <form action="/scheduler/jobEvent" method="POST">

        <select class="custom-select" id="addJobEvent" name="event[title]">
          <option selected>Select</option>

          <% personnelList.forEach(person => { %>
            <option value=<%- person.title %>><%- person.title %></option>
          <% }) %>
        </select>

        <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-outline-success">Save Event</button>

    </form>

The list is filled up dinamically from DB. Click on submit sends form's data to back-end JS file, where it is further processed:
router.post('/scheduler/jobEvent', middleware.loggedAsAdmin, async (req,res) => {
    var personTitle = req.body.event.title;
        console.log(personTitle);
});

The list itemizes people nicknames, that consist of a given name and the first letter of surname, e.g.
John H, Mike K, etc. And I found out that everything in nickname after space is being lost while transmitting from form to back-end. That is John H shortens to just John when console.log it in JS. Below is my troubleshooting:

Nickname is displayed properly with the letter after space on the list when rendering the EJS file, and so all data is transmitted from DB to <%- person.title %>.
I hardcoded nickname in the list, i.e. <option value='John H'><%- person.title %></option> and it comes to the back-end file in the same way, and so nothing loses between client and server-side.
I added underscore in nicknames in the DB, i.e. John_H and it works as it should be without losses, that is it relates somehow to space.
Has anyone encountered such an issue?
Thank you in advance.

A:

Compare the working and non-working code:

<option value=<%- person.title %>>

and

<option value='John H'>

What is different?
quotes
If you don't have quotes around an attribute value, then a space ends the value and whatever comes after the space starts a new attribute.


Q:

Can I bake 2 small cakes at the same time?

I have to bake 3 small white cholocate mudcakes and put them together to make the final butt shaped cake, which I will ganache and fondant. I have to bake 1 rectangle cake (for the back) and 2 half hemisphere round cakes (for the cheeks).
I have one rectangle pan 13cmx24cm and one 16cm half hemisphere round pan. I was wondering if I could bake the rectangle and one half round cake at the same time in the middle rack of my fan force oven or will that be a risk and make the cakes dry or undercooked? I usually bake them at 150 degrees.

A:

As long as you monitor each cake for doneness individually, there is no reason not to bake them  together—assuming they both need the same temperature.
If the sizes are radically different (in terms of the thinnest dimension, which is usually the depth) you may need to adjust temperature to control crust formation during the time it takes the cakes through to the center.
If the cakes are close in depth, they should bake in approximately equal times.
You may wish to use cake strips or aluminum foil to protect the thing easily burned permiter of a hemispherical cake.
Note that 150 C (300 F) is an atypically low temperature for baking a cake.
See related:  Additional Cooking Time When baking more than one loaf of quick bread


Q:

Was decoupling actually detripling?

As I previously understood it, before recombination, high energy photons were bound up in interactions with excited electrons, meaning electrons couldn't settle into orbit with protons and other nuclei.
However, there were lots of free protons about, whose electric charge would have made them interact electromagnetically. Were photons as much bound up with protons as electrons during this phase? If so, did those interactions produce electron / positron pairs?

A:

From the theory of Thompson scattering (see http://farside.ph.utexas.edu/teaching/em/lectures/node96.html ) we know that a charged particle of mass m interacting with a plane wave electromagnetic field of Strength $E_0$ and frequency $\omega$ has an effective dipole moment of magnitude $$d=\frac{e^2E_0}{m\omega^2}$$
Note that the dipole moment scales inversely with the mass of the charged particle.  It is this dipole moment (actually $d^2$) that determines the amount of energy that the charged particle scatters (radiates) from the electromagnetic field.  Hence electrons with a mass some 2000 times less than that of the proton are much more efficient at interacting with (scattering) a high energy photon.  Technically the protons contribute as well but the overwhelming majority of energy scattering (and hence decoupling) is between electrons and photons.


Q:

How this inequality works?

I'm trying to understand the proof of Malinowski inequality by reading this article. But I don't know how Holder’s Inequality holds. specifically I don't know how this part works:

It says by summing over $i = 1, . . .,n,$ we obtain the last inequality. But I don't know how. And where did the last inequality came from.

A:

It comes from the following inequality: $xy \leq \dfrac{x^p}{p} + \dfrac{y^q}{q}$, with
$x = \dfrac{|a_i|}{\left(\displaystyle \sum_{i=1}^n |a_i|^p\right)^{\frac{1}{p}}}, y = \dfrac{|b_i|}{\left(\displaystyle \sum_{i=1}^n |b_i|^q\right)^{\frac{1}{q}}}$. Also:
$\displaystyle \sum_{i=1}^n \dfrac{|a_i|^p}{\displaystyle \sum_{k=1}^n |a_k|^p}=1$. The same is true for the other part which involves the $|b_i|^p$'s.


Q:

Mobile friendly over images - lightbox

Good evening, thanks for trying to help first off.
I have a 'portfolio' page with 45 images of houses I've built. They're laid out in a grid, 5 wide 9 down. Simply, when you click and expand the image in browser, it works great. However, when I view on mobile, it get's a little fishy. The image tends to stretch past the view of the screen.
My question is: how can I make the image stay in the viewport of say my mobile device instead of stretching passed the screen? I tried absolutely positioning the overlay, that didn't work.
The lightbox script i'm using: http://tympanus.net/Tutorials/CSS3Lightbox/index3.html
My portfolio page: http://www.ocalaplastering.com/portfolio.html
This would be my html heavily reduced. Multiply the "li" element times 45 and that's basically the page.

                Expand

                Prev
                Next

                x Close

As for the CSS, this is the styles for the aforementioned elements:
.lb-album{
    width: 100%;
    margin: 0 auto;
    font-family: 'BebasNeueRegular', 'Arial Narrow', Arial, sans-serif;
}
.lb-album li{
    float: left;
    padding:0px;
    padding-right:1px;
    padding-bottom:1px;
    position: relative;
    list-style:none;
}
.lb-album li > a,
.lb-album li > a img{
    display: block;
}
.lb-album li > a{
    width: 150px;
    height: 150px;
    position: relative;
    padding: 3px;
    background: #816445;
    -webkit-box-shadow: 1px 1px 2px #fff, 1px 1px 2px rgba(158,111,86,0.3) inset;
    -moz-box-shadow: 1px 1px 2px #fff, 1px 1px 2px rgba(158,111,86,0.3) inset;
    box-shadow: 1px 1px 2px #fff, 1px 1px 2px rgba(158,111,86,0.3) inset;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px 4px 4px 4px;
}
.lb-album li > a span{
    position: absolute;
    width: 150px;
    height: 150px;
    top: 3px;
    left: 3px;
    text-align: center;
    line-height: 150px;
    color: rgba(27,54,81,0.8);
    text-shadow: 0px 1px 1px rgba(255,255,255,0.6);
    font-size: 24px;
    opacity: 0;
    filter: alpha(opacity=0); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
    background: rgb(241,210,194);
    background: -moz-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%, rgba(241,210,194,1) 100%);
    background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(255,255,255,0.56)), color-stop(100%,rgba(241,210,194,1)));
    background: -webkit-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -o-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -ms-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    -webkit-transition: opacity 0.3s linear;
    -moz-transition: opacity 0.3s linear;
    -o-transition: opacity 0.3s linear;
    -ms-transition: opacity 0.3s linear;
    transition: opacity 0.3s linear;
}
.lb-album li > a:hover span{
    opacity: 1;
    filter: alpha(opacity=99); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=99)"; /*IE8*/
}
.lb-overlay{
    width: 0px;
    height: 0px;
    position: fixed;
    overflow: hidden;
    left: 0px;
    top: 0px;
    padding: 0px;
    z-index: 99;
    text-align: center;
    background: rgb(241,210,194);
    background: -moz-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%, rgba(241,210,194,1) 100%);
    background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(255,255,255,0.56)), color-stop(100%,rgba(241,210,194,1)));
    background: -webkit-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -o-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -ms-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
}
.lb-overlay > div{
    position: relative;
    color: rgba(27,54,81,0.8);
    width: 550px;
    height: 80px;
    margin: 40px auto 0px auto;
    text-shadow: 0px 1px 1px rgba(255,255,255,0.6);
}
.lb-overlay div p{
    font-size: 14px;
    text-align: left;
    float: left;
    width: 260px;
}
.lb-overlay a.lb-close{
    background: rgba(27,54,81,0.8);
    z-index: 1001;
    color: #fff;
    position: absolute;
    top: 43px;
    left: 50%;
    font-size: 15px;
    line-height: 26px;
    text-align: center;
    width: 50px;
    height: 23px;
    overflow: hidden;
    margin-left: -25px;
    opacity: 0;
    filter: alpha(opacity=0); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
    -webkit-box-shadow: 0px 1px 2px rgba(0,0,0,0.3);
    -moz-box-shadow: 0px 1px 2px rgba(0,0,0,0.3);
    box-shadow: 0px 1px 2px rgba(0,0,0,0.3);
}
.lb-overlay img{
    /* height: 100%; For Opera max-height does not seem to work */
    max-height: 100%;
    position: relative;
    opacity: 0;
    filter: alpha(opacity=0); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
    -webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.3);
    -moz-box-shadow: 1px 1px 4px rgba(0,0,0,0.3);
    box-shadow: 0px 2px 7px rgba(0,0,0,0.2);
    -webkit-transition: opacity 0.5s linear;
    -moz-transition: opacity 0.5s linear;
    -o-transition: opacity 0.5s linear;
    -ms-transition: opacity 0.5s linear;
    transition: opacity 0.5s linear;
}
.lb-prev, .lb-next{
    text-indent: -9000px;
    position: absolute;
    top: -32px;
    width: 24px;
    height: 25px;
    left: 50%;
    opacity: 0.8;
    filter: alpha(opacity=80); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=80)"; /*IE8*/
}
.lb-prev:hover, .lb-next:hover{
    opacity: 1;
    filter: alpha(opacity=99); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=99)"; /*IE8*/
}
.lb-prev{
    margin-left: -30px;
    background: transparent url(../images/arrows.png) no-repeat top left;
}
.lb-next{
    margin-left: 6px;
    background: transparent url(../images/arrows.png) no-repeat top right;
}
.lb-overlay:target {
    width: auto;
    height: auto;
    bottom: 0px;
    right: 0px;
    padding: 80px 100px 120px 100px;
}
.lb-overlay:target img,
.lb-overlay:target a.lb-close{
    opacity: 1;
    filter: alpha(opacity=99); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=99)"; /*IE8*/
}
/*
    100% Height for Opera as the max-height seems to be ignored, not optimal for large screens
    http://bricss.net/post/11230266445/css-hack-to-target-opera
*/
x:-o-prefocus, .lb-overlay img {
    height: 100%;
}

There isn't jQuery involved, so i'm assuming it will just be a very simple property to add, but I cannot figure it out.
Cheers for the help!

A:

This can be solved with a simple addition to your CSS on line 355 (.lb-overlay img):
Add a max-width: 100%; below the max-height:100%;
Let me know if that makes it behave how you are expecting!


Q:

Automatic NSView resizing

I'm doing something with cocoa which I think is a bit complicate for a beginner like me. I tried a few things, but I admit I need some theory first, because I would like to understand exactly the meaning of this concepts.
I see that every NSView and every class that subclasses it has one thing called frame, and one called bounds. They both have a size with width and height and an origin.
I have an NSView with an NSTableView inside of it.
I have the size of a row from the table view, and I would like to set the height of both NSView and NSTableView equal to rows*rowSize, in a way that the group NSView+subviews is automatically resized when an object is added or removed to and from the data source of the Table View.
I made some experiments, but I did end a bit confused about frame, bounds, sizes and so on. I don't know what I should change and how.
Can you please give me an hint about what bounds and frame basically are, and how can I achieve that magic resizing?
Thank you for your replies in advance. Best regards,
—Albé

A:

The difference between frame and bounds is covered very nicely in the View Programming Guide (under View Geometry).
You'll also want to peruse the NSView Class Reference, where you'll find some handy notifications, such as NSViewFrameDidChangeNotification and handy methods such as setPostsFrameChangedNotifications:.


Q:

Cmake compiling python into build folder

I think an example would be the best way to demonstrate my problem:
Lets say I have a source directory named src. This directory has two files, a CMakeLists.txt file and a python file named blah. In the same place where src is stored, there is a folder named build. Now, I would like to be able to run cmake and make it compile my python file blah and place it into my build directory. Currently, my CMakeLists.txt is just copying the uncompiled code straight into my build directory using the call:
CONFIGURE_FILE(${PATH_TO_SOURCE}/blah.py ${PATH_TO_BUILD}/blah.py COPYONLY)

Then I run make in the terminal to compile the actual file. This leaves the uncompiled python file in my build directory, which is no good. I've tried using ADD_EXECUTABLES, creating a custom target and using COMMAND, but my syntax must be off somewhere. Any help would be greatly appreciated!

A:

CMake doesn't support Python out of the box, AFAIK. Because of this, you will need to write rule to build python files, something like that:
macro(add_python_target tgt)
  foreach(file ${ARGN})
    set(OUT ${CMAKE_CURRENT_BINARY_DIR}/${file}.pyo)
    list(APPEND OUT_FILES ${OUT})
    add_custom_command(OUTPUT ${OUT}
        COMMAND <python command you use to byte-compile .py file>)
  endforeach()

  add_custom_target(${tgt} ALL DEPENDS ${OUT_FILES})
endmacro()

After defining it, you can use it this way:
add_python_target(blabla blah.py)

If you want to make adjustmenets or need more information, see CMake documentation.


Q:

Cutting depth of a Jig Saw

I'm looking at getting a hand held Jig Saw like the Bosch 150 CE because it has the longest cutting depth 15cm(6"). I'm wanting to do some end notching on 150mm x 150mm lumber.
For example:

What I'd like to know though is what happens when you attempt to cut through a larger piece then the blade is specified for, e.g. 200mm? Must the blade be able to extend past the other side of the material, or can you do a cut only part way into it? So if I wanted to notch a 200mm piece, could I do a 150mm cut, then flip the wood over and cut the remaining 50mm?
For example:

I asked several sellers at stores why all the Jig Saws they have only have it specified that they can cut to 150mm max, yet they sell blades for 200mm. Nobody could tell me why.
If this isn't how you would tackle a notch on pieces bigger than 150mm, could you point me in the direction of how you would do it? At the moment I'm using a hack saw and chisels and it takes too long considering how many I have to do.

A:

Hand-held jigsaws are not the right tool for cutting large notches in a 6x6 post. Yes, the blade must extend past the wood - they only cut on the front of the blade, not the bottom. And the blade will drift quite a bit going through 6 inches of lumber. Jigsaws are meant for fine detail work, not large straight cuts.
However, a close cousin is the reciprocating saw like the Bosch RS35. Larger motor, much heavier blades. You still have the problem of squaring off the bottom of the notch, but if you use a large auger bit to make a series of holes you will be able to remove the bulk with one good hammer hit and then use a thinner blade or a chisel to flatten out the bottom.
If you have a large number and want to mass-produce the notches I would rent a 12 to 16 inch circular saw, line up all the posts, bind them together, and make a jig to hold the saw in position on the ends. Cut, move blade down a bit, repeat.

A:

I am sure you can do a partial depth cut with a jigsaw. I have done the same in a 4" thick wood piece, when the cutting depth of the blade was only 3-4/9". There was no problem of the saw "jumping up", as opposed to what the other responders have mentioned. The quality of cut was also O.K. (it depends upon the blade you use). I recommend Bosch T744D blade for a 6"-7" depth of cut.


Q:

Why am I sometimes outside of town when I log in?

So far I have never logged out without first heading back to town. It takes longer and sets you up for a nasty surprise when you log back in.
For some reason, however, I occasionally find myself outside of town when I log back in. I'm usually standing near the waypoint that I took to get back to town before logging off. It doesn't seem to be a problem with the game not saving, since the items that I sold and salvaged in town before logging off are still gone.
Is this a bug? Has anyone else run into this problem?

A:

You always start from your most recent checkpoint, or, if you selected a new quest step, wherever that quest step starts. It's not a bug.


Q:

Getting Bonjour Address with IP Address and/or Host Name

I'm working on an iPhone-iPad app with Objective-C. I need to get the Bonjour Address of the device. I understand this address is generated with the hostname of the device, which I've already got.
Could anybody help me?
Thanks in advance.
Mikywan.

A:

see following
service = [[NSNetService alloc] initWithDomain:@"local." type:@"_music._tcp" name:serviceName];

[service setDelegate:delegateObject];

[service resolveWithTimeout:5.0]; // This code will return an address on delegate method`

following delegate methods will get fired depending on the result
 netServiceDidResolveAddress

   netService:didNotResolve:

See Docs for more detailed description


Q:

¿como actulizar registros de una base de datos despues de realizar la consulta?

Estoy haciendo la actualizacion de datos  de un registro en mi base de datos pero antes necesito obtener los datos de ese registro en sus campos
respectivos esta es mi base datos.
Field             type         key   default
servicio_No       int(11)      PRI     NULL
tipo_Ambulancia   Varchar(5)           NULL
tipo_Traslado     varchar(20)          NUll
cliente           varchar(45)          NULL
fecha_Solicitud   date                 NULL

consultar.php

    <title>Inicio Consulta.</title>
    <meta http-equiv="Content-type" content="text/html"; charset="utf-8">
    <link rel="stylesheet" type="text/css" href="estilos.css">

            <form class="form" method="POST" action="servicioConsultado.php">

Consultando Servicio

                    Servicio No:

                    <input type="text" REQUIRED name="id" size="20" class="input">

                    <input type="submit" value="Consultar" name="btn-consultar" class="submit">
       </form>

formatoModificacion.php

    <title>Consultando Servicio...</title>
    <meta http-equiv="Content-type" content="text/html"; charset="utf-8">

<?php
echo "";
//Conexion a la base de datos
$conexion =  mysqli_connect("localhost", "root","admin123","database");
//Validamos la conexion a la base de datos
if (mysqli_connect_errno()) {
    echo 'Fallo la conexion a la base de datos';
}
//Limpiamos y Recibimos por POST los datos procedentes del formulario
$id = mysqli_real_escape_string($conexion, $_POST['id']);

    $query = "SELECT servicio_No, hora, tipo_Ambulancia, tipo_Traslado, horario, cliente, fecha_Solicitud FROM servicio WHERE servicio_No = ?";
    /*Prepara la setencia SQl para su ejecucion*/
if ($stmt = mysqli_prepare($conexion, $query)) {

    /*Agrega variables a una sentencia preparada como parametros*/
    /* ligar parámetros para marcadores */
    /*IMPORTANTE: Si id no es numérico en la base de datos, cambia la i por una s*/
    mysqli_stmt_bind_param($stmt, "i", $id);

    /* Ejecuta una consulta preparada */
    mysqli_stmt_execute($stmt);

    /*Se transfiere los  resultados de la ultima consulta*/
    $stmt->store_result();

    /* Vincula las variables a una setencia preparada para el almacenamineto de result */
    $stmt->bind_result($servicio_No, $hora, $tipo_Ambulancia, $tipo_Traslado, $horario, $cliente, $fecha_Solicitud);
     while ($stmt->fetch()) {
        echo "

Regulacion

        <form method='POST' action='modificarServicio.php'  class='form'>

    Servicio No:<input type='text' name='servicio_No' value='".$servicio_No."' style='width: 2%'>

    Tipo Ambulancia:
        <select name='tipo_Ambulancia'>
            <option value='".$tipo_Ambulancia."'>TAB</option>
            <option value='".$tipo_Ambulancia."'>TAM</option>
        </select>

Tipo Traslado:
        <select name='tipo_Traslado'>
            <option value='".$tipo_Traslado."'>Simple</option>
            <option value='".$tipo_Traslado."'>Doble</option>
            <option value='".$tipo_Traslado."'>Asistencia</option>
            <option value='".$tipo_Traslado."'>Evento</option>
        </select>
    Cliente:
    <select name='cliente'>
        <option value='".$cliente."'>Particular</option>
        <option value='".$cliente."'>EMP Medisanitas</option>
        <option value='".$cliente."'>ARL Colmena</option>
        <option value='".$cliente."'>AXA</option>
        <option value='".$cliente."'>PEPS Sanitas</option>
        <option value='".$cliente."'>San Esteban</option>
        <option value='".$cliente."'>EMP Colsanitas</option>
        <option value='".$cliente."'>HSVF Medellin</option>
        <option value='".$cliente."'>Hospital Pablo Tobon Uribe</option>
        <option value='".$cliente."'>Seguros De Vida Suramerica</option>
        <option value='".$cliente."'>EPM</option>
        <option value='".$cliente."'>Clinica Rosario</option>
        <option value='".$cliente."'>Coosalud</option>
        <option value='".$cliente."'>HSVF Rionegro</option>
        <option value='".$cliente."'>Clinica Sagrado Corazon</option>
        <option value='".$cliente."'>Sky Ambulance</option>
        <option value='".$cliente."'>Quirofanos el tesoro</option>
    </select>

    Fechar Solicitud:<input type='text' name='fecha_Solicitud' value='".$fecha_Solicitud."'>
    <input type='submit' value='Modificar' class='submit'>
    </form>
    ";
    }

}else{
    echo '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=http://localhost/Aeroasistencia/Servicios/consultarServicio.php">
         ';
}
//Cerramos la conexion con la base de datos
mysqli_close($conexion);
?>

modificarServicio.php
     <?php
    //Conexion a la base de datos
    $conexion =  mysqli_connect("localhost", "root", "admin123", "database");
    //Validamos la conexion a la base de datos
    if (mysqli_connect_errno()) {
        echo 'Fallo la conexion a la base de datos';
    }
                ////Limpiamos y Recibimos por POST los datos procedentes del formulario
                $servicio_No = $_POST['servicio_No'];
                $tipo_Ambulancia = $_POST['tipo_Ambulancia'];
                $tipo_Traslado = $_POST['tipo_Traslado'];
                $cliente = $_POST['cliente'];
                $fecha_Solicitud = date('Y-m-d');

    mysqli_query($conexion,"UPDATE servicio SET servicio_No ='$servicio_No',
                                                            tipo_Ambulancia = '$tipo_Ambulancia',
                                                            tipo_Traslado = '$tipo_Traslado',

                                                            cliente = '$cliente',
                                                            fecha_Solicitud = '$fecha_Solicitud',
                                                            WHERE
                                                            servicio_No = '$servicio_No'") or die("ERROR AL ACTUALIZAR");

    mysqli_close($conexion);
?>
                <META HTTP-EQUIV="Refresh" CONTENT="0; URL=http://localhost/Aeroasistencia/Servicios/index.php">

A:

El problema esta en como estas construyendo los select.  Les estas poniendo el mismo value a todas las opciones.  Te dejo un ejemplo con la primera opcion:
<select name='cliente'>
    <option value='Particular' "
        . ($cliente == 'Particular' ? "selected" : "") . ">Particular</option>
                 // Aqui van todas las otras opciones
                 // con un formato similar
                 //
</select>

Asi tendrias que construir todas las otras opciones.


Q:

Sinatra API Server Accessing Preexistent Database via Activerecord: about validations

I'm experimenting great Sinatra environment to realize a json API server that access data from a "legacy" db, (an existent database, already in production).
I'm enjoing sinatra-activerecord gem to access my data. as simple as include in the Sinatra app the simple decalration:
class Exam < ActiveRecord::Base
end

I'm enjoing too tux (the rails console equivalent), to query my models (tables).
Now, I have an Architectural doubt about two different scenarios explained here below, in the case of inserting new records via an API call (let say a POST client request to Create/update a record):
Scenario 1. Existent DB as part of (my) Rails project, already in prod
suppose my production database (postgresql instance) is part of a Rails project developed by myself, so I have my Activerecord Models .rb code that contain quite complex validations methods; By example the above mentioned Model exam.rb consiste of a thousand of line of some complex regex validation methods...
In that scenario, what is the best technical solution to avoid Model source code duplication (and so poossible mismatch errors) ? My I have to do in the Sinatra app, an OS symbolik link to the original Rails model exam.rb ... ?
Scenario 2. Existent DB developed by someone else
so suppose I have access at the database tables, but I do not have any source code about applicative data "validations" (maybe developed in Java or any code I do not access for some reasons...)
In that scenario, I think the way is to re-write validations in ruby-activerecord; right ?
sorry for my long post
giorgio
about.me/solyaris

A:

Scenario 1. Existent DB as part of (my) Rails project, already in prod
You have three options (in my opinion):

Mount the Sinatra app via Rack along with the Rails app (in the config.ru), and then it will be able to access the same code as the Rails app.
Make the database code into its own library, put it in a gem, get both apps to require the gem.
Wrap the existing DB in a data API, one that serves no pages, only data (this may be what you're trying to do with Sinatra anyway). Take the direct access to the database away from the Rails app and get it to make calls to the new API just like any other client.

I believe option 2 is better than option 1, and option 3 is better than option 2. If I was going to move to option 3, then I'd probably do 1 first, then 2, then 3, as each can use the previous option to make it easier.
Scenario 2. Existent DB developed by someone else
I'm not certain I fully understand, but yes, you'd have to re-write validations. A well designed database will mean that some validations should already exist in the form of constraints, but not always.


Q:

How to create a function to accept concatenated source value - Excel VBA

I'm trying to create a vba function to replace multiple characters from cell value. I'm calling this function 'TestFunction' for now. The purpose of the function is to parse illegal characters from the data to be able to use it and the original data needs to remain in their own columns after parse.
I have pasted my code and table as a reference.

To use the function I would like to use =TestFunction(...) on a helper column on the same row as the data is in. The code works for a single reference e.g. =TestFunction(A1), but when trying to pass concatenated reference e.g. =TestFunction(A1&A2) it returns #VALUE!.
I've tried to fix this for a while with no success. I could make another helper column where the concatenated data is but I would really love to get this function to work without additional column.
Anyone know if this is possible to achieve?
Reference code:
Function TestFunction(CellContents As Range) As String
  Dim CellTextReplaced As String
  Dim char As Variant
  ' Characters to be replaced with "|" as delimiter
  Const SpecialCharacters As String = ".|,|!| |/|\|+|-|@|&"

  ' Replace all special characters
  CellTextReplaced = CellContents.Value
    For Each char In Split(SpecialCharacters, "|")
      CellTextReplaced = Replace(CellTextReplaced, char, "")
    Next
  ' Output

  TestFunction = CellTextReplaced
End Function

Reference table:
  |   A    |    B     |        C           |          D           |
-------------------------------------------------------------------
1 | .test  |   .test  |  =TestFunction(A1) | =TestFunction(A1&B1) |
2 | ,test  |   ,test  |  =TestFunction(A2) | =TestFunction(A2&B2) |
3 | test-  |   test-  |  =TestFunction(A3) | =TestFunction(A3&B3) |
4 | /test\ |   /test\ |  =TestFunction(A4) | =TestFunction(A4&B4) |

A:

The issue is that your function TestFunction(CellContents As Range) was waiting for a Range but A1&B1 actually is a String because the concatenation with & casts the values of the two ranges A1 and B1 into a string.
I suggest the following improvements:
Option Explicit

Public Function TestFunction(ByVal CellContents As String) As String
    Const SpecialCharacters As String = ".,! /\+-@&"

    Dim iChar As Long
    For iChar = 1 To Len(SpecialCharacters)
        CellContents = Replace$(CellContents, Mid$(SpecialCharacters, iChar, 1), "")
    Next iChar

    TestFunction = CellContents
End Function


Q:

как вставить иконку в кнопку

создавая динамически кнопку button с помощью jquery:
var mybutton = $('<button/>',
{
    text: 'Click Me',
    click: function () { alert('Hello Habr'); }
}).appendTo('.content');

как в кнопку можно вставить иконку

A:

Один из способов. Есть свойство html, в которое можно вставить html.

var mybutton = $('<button/>', {
  html: 'icon Click Me',
  click: function() {
    alert('Hello Habr');
  }
}).appendTo('.content')


Q:

Jetty: Configure SSL connector to only serve specific resource(s)

Apologies in advance if I'm using terms incorrectly, I'm not familiar with Jetty.
I've attached an SSL connector to my Jetty server.  Now, my public resources are accessible through both http and https.  I would like to restrict the resources served from https, preferably by checking against some URI pattern. How would I accomplish this?

A:

Use the standard servlet <security-constraint> configurations in your WEB-INF/web.xml
Example:
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Force SSL on /private/ url-patterns</web-resource-name>
        <url-pattern>/private/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>