text:
Q: Script to compress contents of a folder once per month into an archive and then delete I need a script to backup the contents of a directory including sub folders to a single archive file. I would like to run this script on a monthly schedule (will use task scheduler), so every 30 days the script compress the contents of the folder and create a NEW archive file with the month as the name of the file and then delete the files/subfolders.
Ive put together a mixture of coding I found online, this is the product. The code functions as desired, just not sure if the logic is there.
for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x

IF %month%==1 (
SET mth=Jan
)
IF %month%==2 (
SET mth=Feb
)
IF %month%==3 (
SET mth=Mar
)
IF %month%==4 (
SET mth=Apr
)
IF %month%==5 (
SET mth=May
)
IF %month%==6 (
SET mth=Jun
)
IF %month%==7 (
SET mth=Jul
)
IF %month%==8 (
SET mth=Aug
)
IF %month%==9 (
SET mth=Sep
)
IF %month%==10 (
SET mth=Oct
)
IF %month%==11 (
SET mth=Nov
)
IF %month%==12 (
SET mth=Dec
)

for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a "%mth%-%Year%.zip" "%%X\"

IF EXIST %mth%-%Year%.zip (
    FOR /D %%p IN ("*") DO rmdir "%%p" /s /q
) ELSE (
    echo NO
)

If anyone could help me optimize this code or improve it I would be greatly appreciated.

A: I suggest to use one of the two solutions below and run either WinRAR or the batch file using 7-Zip with task scheduler on last day of a month some minutes before midnight, or every 30 days if it is not really necessary to have all files of a month in one archive.
One note before reading below about the solutions:
Do not create the ZIP archive in the folder with the files and subfolders to archive. That would not be a good idea on using the solution with 7-Zip.

WinRAR solution
My first solution for this task is using WinRAR which makes this task a one-liner:
"C:\Program Files\WinRAR\WinRAR.exe" m -afzip -agMMM-YYYY -ibck -cfg- -ep1 -m5 -r "C:\Path to Destination Folder of Archive\.zip" "C:\Temp\Folder with Files and Subfolders to compress\"

The destination folder of the ZIP archive must already exist on execution of WinRAR.
In program files folder of WinRAR there is the text file Rar.txt which contains all commands and switches with an explanation for console version Rar.exe. Help of WinRAR has on tab Contents the item Command line mode with subitems Commands and Switches. Both can be used to create a command line like above.
The command m is explained with moves files and directories which results in the files and directories being erased upon successful completion of the packing operation.
The switch -afzip is a WinRAR only switch which selects ZIP as archive format. Rar.exe does not support this switch as the console version supports only creating RAR archives.
The switch -ag with option MMM-YYYY results in appending to name of archive file before file extension the month in short name format and the year, e.g. Nov-2014.
The switch -ibck results in minimizing WinRAR window to Windows system tray on archive processing.
The switch -cfg- results in ignoring configuration file and RAR environment variable (just for safety).
The switch -ep1 results in excluding from archive the entire path to base directory which results here not putting "C:\Temp\Folder with Files and Subfolders to compress\" into the archive, just the file and subfolders in this folder.
The switch -m5 sets best compression for the archive.
The switch -r is a very important one as it tells WinRAR to recursive compress all files and folders.
The archive file created is for example Nov-2014.zip because the name of the archive file is just .zip.
Investing a small amount of money for WinRAR license can make many archiving and backup tasks very simple.
Of course it would be also possible to create a RAR archive instead of a ZIP archive.

7-Zip solution
The 7-Zip solution needs more effort as currently not having features like WinRAR for such backup tasks.
@echo off
setlocal EnableDelayedExpansion
for /f %%x in ('wmic path win32_localtime get /format:list') do (
    set "Value=%%x"
    if "!Value:~0,5!"=="Month" (
        set "Month=!Value:~6!"
    ) else if "!Value:~0,4!"=="Year" (
        set "Year=!Value:~5!"
    )
)
if "%Month%"=="1"  set "Month=Jan" & goto Compress
if "%Month%"=="2"  set "Month=Feb" & goto Compress
if "%Month%"=="3"  set "Month=Mar" & goto Compress
if "%Month%"=="4"  set "Month=Apr" & goto Compress
if "%Month%"=="5"  set "Month=May" & goto Compress
if "%Month%"=="6"  set "Month=Jun" & goto Compress
if "%Month%"=="7"  set "Month=Jul" & goto Compress
if "%Month%"=="8"  set "Month=Aug" & goto Compress
if "%Month%"=="9"  set "Month=Sep" & goto Compress
if "%Month%"=="10" set "Month=Oct" & goto Compress
if "%Month%"=="11" set "Month=Nov" & goto Compress
set "Month=Dec"

:Compress
set "FolderToCompress=C:\Temp\Folder with Files and Subfolders to compress"
"C:\Program Files\7-Zip\7z.exe" a -mx=9 -r -tzip "C:\Path to Destination Folder of Archive\%Month%-%Year%.zip" "%FolderToCompress%\*"
rd /S /Q "%FolderToCompress%"
md "%FolderToCompress%"
endlocal

First, the commands FOR, IF and SET are used to process output of Windows Management Instrumentation Command to get month and year.
For help on those 3 commands run in a command prompt window (console window)

*

*help for or for /?

*help if or if /?

*help set or set /?
Or the Microsoft TechNet articles for for, if and set are read for details.
And help on the other commands GOTO, MD, RD and SETLOCAL can be get the same way.
After determining month and year for archive file name, 7-Zip is executed to create a ZIP file in a destination folder which of course must already exist.
And also 7-Zip has a help which on Contents tab has the item Command Line Version with the subitems Commands and Switches.
The command a is for compressing files into an archive. There is no m as WinRAR offers. So deletion after compression must be done separately.
The switch -m with the option x=9 sets best compression.
The switch -r is a very important one as it tells 7-Zip to recursive compress all files and folders.
And the switch -tzip selects the standard ZIP format.
With the command RD the folder "C:\Temp\Folder with Files and Subfolders to compress\" with all files and subfolders is deleted and next with MD the folder itself is recreated as I suppose the folder itself should remain for next month.


text:
Q: How to structure a Dart application with multiple views with Polymer This question has been asked before but since the answer to that question Dart has adopted polymer to replace Web UI.  Is there a Polymer version of the answer to this question?  Also, I saw the answer relating to routes, which I like, but investigating it further has led me to believe that routes and polymer do not play well together yet.
I would also like to solicit views on the new Angular-Dart since I am comfortable with Angular but see it as a competing technology to polymer at least in the Dart world.
How to build a complex Web UI application with multiple views?

A: Since Polymer is just a later version of web_ui (Polymer >= 0.5.0, web_ui is < 0.5.0) of the same framework, I believe the responses in the original question are still valid, only the syntax and API changes need be updated (ie, new Element.tag() vs new Element.html() etc).
See my sample on using routes with polymer

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ionic 2 - Keyboard Not Hiding on Form Input(text area). Issue present in iOS devices, android works fine When the user taps outside the input fields the keyboard is not hiding. Using ionic-plugin-keyboard on ionic 2. The UI template is as following,
<ion-content padding id="ten" no-bounce>

{{ "PLEASEENTER" | translate}}
{{"name" | translate}}

<form [formGroup] = "tn" id="tn">
<ion-item id="inputItem"  [ngClass] = "{'requiredField' : requiredFieldNotFilled}">
    <ion-textarea #input class="mediumFontInput" clearInput ="false"  type="text" name="name" formControlName="name" placeholder = "{{'NAME' | translate}}" [(ngModel)]="search" (input)="searchList($event)" (focus)="setCursorPosition($event)" ></ion-textarea>
</ion-item>
</form>

</ion-content>

Any help or suggestion is appreciated.


text:
Q: How to load HTML file into HTML use JS with button I what to load the b.js file to HTML with button and function. when user type "yes" and click on "Ok" button, "b.js" must load in page (not open in new window or new tab)
what code I must to use in ??????????? place to solve my problem?
here is the code:
HOME.html

<form name="load">yes OR no<input name="id" type="text">
<input type="button" value="OK" onClick="my(document.forms.load)">

b.js
document.write(`

 Load the HTML code

`);

I tried to use   but this code immediately load "b.js" that I dont what this
I tried to use
var scriptTag = document.createElement('script');
scriptTag.setAttribute('src','b.js');
document.head.appendChild(scriptTag)

but not working
I tried to use
document.getElementsByTagName('body')[0].innerHTML += "";

but this code not working
what can I do to load the "b.js" file after click on button?
thanks :)

A: Is this what you're looking gor?

function my(form) {
  const loadHTML = () => {
    const scriptB = document.createElement('script')
    scriptB.setAttribute('src','b.js')
    console.log(scriptB)
    document.write(`

Load the HTML code

      ${scriptB.outerHTML}
    `);
  }
  if (form.id.value==="yes") {
    loadHTML()
  } else {
    alert("NO")
  }
}

<form name="load">

YES or NO

  <input name="id" type="text">
  <input type="button" value="OK" onClick="my(document.forms.load)">
</form>


text:
Q: Intersection Observer fine tuning for different window sizes This is my code so far:

const mediaInViewport = document.querySelectorAll('.media');
const links = Array.from(document.querySelectorAll('.link'));
let actLink = links[0];

document.body.addEventListener('click', (event) => {
  if (event.target.tagName === 'a') {
    actLink.classList.remove('active');
    actLink = links.find(link => event.target.href === link.href)
    actLink.classList.add('active');
  }
}, false)

observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    if (entry.target && entry.isIntersecting) {
      const closestParent = entry.target.closest('section');
      if (closestParent) {
        actLink.classList.remove('active');
        actLink = links.find(link =>
          link.href.slice(link.href.lastIndexOf('#')) === `#${closestParent.id}`
        )
        actLink.classList.add('active');
      }
    }
  });
}, {
  threshold: 0
});

window.addEventListener('DOMContentLoaded', () => {
  setTimeout( // Wait for images to fully load
    () => {
      mediaInViewport.forEach((item) => {
        observer.observe(item);
      });
    }, 1000);
});
* {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  font-size: 30px;
  text-decoration: none;
  color: inherit;
}

body {
  display: flex;
  cursor: default;
}

#left,
#right {
  width: 50%;
  height: 100vh;
  overflow-y: scroll;
  scroll-behavior: smooth;
}

#left {
  background-color: rgb(220, 220, 220);
}

#right {
  background-color: rgb(200, 200, 200);
}

.media {
  padding: 10px;
  padding-bottom: 0;
}

.media:nth-last-child(1) {
  margin-bottom: 10px;
}

img {
  display: block;
  width: 100%;
}

.link {
  cursor: pointer;
}

.active {
  background-color: black;
  color: white;
}

  Landscapes
  Cats
  Beer
  Food

The observation function should work with all window sizes. Currently, if the window size is a bit higher, for example the "Beer" link doesn't receive the .active class if you click on it or scroll too insensitive.
Is there a way to fix that?
Rules like the following would be needed:

*

*Always only the last observed object should trigger an .active
class.

*But: If there are at one point different observable objects visible
(for example after a click on the link "Beer"), then the "most
dominant" one (the one that is not cut off and most present) should
trigger the .active class.

I would be sooooo thankful for help! <3

A:

const mediaInViewport = Array.from(document.querySelectorAll('.media'));
const sections = Array.from(document.querySelector('#right').children);
const links = Array.from(document.querySelectorAll('.link'));
let actLink = links[0];
let actSection = null;
let targetLink = null;
let targetSection = null;

document.body.addEventListener('click', (event) => {
  if (event.target.tagName === 'A') {
    event.preventDefault();
    targetLink = event.target;
    targetSection = sections.find(section => section.id ===  targetLink.href.slice(targetLink.href.lastIndexOf('#')+1))
    location.hash = targetLink.href.slice(targetLink.href.lastIndexOf('#'));
    actLink.classList.remove('active');
    actLink = links.find(l => event.target.href === l.href)
    actLink.classList.add('active');

  }
}, false)

observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    if (entry.target && entry.isIntersecting) {
      const closestParent = entry.target.closest('section');
      if (closestParent) {
        actLink.classList.remove('active');
        if (!targetLink) {
          actLink = links.find(link =>
            link.href.slice(link.href.lastIndexOf('#')) === `#${closestParent.id}`
          )
        } else {
          if (closestParent === targetSection){
            targetLink = null
          }
        }
        actSection = sections.find(section => section.id ===  actLink.href.slice(actLink.href.lastIndexOf('#')))
        actLink.classList.add('active');
      }
    }
  });
}, {
  threshold: 0.3
});

window.addEventListener('DOMContentLoaded', () => {
  setTimeout( // Wait for images to fully load
    () => {
      mediaInViewport.forEach((item) => {
        observer.observe(item);
      });
    }, 1000);
});
* {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  font-size: 30px;
}

body {
  display: flex;
  cursor: default;
}

#left,
#right {
  width: 50%;
  height: 100vh;
  overflow-y: scroll;
  scroll-behavior: smooth;
}

#left {
  background-color: rgb(220, 220, 220);
}

#right {
  background-color: rgb(200, 200, 200);
}

.media {
  padding: 10px;
  padding-bottom: 0;
}

.media:nth-last-child(1) {
  margin-bottom: 10px;
}

img {
  display: block;
  width: 100%;
}

.link:active {
  cursor: pointer;
}

a:target {
  background-color: black;
  color: white;
}

a {
  text-decoration: none;
  color: inherit;
}

section:target {
  background-color: black;
  color: white;
}

.active {
  background-color: black;
  color: white;
}

      Landscapes
      Cats
      Beer
      Food


text:
Q: How to upload images to firebase without using an HTML form? How do I upload images to firebase without an HTML form, I need to use code only.
I have tried some ways myself but the files fail to preview they're corrupted I guess.
I'm developing my App in React and I need a way to upload images to firebase without an HTML form
I tried:
await uploadBytes(storageRef, '../images/image.jpg')

I also tried:
const metadata ={ contentType:'image/jpeg' }
and also
const metadata ={
  contentType:'image/svg+xml'
}
await uploadBytes(storageRef, '../images/image.jpg', metadata)

A: There is no way to upload a file to Cloud Storage for Firebase with just a local path as you do here uploadBytes(storageRef, '../images/image.jpg').
If you pass a string as the second argument, you will have to call uploadString and the second argument has to be the base64 encoded data that you want to upload.
If you want to upload a file based on its path, you will have to either create a File reference to that file, or read its data into a Blob and then pass that to uploadBytes.
All of these are covered in the Firebase documentation on uploading data, so I recommend keeping that handy.

A: use the Firebase SDK for Cloud Storage and the FileReader API in JavaScript.
import { getStorage, ref, uploadBytes } from "firebase/storage";

const storage = getStorage();

const handleFileUpload = (file) => {
  const storageRef = ref(storage, "images/" + file.name);
  const metadata = {
    contentType: file.type,
  };
  const reader = new FileReader();
  reader.readAsArrayBuffer(file);
  reader.onload = async (event) => {
    const buffer = event.target.result;
    await uploadBytes(storageRef, buffer, metadata);
  };
};


text:
Q: why cant I change colnames with dates? I have created a dataframe with columns representing Lon position, Lat position and beyond the 3rd column its dates. however I'm unable to rename the columns with the date values.
rtime<-as.Date(time,origin='1900-12-31')

which gives the desired output as date with dd-mm-yyyy format.
Here is my attempt to rename the columns:
colnames(dfR)[3:368]<-rtime

I'm unable to change the names using this. any input?


text:
Q: Objective c select statement hey guys im trying to do a SELECT Statement from a local SQLDB
so my statement is something like
select ..etc..etc WHERE Date =%@,theDate
theDate is an NSString variable.
i NSLoged theDate and it returned 22/06/2010
But it doesnt work so i tried the following
select ..etc..etc WHERE DATE ='22/06/2010'
And the values came by. any idea why this happens?
In the SQLDB, the column type for DATE is NVARCHAR though. does that matters?

A: from your question it looks like including single quotes around the %@ token might be worth a shot
"select....etc. etc. ...WHERE Date ='%@'",theDate


text:
Q: Annotation for field matching or equals I have an endpoint in my spring-boot application which accepts from & to ids. Now in my domain, I have following code:
@Data
class UserAccount {

    @NotNull
    @NotEmpty
    private final String from;

    @NotNull
    @NotEmpty
    private final String to;

    @JsonCreator
    public UserAccount(@JsonProperty("from") String from,
                    @JsonProperty("to") String to,) {
        this.from = from;
        this.to = to;
    }
}

Is there a way to validate that from & to fields should not be same using annotations?

A: Lombok does not have this feature as of today. Lombok used to reduce boilerplate code. You asked for something that more like business logic and should be written out explicitly (from the Lombok point of view):
public UserAccount(@NonNull String from, @NonNull String to) {
    this.from = from;
    this.to = to;
    if (form.equals(to)) {
        throw new IllegalArgumentException("Invalid combination of from and to fields.");
    }
}

The onX experimental feature might be also interesting: https://projectlombok.org/features/experimental/onX
Please note that @NonNull and @NotNull are not the same.


text:
Q: cannot access server terminal in Ubuntu 14.04 i am new to Ubuntu OS. I recently installed Ubuntu Server 14.04. in addition to that i also checked the option of installing ubuntu desktop so it installed ubuntu 14.04 lts with that.
Now when the system loads up it takes me directly to Ubuntu Desktop 14.04 LTS.
Okay here's what i want to do. i want to access the server using our client machine that is why i installed desktop(client) along with the server. But as i get into login screen of desktop i have no option to access the Server terminal.
Please I need help...

A: Install SSH server daemon on server machine:
sudo apt-get install openssh-server
sudo service ssh start

Configuration files are in /etc/ssh/
Create user for server (do not use root or your own account if possible)
mkdir /home/jimmy
sudo useradd jimmy -s /bin/sh -d /home/jimmy
sudo chown jimmy /home/jimmy

And enter password for new jimmy user.
For clients
Access from another machine:
ssh jimmy@hostname

ssh jimmy@ip_addr

Port 22 (TCP) must be open. It's recommended to change port number and do not use password login if machine is available from public net.


text:
Q: Boundedness of relative risk aversion function Let $f\colon [0,\infty)\mapsto \mathbb{R}$ be a strictly increasing and strictly concave function. Let $$RRA_f(x)=-\frac{xf''(x)}{f'(x)}.$$
Is it possible that $RRA_f$ isn't bounded?

A: Consider the function $f(x) = 1-e^{-x}$ on $[0,\infty)$.
We have
$$f'(x) = e^{-x}>0, \\ f''(x)=-e^{-x}<0.$$
So $f$ is strictly increasing and strictly concave.
However,
$$\lim_{x \rightarrow \infty}-\frac{xf''(x)}{f'(x)}= \lim_{x \rightarrow \infty}-\frac{-xe^{-x}}{e^{-x}}= \lim_{x \rightarrow \infty}x= \infty$$
So in this case, $RRA$ is unbounded on $[0,\infty)$.


text:
Q: Mockito unfinished stubbing exception detected ONLY in Intellij Debugger The problem only occurs when I am trying to debug a test via the IntelliJ debugger. It does not happen when I just simply run the test.
CustomerChoiceRepository is a normal Spring Boot JPA repository which here is being mocked with @Mock.

When this line executes in the debugger I get the following error in the watch section of the variables:

The entire error message is:
Method threw 'org.mockito.exceptions.misusing.UnfinishedStubbingException' exception. Cannot evaluate com.item.repository.jpa.CustomerChoiceRepository$MockitoMock$1318657964.toString()

Again this is only is detected in the IntelliJ debugger, as a result the test fails only when I am debugging it.
So my question is: what is happening here?
Is this a bug ? Is this something that I fail to understand because I do not know the internals of Mockito particularly well ?

A: Your IntelliJ is calling toString on the mock during stubbing, which causes the exception.
Check your debugger settings
By default, IntelliJ calls toString on objects in debugger window, but only on objects that override that method. This behaviour is customizable, currently in Preferences -> Build Tools -> Debugger -> Data Views -> Java -> Enable 'toString' object view, but the settings mey differ between IDE versions.
See:

*

*Is it possible to tell IntelliJ IDEA to automatically invoke toString() on the objects inspected in watches, variables, tool tip windows?
Don't call methods on mocked object during stubbing
See:

*

*How do Mockito matchers work?

*How does mockito when() invocation work?


text:
Q: How to make a new Item in a double chained list? I have a double chained list and an item class. I want to implement a function spliced, which does the following
Splice method
The first thing that is required is creating the Handles ap and bn, so i try the following
template <class T> void DoublyLinkedList<T>::splice(Item<T> *a, Item<T> *b, Item<T> *t)
{
    Item<T> ap()=a->prev;
    Item<T> bn()=b->next;
}

Before compiling, my IDE highlights an and bn and says

Illegal Initializer (only variables can be initialized)

Upon compiling, i get this error Error
This is my source code for the Double linked list (you can ignore everything except the splice method, because it was pre-written by our instructors)
#include "DoublyLinkedList.h"

template <class T> DoublyLinkedList<T>::DoublyLinkedList()
{
    h = new Item<T>();
    h->next = h;
    h->prev = h;
}

template <class T> DoublyLinkedList<T>::~DoublyLinkedList()
{
    delete h;
}

template <class T> void DoublyLinkedList<T>::splice(Item<T> *a, Item<T> *b, Item<T> *t)
{
    Item<T> ap()=a->prev;
    Item<T> bn()=b->next;
}

template <class T> Item<T>* DoublyLinkedList<T>::head()
{
    return h;// your code
}

template <class T> bool DoublyLinkedList<T>::isEmpty()
{
    return true;// your code
}

template <class T> Item<T>* DoublyLinkedList<T>::first()
{
    return h;// your code
}

template <class T> Item<T>* DoublyLinkedList<T>::last()
{
    return h;// your code
}

template <class T> void DoublyLinkedList<T>::moveAfter(Item<T> *b, Item<T> *a)
{
    // your code
}

template <class T> void DoublyLinkedList<T>::moveToFront(Item<T> *b)
{
    // your code
}

template <class T> void DoublyLinkedList<T>::moveToBack(Item<T> *b)
{
    // your code
}

template <class T> void DoublyLinkedList<T>::removeItem(Item<T> *b)
{
    // your code
}

template <class T> void DoublyLinkedList<T>::popFront()
{
    // your code
}

template <class T> void DoublyLinkedList<T>::popBack()
{
    // your code
}

template <class T> Item<T>* DoublyLinkedList<T>::insertAfter(T new_element, Item<T> *a)
{
    return h;// your code (use "new" to reserve space on the heap for the new Item and make sure to "delete" it at an appropriate position)
}

template <class T> Item<T>* DoublyLinkedList<T>::insertBefore(T new_element, Item<T> *b)
{
    return h;// your code
}

template <class T> void DoublyLinkedList<T>::pushFront(T new_element)
{
    // your code
}

template <class T> void DoublyLinkedList<T>::pushBack(T new_element)
{
    // your code
}

template <class T> Item<T>* DoublyLinkedList<T>::findElement(T new_element)
{
    return h;// your code
}

template <class T> int DoublyLinkedList<T>::getSize()
{
    return 0;// your code
}

// you can ignore the functions below this line
// -----------------------------------------------------------------------

template <class T> void DoublyLinkedList<T>::bubbleSort()
{
    // not part of this exercise
}

template <class T> void DoublyLinkedList<T>::mergeSort()
{
    // not part of this exercise
}

template <class T> void DoublyLinkedList<T>::mergeSort_sort(DoublyLinkedList<T> * unsorted_list)
{
    // not part of this exercise
}

template <class T> void DoublyLinkedList<T>::mergeSort_merge(DoublyLinkedList<T>* unsorted_list, DoublyLinkedList<T>* l, DoublyLinkedList<T>* r)
{
    // not part of this exercise
}

#if !__has_include ("aircraft.h")
    template class DoublyLinkedList<int>;
#endif

#if __has_include ("aircraft.h")
    #include "aircraft.h"
    template class DoublyLinkedList<aircraft*>;
#endif

And this is the item.h file
#ifndef ITEM_H
#define ITEM_H

template <class T> class Item
{
    public:
        Item();
        Item *prev;
        Item *next;
        T element;
};

template <class T> Item<T>::Item()
{
    prev= this;
    next= this;
}

#endif // ITEM_H


text:
Q: Formula to $\ln$ that holds on interval $x \geq 1$ In the Wikipedia we can find two formulas using power series to $\ln(x)$,
but I would like a formula that holds on the interval $x \geq 1$ (or is possible to calculate $\ln(x)$ to $x \geq 1$ with the same formula).
Is there one?
In other words, a formula like,
$$\ln(x)=\sum_{i=0}^{\infty}a_i x^i$$
The wikipedia formulas are:
$$\ln(x+1)=\sum_{i=1}^{\infty}\frac{(-1)^{i-1}x^i}{i}\text{ for }1 < x \leq1$$
and
$$\ln\left(\frac{x}{x-1}\right)=\sum_{i=1}^{\infty}\frac{1}{i x^i}$$
PS.: Is important to me to use power series, but, any help are welcome.

A: To add to what was written by Gerry Myerson, if $|w|<1$, we have by the usual power series expansion for $\log(1+w)$,
$$\log(1+w)=w-\frac{w^2}{2}+\frac{w^3}{3}-\frac{w^4}{4}+\cdots.\tag{$1$}$$
Replacing $w$ by $-w$, we have
$$\log(1-w)=-w-\frac{w^2}{2}-\frac{w^3}{3}-\frac{w^4}{4}-\cdots.\tag{$2$}$$
Subtracting $(2)$ from $(1)$, we obtain
$$\log(1+w)-\log(1-w)=\log\left(\frac{1+w}{1-w}\right)=2w+2\frac{w^3}{3}+2\frac{w^5}{5}+\cdots.\tag{$3$}$$
For any $x>1$, there is a $w$ between $0$ and $1$ such that $x=\frac{1+w}{1-w}$. We can solve for $w$ explicitly in terms of $x$, obtaining $w=\frac{x-1}{x+1}$.
Thus we get an expansion for $\log x$ in terms of powers of $\frac{x-1}{x+1}$. This is not a power series expansion of $\ln x$, but it can be useful.  For large $x$, the number $w$ is close to $1$, so the convergence is relatively slow. But for smallish $x$, there is usefully fast convergence. Euler, among others, used the series $(3)$ for computations.
Take for example $x=2$. The ordinary series for $\log(1+x)$ converges when $x=1$, but too slowly for practical use. However, in this case $w$ turns out to be $1/3$, and the series $(3)$ converges quite fast. For $x=3$, we get $w=1/2$, and again we get usefully fast convergence.

A: At http://www.efunda.com/math/exp_log/series_exp.cfm you will find $$\log x=2\sum_1^{\infty}{1\over2n-1}\left({x-1\over x+1}\right)^{2n-1}$$ claimed to be valid for $x\gt0$, and several other formulas you might enjoy.

A: Another alternative, that works for $x > -\dfrac 1 2 $ is
$$\log (1+x) =\sum_{n>0} \frac 1 n\left( \frac{x}{x+1}\right)^n$$
This is trivially obtained by setting $u=\dfrac{x}{x+1}$ in
$$-\log(1-u)=\sum_{n >0}\frac {u^n} n $$
or by showing
$$\int_0^x \left( \frac{t}{t+1}\right)^{n+1}\frac{dt}t=\log(1+x)-\sum_{k \leq n} \frac 1 k\left( \frac{x}{x+1}\right)^k$$
Then since
$$\left|\log(1+x)-\sum_{k \leq n} \frac 1 k\left( \frac{x}{x+1}\right)^k\right|=\left| \int_0^x \left( \frac{t}{t+1}\right)^{n+1}\frac{dt}t \right|<\epsilon$$
for sufficiently large $n$ and $x > -\dfrac 1 2 $ the equality follows.


text:
Q: Integrating Apache Jena to Oracle 12c Error: Invalid common user or role name I am new to oracle and Jena both. For my project I am convert Json data to RDF using Apache Jena successfully. I downloaded the latest version of Oracle ie 12c as it supports storage of RDF data and since it has Jena Adapter Support.
I followed all the steps to set up Jena Adapter given HERE in section 7.1. After point 9 there it says to enable queries to perform section 7.3. Since I am new to Oracle I have set it up but now when I am creating a user I get error
CREATE USER rdfusr IDENTIFIED BY rdfusr DEFAULT TABLESPACE rdf_users
            *
ERROR at line 1:
ORA-65096: invalid common user or role name

How to resolve this? Are there any blog/links on how to integrate Jena to Oracle 12c?


text:
Q: Removing a Corrupted Ubuntu Installation I have a corrupted Ubuntu partition on my computer. Would installing a new copy of Ubuntu and selecting to remove the old OS remove the corrupted copy from my computer?

A: Yes, if you choose to overwrite the corrupted partition.
When you got to the Installation type section. You would need to select the option: Replace "OS name" with Ubuntu. ("OS name" = the name of your OS goes here.)


text:
Q: UQM: probability of Orz vac-suit kills in different opponent ships This article on Ultronomicon describes how the Orz "intruders" (Marines) kill enemy crew and are killed in turn.  The article implies that the probabilities are the same regardless of the type of enemy ship.
To me, however, it seems that Orz intruders do better in some enemy ship types than others.  Particularly, the Slylandro probes seem to be almost impervious to them.  Is the article's implication correct in terms of the game source code?  Is it possible that other factors, such as poor random-number generation, could cause the effective probability to be different?

A: I downloaded the source code.  In the file orz.c, there is a function called intruder_preprocess that handles what happens when the intruder is on the enemy ship.  Within that function is the following code:
            BYTE randval;

            ElementPtr->thrust_wait = MARINE_WAIT;

            randval = (BYTE)TFB_Random ();
            if (randval < (0x0100 / 16))
            {
                ElementPtr->life_span = 0;
                ElementPtr->state_flags |= DISAPPEARING;

                ProcessSound (SetAbsSoundIndex (
                        StarShipPtr->RaceDescPtr->ship_data.ship_sounds, 4), ElementPtr);
                goto LeftShip;
            }
            else if (randval < (0x0100 / 2 + 0x0100 / 16))
            {
                if (!DeltaCrew (ShipPtr, -1))
                    ShipPtr->life_span = 0;

                ++ElementPtr->thrust_wait;
                s.origin.x = 16 + (ElementPtr->turn_wait & 3) * 9;
                s.origin.y = 14 + (ElementPtr->turn_wait >> 2) * 11;
                s.frame = SetAbsFrameIndex (ElementPtr->next.image.farray[0],
                        GetFrameCount (ElementPtr->next.image.farray[0]) - 1);
                ModifySilhouette (ShipPtr, &s, 0);
                ProcessSound (SetAbsSoundIndex (
                        StarShipPtr->RaceDescPtr->ship_data.ship_sounds, 3), ElementPtr);
            }

As you can see, a random number is generated from the TFB_Random function (this is defined in the random.c file).  If it is less than 6.25 (this comes from 100/16), the ElementPtr's life_span is set to 0.  ElementPtr represents the intruder and setting life_span to 0 means he dies.  This matches up with the Ultranomicon saying "6.25% chance a marine dies".
If the random number is greater than 6.25 but less than 56.25 (this comes from 50+6.25), which is a range of 50, then the DeltaCrew function is called on ShipPtr with a -1 value.  DeltaCrew is defined in the status.c file, and modifies the number of crew on a ship.  ShipPtr represents the enemy ship and -1 means one enemy crew member has died.  This matches up with the Ultranomicon saying "50% chance one enemy crew dies".
If the random number is greater than 56.25 and less than 100, which is a range of 43.75, then nothing happens.  This matches up with the Ultranomicon saying "43.75% chance nothing happens".
There is no code that checks for the type of enemy ship.  That code in the intruder_preprocess function will execute for all enemy ships, so the Ultranomicon is correct.
EDIT:
As for the TFB_Random function, it is seeded by the TFB_SeedRandom function (also defined in random.c):
#define A 16807 /* a relatively prime number -- also M div Q */
#define M 2147483647L /* 0xFFFFFFFF / 2 */
#define Q 127773L /* M div A */
#define R 2836 /* M mod A */

static DWORD seed = 12345L; /* random number seed */

DWORD
TFB_Random (void)
{
    seed = A * (seed % Q) - R * (seed / Q);
    if (seed > M)
        return (seed -= M);
    else if (seed)
        return (seed);
    else
        return (seed = 1L);
}

DWORD
TFB_SeedRandom (DWORD new_seed)
{
    DWORD old_seed;

    /* coerce the seed to be in the range 1..M */
    if (new_seed == 0L) /* 0 becomes 1 */
        new_seed = 1;
    else if (new_seed > M) /* and less than M */
        new_seed -= M;

    old_seed = seed;
    seed = new_seed;
    return (old_seed);
}

I searched for all calls to TFB_SeedRandom, and every one (related to melee and ship fighting) passes in a value that is based on the current time.  There is nothing that passes in a seed that is dependent on ship type.  If the random number generation or the seeding is poor, then that would be true for all enemy ships, not just certain types.

A: The slylandro probe fries the intruders before they can enter...


text:
Q: How to create an attribute node and attach it to output node..? I'm not able to figure out a way to attach an attribute node to output node in below scenario..
input xml:
<record>
    <user>
        <field name="LastName">user33</field>
        <field name="FirstName">user33</field>
        <field name="Title"/>
        <field name="Email">user33@gmail.com</field>
        <field name="WorkPhone"/>
        <field name="Fax"/>
        <field name="Description">new user</field>
        <field name="Group Member"> group1</field>
    </user>
</record>

Expected output:
<add class="user" id-val="user33 user33" >
        <add-value attr="LastName">
            <value type="string">user33</value>
        </add-attr>
        <add-value attr="FirstName">
            <value type="string">user33</value>
        </add-value>
        <add-value attr="Email">
            <value type="string">user33@gamil.com</value>
        </add-value>
        <add-value attr="Description">
            <value type="string">new user</value>
        </add-value>
    </add>

this is the snippet of xslt that i have so far.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:variable name="lessThan" select="'<'"/>
  <xsl:variable name="GreaterThan" select="'>'"/>

  <xsl:template match="user">
    <xsl:variable name="temp1" select="concat(field[@name=$srcdn-field-name1],' ')"/>
    <xsl:variable name="temp2" select="concat($temp1,field[@name=$srcdn-field-name2])"/>
    <xsl:variable name="src" select="translate($temp2,'+=,.\','-----')"/>

    <xsl:value-of disable-output-escaping="yes" select="$lessThan"/>
    <xsl:text>add</xsl:text>
    <xsl:value-of disable-output-escaping="yes" select="$GreaterThan"/>

    <!-- it is required to add attribute id-val to element <add> with value of  $src-->

    <xsl:for-each select="field[string()]">
      <xsl:variable name="fieldValue" select="normalize-space(.)"/>
      <xsl:choose>
        <xsl:when test="@name !='Group Member'">
          <add-value attr="{@name}">
            <value type="string">
              <xsl:value-of select="$fieldValue"/>
            </value>
          </add-value>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of disable-output-escaping="yes" select="$lessThan"/>
          <xsl:text>/add</xsl:text>
          <xsl:value-of disable-output-escaping="yes" select="$GreaterThan"/>

          <!--perform some other operations-->

        </xsl:otherwise>
      </xsl:choose>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Now my requirement is to have id-val and class as  attributes of <add>.. In this context the <xsl:attribute> isn't working. What changes do i need to make to my xslt.?

A: You can't add an attribute to something that's not an element. That's one of the many reasons not to try to manually construct start and end tags. Try this:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="user">
    <xsl:variable name="temp1" select="concat(field[@name=$srcdn-field-name1],' ')"/>
    <xsl:variable name="temp2" select="concat($temp1,field[@name=$srcdn-field-name2])"/>
    <xsl:variable name="src" select="translate($temp2,'+=,.\','-----')"/>

    <add class="user" id-val="{$src}">

      <!-- it is required to add attribute id-val to element <add> with value of  $src-->

      <xsl:for-each select="field[string()]
                              [not((. | preceding-sibling::field)
                                             [@name = 'Group Member'])]">
        <add-value attr="{@name}">
          <value type="string">
            <xsl:value-of select="normalize-space()"/>
          </value>
        </add-value>
      </xsl:for-each>

    </add>
  </xsl:template>
</xsl:stylesheet>


text:
Q: SharePoint Configuration Failed cannot open WordAutionService DB I was installing SharePoint 2010 in Windows 7 , SharePoint Configuration Wizard failed to open DB of WordAutmationService . Can any one help me in knowing what is the issue and why it encountered ,And how can I solve this issue

A: *

*Open SQL Server Management Studio.

*Check that the Database WordAutomationServices_###### exists.

*The error is indicating that the account spadmin\sharepointpc doesn't have enough permissions to complete the installation process.

*Give the spadmin\sharepointpc account more permissions and execute the wizard again.

-Hope it helps.


text:
Q: Fit/Scale image that has graphics/text on it to 100% width/height I have an image that is 1920x1080 in resolution. The image was created by a graphics team, and has a lot of text/graphics on it. I'm not sure if there is a way with CSS and/or JavaScript/jQuery that when the page loads, this image is taking up 100% of the screen at load. The user can then scroll down past it and view the rest of the page's content.
Right now I am trying something like this (using Bootstrap):

        Ciudad de México Marzo 7th o Marzo 8th 2016

It's not working out too well, because as the viewport size starts to approach 1770px, the image starts being vertically taller than the height of the window, therefore causing some of the text within the image to scroll off the page.
I'd like to just have the image fit to the screen size on load (at 100% of the page's height on load). I've tried multiple solutions involving jQuery, and CSS, but none seem to fit these basic requirements. Is it even possible?
Edit: Another attempt here
#hero {
    background-image: url(http://az860851.vo.msecnd.net/release/site/3DScantoPrint_landing_hero.jpg);
    background-size: cover;
    position: relative;
    height: 100vh;
}

<wrapper id="wrapper">

</wrapper>

This solution doesn't fit the image to the screen as it scales down.
Edit 2: jQuery attempt here
#hero{
  background-image:url(http://az860851.vo.msecnd.net/release/site/3DScantoPrint_landing_hero.jpg);
  background-size:cover;
  position:relative;
}

<wrapper id="wrapper">

</wrapper>

$(window).scroll(function (e) {
    handleScroll();
});

function fullscreen() {
    $('#hero').css({
        width: $(window).width(),
        height: $(window).height()
    });
}

fullscreen();

// Run the function in case of window resize
$(window).resize(function () {
    fullscreen();
});

Yields the same results as the CSS version it seems.

A: Does this work for you? ... and by adding a bottom padding it keeps its aspect ratio.

html, body { margin: 0; }

#hero {
    background-image: url(http://az860851.vo.msecnd.net/release/site/3DScantoPrint_landing_hero.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    padding-bottom: 56.25%;    /* 1080 / 1920 = 0.5625 */
}

 Bla bla

 Bla bla

 Bla bla

 Bla bla

 Bla bla

 Bla bla

 Bla bla

Sample 2

html, body { margin: 0; }

.hero {
  height: 100vh;
}

.hero img {
  display: block;
  margin: 0 auto;
  max-height:100%;
  max-width: 100%;
}

A: Try this
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Document</title>

Other

Other

Other

A: I think I have solved you the problem ?
https://jsfiddle.net/Microsmsm/yuf56uv0/

img {
  width:100%;
  height:auto;
}

A: The real answer to this, as the comments have indicated, is that there is no way to do this while maintaining the aspect ratio and readability of the image as the screen size changes.
The solution is to not take a huge image with all of the text/graphics on it and try to use it, and instead to break it up into components, and piece them together on the page using html/css accordingly. That way they can move/shift around as the screen size changes, while still keeping the message clear.


text:
Q: Finding a Conditional Probability
This is the given info:
  $P(A)=2/5$ ,
  $P(A \cup B)=3/5$ ,
  $P(B|A)=1/4$ ,
  $P(C|B)=1/3$ ,
  $P(C|A \cap B)=1/2$ ,
  Find $P(A|B \cap  C)$

I know that $P(A|B \cap C)$ is equivalent to $P(A \cap B \cap C)$ divided by $P(B \cap  C)$.
I was able to calculate $P(A \cap B \cap C)$ by doing $P(A)P(B|A)P(C|A \cap B)$ and I get $1/20$. But I don't know how to calculate $P(B \cap C)$ to calculate $P(A|B \cap C)$. please help.

A: $$P(A) + P(B) = P(A\cap B) + P(A\cup B) = P(A)P(B|A) + P(A\cup B).$$
Thus
$$P(B) = P(A)(P(B|A) - 1) + P(A\cup B).$$
And then
$$ P(B\cap C) = P(B)P(C|B).$$


text:
Q: Writing Pythons Errors to a txt file I am having trouble getting this to work correctly (obviously) - I am ALMOST there, and I have a good idea of WHY it is not working - just not sure how to make it work.
This is suppose to attempt to read a file into memory, if it fails it goes to the "except" clause of the block of code (that part is 'duh').  The error file prints: "<main.DebugOutput instance at 0x04021EB8>".  What I want it to do is print the actual Error.  Like a FileIOError or TraceBackError or whatever it is to that error file.  This is just the beginning stages and I plan to add things like date stamps and to have it append, not write/create - I just need the actual error printed to the file.  Advice?
import os, sys

try:
    myPidFile = "Zeznadata.txt"
    myOpenPID_File = open(myPidFile, "r") #Attempts to open the file
    print "Sucessfully opened the file: \"" + myPidFile + "\"."

except:
    print "This file, \"" + myPidFile + "\", does not exist.  Please check the file name and try again.  "
    myFileErr = open("PIDErrorlog.txt", "w")
    myStdError = str(sys.stderr)
    myFileErr.write(myStdError)
    myFileErr.close()
    print "\nThis error was logged in the file (and stored in the directory): "

A: First, you should use a logging library. It will help you deal with different logging levels (info/warn/error), timestamps and more.
http://docs.python.org/library/logging.html
Second, you need to catch the error, and then you can log details about it. This example comes from the Python documentation.
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())

except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

See how it catches an IOError and assigns the error number and error message to variables? You can have an except block for each type of error you want to deal with. In the last (generic error) block, it uses sys.exc_info()[0] to get the error details.
http://docs.python.org/tutorial/errors.html

A: the problem is here:
 myStdError = str(sys.stderr)
 myFileErr.write(myStdError)

sys.stderr is a file-like interface defined in POSIX standards, called standard error, not "error text" that you can write to a file. So what you (probably) wanted to do is:
sys.stderr = myFileErr

This is the python equivalent to python your_python_sctipt.py 2> PIDErrorLog.txt in unix shell.

A: Use the logging module. The logging module have exception formatters that will help you print exceptions in a pretty way.
http://docs.python.org/library/logging.html

A: Like Kimvais says, your problem is:
myStdError = str(sys.stderr)
myFileErr.write(myStdError)

sys.stderr is a file handle to stderr (stdout is what print writes to).
You should do something like:
try:
    ...open file...
except IOError as (errno, strerror):
    ...open errfile...
    errfile.write(strerror)
    errfile.close()

Alison's answer is also very good and well written.


text:
Q: Visual Studio Solution Structure for multiple deployable projects Scenario:
Currently we have a single solution supporting a single deployable entity, a WinForm/WPF client, this solution has a layer architecture with projects representing various layers (Data, Business, UI). We will be introducing other deployable entities such as a LiteClient, a Server and an RIA.
We are considering a restructure where we will have multiple solutions, one per deployable entity (Client Solution, Server Solution, RIA Solution etc), these solutions will share various projects, e.g the Data layer project. This is essentially the Partitioned Single Solution recommended by Microsoft's P&P group (http://msdn.microsoft.com/en-us/library/Ee817674(pandp.10).aspx)
Question:
Apart from the admin overhead of this approach, is there any serious real world gothas waiting for us, if we adopt it.

A: This is a reasonable and normal approach.  At the end of the day, the Visual Studio solution is simply a collection of projects with deployment information.
In order to reduce possible dependency issues, make sure you use a build server (TFS or otherwise) that takes care of compiling and deployments.

A: If you change something within the shared projects, you have to check if that didn't break the dependent projects. If you keep those projects in seperate solutions you have to remember to recompile them each time you modify the shared projects.
That's a drawback that I can see.


text:
Q: Eliminar nodo hoja de un árbol binario Ayuda necesito eliminar un nodo hoja de un árbol binario
public function EliminarNodo($n,$dato){
   if($this->root !=null){
     if($n->getLeft() == null && $n->getRight()==null){
       if($n->getValor()==$dato){
         $n=null;
       }
     }else{
       $i=$this->EliminarNodo($n->getLeft(),$dato);
       if($i!= null){
         return $i;
       }else{
         $s=$this->MostrarHojas($n->getRight(),$dato);
         return $s;
       }
     }
   }
}

A: ¡Ey, Que tal amigo!
Acá tengo una clase con diferentes métodos para un Arbol de forma recursiva en Java, también esta el que necesitas. ¡Espero te sirva, Saludos!
public class Main {

    Arbol arbol;

    public Main(){
        arbol = null;
    }

    public void insertar(int valor) {
        arbol = insertarValor(arbol, valor);
    }

    public Arbol insertarValor(Arbol raizA, int valor) {

        if (raizA == null) {
            raizA = new Arbol(valor);
            System.out.println("Raiz " + raizA.getValor());
            return raizA;
        }

        if (valor < raizA.getValor()){
            System.out.println(" por la izquierda ");
            raizA.izq = insertarValor(raizA.getIzq(), valor);

        }else if (valor > raizA.getValor()){
            System.out.println("por la derecha");
            raizA.der = insertarValor(raizA.der, valor);
        }

        return raizA;
    }

    public Arbol eliminar(int valor){
        arbol = eliminarValor(arbol, valor);
        return arbol;
    }

    public Arbol eliminarValor(Arbol raizA, int valor){
        if (raizA == null){
            System.out.println("No se encuentra el valor " + valor + " en el arbol.");
            return raizA;
        }

        if(valor==raizA.valor){
            if (raizA.izq == null){
                System.out.println("Eliminado ");
                return raizA.der;
            }else if (raizA.der == null){
                System.out.println("Eliminado ");
                return raizA.izq;
            }

        }

        if (valor < raizA.valor){
            raizA.izq = eliminarValor(raizA.izq, valor);
        }else if (valor > raizA.valor){
            raizA.der= eliminarValor(raizA.der, valor);
        }

        return raizA;
    }

    public Arbol buscarValor(Arbol raizA, int valor){

        if (raizA==null){
            System.out.println("El valor " + valor + " no se encontró");
            return raizA;
        }

        if(raizA.valor==valor){
            System.out.println("El valor " + valor + " se encontró");
            return raizA;
        }

        if (raizA.valor > valor){
                System.out.println("El valor " + valor + " esta por el lado izquierdo de la raiz " + raizA.valor);
                return buscarValor(raizA.izq, valor);
        }else if(raizA.valor < valor){
                System.out.println("El valor " + valor + " esta por el lado derecho de la raiz " + raizA.valor);
                return buscarValor(raizA.der,valor);
        }
        return null;

    }

    public static void main(String []args){
        Main ar = new Main();

        ar.insertar(5);
        ar.insertar(10);
        ar.insertar(20);
        ar.insertar(15);
        ar.insertar(30);
        ar.insertar(3);
        ar.insertar(100);

        ar.eliminar(3);
        ar.eliminar(100);
        ar.eliminar(100);

        ar.buscarValor(ar.arbol,30);

    }

}


text:
Q: Arel: active relation from Arel::SelectManager with join Let us we have a Rails 4.2.x app and we have two tables posts and authors, and we want to use Arel to get the posts authored by an author with name == 'Karl'.
(In this case we could be happy with Active Record joins but this is just to keep the example simple.)
posts = Arel::Table.new :posts
authors = Arel::Table.new :authors

my_query = posts.project(Arel.star)
                .join(authors)
                .on(posts[:author_id].eq(authors[:id]))
                .where(authors[:name].eq('Karl'))

> my_query.class
=> Arel::SelectManager

Now we could get back an array (of class Array) of posts by doing:
> Post.find_by_sql my_query
[master]  Post Load (3.1ms)  SELECT * FROM "posts" INNER JOIN "authors"
                             ON "posts"."author_id" = "authors"."id"
                             WHERE "authors"."name" = 'Karl'

=> [#<Post:0x005612815ebdf8
    id: 7474,
    ...
   ]

So we do get an array of posts, not an active record relation:
 > Post.find_by_sql(my_query).class
 => Array

Also injecting the manager into Post.where won't work
> Post.where my_query
=> #<Post::ActiveRecord_Relation:0x2b13cdc957bc>
> Post.where(my_query).first
ActiveRecord::StatementInvalid: PG::SyntaxError:
ERROR:  subquery must return only one column
SELECT  "posts".* FROM "posts"
WHERE ((SELECT * FROM "posts" INNER JOIN "authors" ON "posts"."author_id" = "authors"."id" WHERE "authors"."name" = 'Karel'))
ORDER BY "posts"."id" ASC LIMIT 1

I am thinking I must be missing something. In short: how do you get an active record relation from a select manager like my_query above (or another select manager accomplishing the same thing).

A: You can't get ActiveRecord::Relation from Arel::SelectManager neither from sql string. You have two ways to load data through ActiveRecord:

*

*Do all query logic in Arel. In this case you can't use any of ActiveRecord::Relation methods. But you have same functionality in Arel. In your example you may set limit through Arel:
my_query.take(10)

*Other way is to use Arel in ActiveRecord::Relation methods. You may rewrite your query like this:
posts = Arel::Table.new :posts
authors = Arel::Table.new :authors

join = posts.join(authors).
          on(posts[:author_id].eq(authors[:id])).
          join_sources

my_query = Post.
              joins(join).
              where(authors[:name].eq('Karl'))

> my_query.class
=> ActiveRecord::Relation

In this case you may use my_query as ActiveRecord::Relation


text:
Q: How to properly import MomentJS in Typescript to resolve the following error: "Type 'typeof moment' has no compatible call signatures." Importing MomentJS is causing the following error:
ERROR in [...] Cannot invoke an expression whose type lacks a call signature. Type 'typeof moment' has no compatible call signatures.

How can I resolve this error?

A: The latest version of MomentJS now has defined types. Reinstall MomentJS without external typings. You should also avoid namespace-style import as such imports cannot be called or constructed and would cause a failure at runtime.
The way to go is traditional import:
import moment from 'moment';


text:
Q: Yup. How to change error message text date How to change message text for date field:

date must be a date type, but the final value was: Invalid Date

Now scheema looks like this:
let scheema= yup.object().shape({
        date: yup.date()
          .min(MIN_DATE, `Дата не может быть раньше ${MIN_DATE?.toLocaleDateString('ru')}`)
          .max(MAX_DATE, `Дата не может быть позже ${MAX_DATE?.toLocaleDateString('ru')}`)
          .required('Обязательное поле'),
        reason: yup.string().required('Обязательное поле'),
        comment: yup.string().max(4000, 'Превышено количество символов'),
    });

error is:
{
    "date": "date must be a `date` type, but the final value was: `Invalid Date`."
}

I need to change this text

A: You could use Schema.typeError as follows:
date: yup.date()
        .typeError('Expected a value of type ${type} but got: ${value}') // ex: Expected a value of type date but got: Invalid Date
        .min(MIN_DATE, `Дата не может быть раньше ${MIN_DATE?.toLocaleDateString('ru')}`)
        .max(MAX_DATE, `Дата не может быть позже ${MAX_DATE?.toLocaleDateString('ru')}`)
        .required('Обязательное поле'),
reason: yup.string().required('Обязательное поле'),
comment: yup.string().max(4000, 'Превышено количество символов'),


text:
Q: selecting another dropdown option with jquery I'm having difficulty selecting another dropdown option by option value="X" .. how can I do this?
<select id="type">
    <option value="all">All Types</option>
    <option value="1">Comments</option>
    <option value="2">Meanings</option>
    <option value="3">Thoughts</option>
</select>

It works if I do the code below, but because I usually put the total amount of types (so Comments 13, Meanings 6, etc) so the numbers are always changing from one form to another.
$("#type").val('Comments');

But how do I select it based on value="X" or value="all"

A: You are confusing option text with value
 $("#type").val(1);// will select option with text="Comments"

If you want to get the text and convert to selected
$('#type option').filter(function(){
     return $(this).text()=="Comments";

}).prop('selected',true)

A: jQuery('#type option:contains("Comments")').prop('selected', true);

EDIT: After looking at this, if you use the following, you can pick based on value or option text: the following will both pick the second item in your list: with option value of 1 and text of Comments - with any suffex/other text in the Comments suchs as "Comments 33" still being supported.
var checkMe = '1';
$('#typePick option:contains("'+checkMe+'"), #typePick option:[value="'+checkMe+'"]').prop('selected',true);

By Text:
 var checkMe = 'Comments';
 $('#typePick option:contains("'+checkMe+'"), #typePick option:[value="'+checkMe+'"]').prop('selected',true);

And the distinct one: for <option value="1">Comments 33</option>
 var checkMe = 'Comments 33';
 $('#typePick option:contains("'+checkMe+'"), #typePick option:[value="'+checkMe+'"]').prop('selected',true);

NOTE: the only difference in the last three examples is the value assigned to checkMe.
See here for working example: http://jsfiddle.net/a7SQT/1/

A: You're close--just call val() with the value of the option:
var value="2";
$("#type").val(value)

fiddle here

A: http://api.jquery.com/val/ always take/gives the data of the value attribute.
Try http://jsfiddle.net/rKMmg/

A: If you want to get the value based off the text, you can use :contains:
$('#type option:contains(Comments)').val();

Otherwise, if you want to set the value you can use the same selector and set the selected property:
$('#type option:contains(Comments)').prop('selected', true);


text: Q: X11 how to simulate two screens in only one monitor how will configure for preference in /etc/xorg.conf a monitor configuration with 2 screen simulate only in one monitor, in a gnu+linux OS, split by a middle vertical for example, thanks for your help...


text:
Q: I need to tockenize string of a java code to its blocks import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Client {
public static void main(String[] args) throws IOException {
    DatagramSocket socket = new DatagramSocket();
    socket.connect(new InetSocketAddress(5000));
    byte[] message = "Oh Hai!".getBytes();
    DatagramPacket packet = new DatagramPacket(message, message.length);
    socket.send(packet);
  }
}

I have this code as a string and I need to get its methods statements loops for separate arrays
Can any body suggest a solution

A: You can use the StreamTokenizer to analyze a stream (e.g. StringReader).
Here you are an example:
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;

public class Test {
    public static void main(String[] args){
        StreamTokenizer tokenizer = new StreamTokenizer(new StringReader("public static void main(String[] args){"));

        tokenizer.parseNumbers();

        tokenizer.wordChars('_', '_');

        tokenizer.eolIsSignificant(true);
        tokenizer.ordinaryChars(0, ' ');
        tokenizer.slashSlashComments(true);
        tokenizer.slashStarComments(true);

        int token;

        try {
            while( (token = tokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
                if(token == StreamTokenizer.TT_WORD) {
                    System.out.println(tokenizer.sval);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            // Please handle this exception
        }
    }
}

This generates the following output:
public
static
void
main
String
args

Please have a look at this for further details:
https://docs.oracle.com/javase/7/docs/api/java/io/StreamTokenizer.html


text:
Q: reload page when hash change using history.back / forward I am sending/receiving values on the same page using hashtag. Every time I change the hash values I manually reload the page after pressing a button and assigning values. For example
<input type="button" value="go to step 2" onclick="reloadpage();"

function reloadpage() {

window.location.hash = "val1:xxx,val2:yyy,val3:zzz";
window.location.reload();

}
if the user press the browser back or forward buttons, the url hash changes but the page not reloads. Is there any way to detect if history.change and refresh the page?

A: At the end I used the jQuery hashchange event.
It enables very basic bookmarkable #hash history via a cross-browser HTML5 window.onhashchange event.
Link to the page with the source

A: Use modern day html5 pushState.


text:
Q: http post not getting input into action field I have a HTTP Post form that receives info from AngularJS (that takes it from the PHP BE).
I use the following code sample:
<form method="post" action="{{aw('TI.sup');}}">
<input type='hidden' name='bla' value="{{aw('TI.sup');}}" />
<input type="submit" class="button s-button"  value="bla" />
</form>

After page is loaded, I see the following result:
<form method="post" class="ng-pristine ng-valid">
<input type="hidden" name="bla" value="https://thisis.the/url">

Strings without 'https:' work fine.
Update
The problem was with $sce, and has slightly changed after I Added a function to the controller.
now I'm getting:
<form method="post" action="https://thisis.the/url" class="ng-pristine ng-valid">

Update, take 2
The form won't respond to submit because the previous URL was blank (before Angular changed it). I decided to take the info from PHP itself, but the following jquery will also do the trick:
$("#FormID").submit();

Thanks,
Dana.

A: You are facing a  $sce:insecurl error , probably because the action URL is from other domain/protocol.
From  $sce:insecurl error docs:

Processing of a Resource from Untrusted Source Blocked
...
To load templates from other domains and/or protocols, either adjust the whitelist/ blacklist or wrap the URL with a call to $sce.trustAsResourceUrl.

Here is an an example: http://jsbin.com/disef/2/edit
function ctrl($scope, $sce){
  $scope.aw = function() {
    return $sce.trustAsResourceUrl("https://thisis.the/url");
  }
};


text:
Q: How to get the best model when using EarlyStopping callback in Keras? I am training a neural network with Keras using EarlyStopping based on val_acc and patience=0. EarlyStopping stops the training as soon as val_acc decreases.
However the final model that I obtain is not the best model, namely the one with the highest val_acc. But I rather have the model corresponding to the epoch after, namely the one corresponding to a val_acc just a bit lower than the best one and that caused the early stopping!
How do I get the best one?
I tried to use the save the best model using the call back:
ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]

But I get the same results.

A: If you would like to save the highest accuracy then you should set the checkpoint monitor='val_acc' it will automatically save on highest. Lowest loss might not necessarily correspond to highest accuracy. You can also set verbose=1 to see which model is being saved and why.

A: In Keras 2.2.3, a new argument called restore_best_weights have been introduced for EarlyStopping callback that if set to True (defaults to False), it would restore the weights from the epoch with the best monitored quantity:

restore_best_weights: whether to restore model weights from the epoch with the best value of the monitored quantity. If False, the
model weights obtained at the last step of training are used.


text:
Q: Extreact List with redux state and local store I'm using Redux for state management in this extreact powered app that I started and I'm at a component (List) that needs data from the redux store. The List component needs a store parameter that I know how to create but I don't know how to couple it with the redux store.
I found an example from Sencha blog but it's lacking exactly at the part that I'm interested in:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Grid } from '@extjs/ext-react';
import { connect } from 'react-redux';

export default class EmployeesGrid extends Component {

    static propTypes = {
        criteria: PropTypes.object
    };

    store = new Ext.data.Store({
        ...
    });

    componentDidUpdate(prevProps) {
        const { criteria } = this.props;

        if (prevProps.criteria !== criteria) {
            const filters = [];

            for (let name in criteria) {
                filters.push({
                    property: name,
                    value: criteria[name]
                })
            }

            this.store.filter(filters)
        }
    }

    render() {
        return (
            <Grid
                store={this.store}
                ...
            />
        )
    }
}

const mapStateToProps = (state) => {
    return { criteria: state.criteria }
};

export default connect(mapStateToProps)(EmployeesGrid);

How does the Ext.data.Store gets the items and how are those items updated on componentDidUpdate for example?

A: DISCLAIMER: I am an ExtJs developer and also a React/Redux developer, but did not try it together yet.
I think your example comes from this article
You post the Option 2 example, where they are writing that data are not stored in redux, only the filtering criteria for the ExtJs Grid. The data are handled out of React/Redux within ExtJs Store, you need to use their API for data (re)loading.


text:
Q: How can I convert a PNG or JPEG image to an Icon using C#? I would like to know if it is possible to convert a PNG or JPEG image file to an Icon file (.ico) by using C#. So far the code I am trying to use has failed me. After converting the file, the converted Icon file is corrupted while trying to use it in other softwares that are compatible with Icon (.ico) files. Or when I try to view it in Windows Photo Gallery, it is corrupted. I don't know what I am doing wrong but here is my code:
    private void btnConvert_Click(object sender, EventArgs e)
    {
        Bitmap Cbitmap = null;
        try
        {
            Cbitmap = new Bitmap(@"C:\Users\Landon\Pictures\image.png"); //(32, 32, PixelFormat.Format64bppPArgb);
        }
        catch(Exception)
        {
            MessageBox.Show("Error opening given Image file", "File Error",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return;
        }
        Cbitmap.MakeTransparent(Color.Transparent);
        System.IntPtr icH = Cbitmap.GetHicon();
        Icon ico = Icon.FromHandle(icH);
        Cbitmap.Dispose();
        System.IO.FileStream f = new System.IO.FileStream(@"C:\Users\Landon\Pictures\" + "\\image.ico", System.IO.FileMode.OpenOrCreate);
        ico.Save(f);
        MessageBox.Show("Image is converted to ICON and saved in the directory: " + @"C:\Users\Landon\Pictures\" + " with name image.ico");
    }

If for some reason I am unclear in what I am trying to ask let me know and I will edit my question. For now I have honestly tried my best. All comments are appreciated.


text:
Q: how to temporarily remove some changes from a git master branch? So for my first webapp I tried to develop all or a lot of the components at once and have succeeded implementing things I didn't think were possible. However, during the deploy process, I need to start releasing these little by little and thus a lot of code that I have committed to master shouldn't really be there until a later date. I would need to remove it for now, and add it in back later.
How can I trim my codebase so that it only has the code I need for now, and keep all that committed code somewhere I go back and add it in with a git merge later? (Instead of having the git merge delete those things I deleted from master)
I will probably need to do this multiple times.
(Probably shouldn't have done it this way, but shit happens when you learn to develop by yourself without guidance.)

A: you can checkout a commit, by doing
git checkout hash

where hash is a hash string shown by git log. Once you're finished, use
git checkout master

In general, you should have a stable branch, into which you merge features for release.

A: Option 1: Choose versions by hand
(as per hannes' answer). The downside of this is that there's no record in git afterwards, of which commits were released

Option 2: Tag versions
Tagging releases is good practise anyway!
Same as option 1 but you tag the checked-out commit with git tag -am'first release' v1.0 (or whatever). This way, you have a record of which commits were released.

Option 3: Fake release history
You can create a release branch from your first commit, and then use git merge --no-ff to merge each blessed commit (as per options 1 & 2) onto the release branch. I'd still tag them, but this provides something like a fake development history. If no-one else has cloned your repo, you can reset master to your complete release branch at the end, if you want the structure but not the separate branch.


text:
Q: T-SQL to check and update Getting error:
Msg 512, Level 16, State 1, Line 48
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Msg 512, Level 16, State 1, Line 87
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Need to check each record in the table and update a table if there is no records = to 0,00. Then update an existing table with current values. I want to be able to track current data and compare with old data.
DECLARE @LocTime DATETIME;
DECLARE @MinDateTime DATETIME;
DECLARE @SystemDateTime DATETIME;
DECLARE @LIR MONEY;
DECLARE @LOAR MONEY;
SELECT @SystemDateTime = SYSDATETIME(); --= '2016-12-07 23:30:00'
SELECT @MinDateTime = DATEADD(mi,-30,@SystemDateTime)   --go back half hour of reads, job is running every 10 minutes for overlap

--select  @MinDateTime, @SystemDateTime

IF OBJECT_ID(N'tempdb..##LastOver2') IS NOT NULL
BEGIN
    DROP TABLE ##LastOver2
END

--make temp table to hold found data
CREATE TABLE ##LastOver2 (ReadDate DATETIME
, FacilityName NVARCHAR(100)
, FacilityID UNIQUEIDENTIFIER
, LastInstantRead MONEY
, LastOverAllRead MONEY
, FacilityTimeZone INT
, FacilityTime DATETIME)

INSERT INTO ##LastOver2 (ReadDate, FacilityName
, FacilityID, LastInstantRead
, LastOverAllRead
, FacilityTimeZone, FacilityTime)
SELECT DISTINCT --why distinct?
fmr.ReadDate, f.Name
, f.FacilityID, fm.LastInstantRead
, fm.LastOverAllRead
, f.Timezone
, @LocTime
FROM [dbo].[Facilities] f WITH (NOLOCK)
JOIN [dbo].[FacilityMeters] fm WITH (NOLOCK)
ON F.FacilityID = FM.FacilityID
JOIN FacilityMeterReadings fmr WITH (NOLOCK)
ON FM.FacilityMeterID = FMR.FacilityMeterID
WHERE  --fm.FacilityMeterID = '9268d1af-cc29-432c-9cdb-06c158180d2f'
(fmr.ReadDate >= @MinDateTime and ReadDate <= @SystemDateTime) --including on both side to continue with overlap
and (fm.IsVirtual = 0 and fm.ParentMeterID is NULL)
--and (fm.LastInstantRead = 0.00 and fm.LastOverAllRead = 0.00)
AND f.SuppressMonitoring = 0
select * from ##LastOver2

IF (select LastInstantRead from ##LastOver2) = 0.00 OR (SELECT LastOverAllRead FROM ##LastOver2) = 0.00
    BEGIN
            --UPDATE dbo.Facilities
            --SET SuppressMonitoring = 1
            --  FROM dbo.Facilities F
            --  JOIN ##LastOver L
            --  ON F.FacilityID = l.FacilityID
            --  WHERE F.FacilityID = l.FacilityID

            DECLARE @body_content NVARCHAR(150);
            DECLARE @StartHour NVARCHAR(8) = '08:30:00' ;
            DECLARE @StopHour NVARCHAR(8) = '16:00:00';
            --why distinct, is it already distinct. Is is supposed to distinct the facility or meter?
            DECLARE @SQLScript NVARCHAR(200) = 'SELECT distinct * FROM ##LastOver2 WHERE CONVERT(TIME, FacilityTime) BETWEEN '
                        + CHAR(39) + @StartHour + CHAR(39)  +' AND ' + CHAR(39) + @StopHour + CHAR(39);
                        --only looking for reads during day hours? shouldn't use between.

            DECLARE @copyRecipients NVARCHAR(100)

            SET @body_content = 'Please check the attached file. This was from server: ' + @@SERVERNAME

            DECLARE @fileName nvarchar(255);
            select @fileName = 'BadReading_' + replace(replace(convert(nvarchar(19),getdate(), 126),':',''),'-','') + '.txt';
            EXEC msdb.dbo.sp_send_dbmail
            @profile_name = 'SQLSupport'
            ,@recipients = 'Btest@test.com'
            --, @recipients = 'jira@cleanenergycollective.atlassian.net'
            --, @copy_recipients= @copyRecipients
            --, @copy_recipients= 'Bill.Lugaila@easycleanenergy.com;yvonne.lewis@easycleanenergy.com;don.munroe@easycleanenergy.com;Justin.Reed@easycleanenergy.com'
            , @query = @SQLScript
            , @subject = 'Facility Meter Check and Updating table'  --change so easier to see in emails
            , @body= @body_content
            , @importance= 'High'
            , @attach_query_result_as_file = 1
            , @query_attachment_filename = @fileName ;

            --select @SQLScript
    END
ELSE IF (select LastInstantRead from ##LastOver2) != 0.00 OR (SELECT LastOverAllRead FROM ##LastOver2) != 0.00
    BEGIN
        UPDATE [dbo].[_LastInstant_OverAll_Read]
        SET     [FacilityName] = lo.FacilityName,
                [LastInstantRead] = lo.LastInstantRead,
                [LastOverAllRead]= lo.LastOverAllRead,
                [Time_Date] = (SELECT CONVERT(DateTime, SysDateTime()))
        FROM ##LastOver2 lo
        WHERE  lo.FacilityName = [dbo].[_LastInstant_OverAll_Read].FacilityName
        AND lo.LastInstantRead != [dbo].[_LastInstant_OverAll_Read].LastInstantRead
        AND lo.LastOverAllRead != [dbo].[_LastInstant_OverAll_Read].LastOverAllRead
    END

A: the following could be returning multiple rows:
.
.
.
IF
(
    SELECT LastInstantRead
    FROM ##LastOver2
) = 0.00
OR
(
    SELECT LastOverAllRead
    FROM ##LastOver2
) = 0.00

.
.
.

IF
(
    SELECT LastInstantRead
    FROM ##LastOver2
) != 0.00
OR
(
    SELECT LastOverAllRead
    FROM ##LastOver2
) != 0.00

if you are expecting them to return only 1 row then you will need to fix the issue with the following query:
SELECT DISTINCT --why distinct?
              fmr.ReadDate,
              f.Name,
              f.FacilityID,
              fm.LastInstantRead,
              fm.LastOverAllRead,
              f.Timezone,
              @LocTime
       FROM [dbo].[Facilities] f WITH (NOLOCK)
            JOIN [dbo].[FacilityMeters] fm WITH (NOLOCK) ON F.FacilityID = FM.FacilityID
            JOIN FacilityMeterReadings fmr WITH (NOLOCK) ON FM.FacilityMeterID = FMR.FacilityMeterID
       WHERE  --fm.FacilityMeterID = '9268d1af-cc29-432c-9cdb-06c158180d2f'
       (fmr.ReadDate >= @MinDateTime
        AND ReadDate <= @SystemDateTime) --including on both side to continue with overlap
       AND (fm.IsVirtual = 0
            AND fm.ParentMeterID IS NULL)
       --and (fm.LastInstantRead = 0.00 and fm.LastOverAllRead = 0.00)
       AND f.SuppressMonitoring = 0;


text:
Q: Help with ASP.NET ObjectDataSource I have a User object with a Load method that takes in a UserId parameter and loads that users data to the objects member variables.
Now what I'd like to do is load this data to a DetailsView control using an ObjectDataSource, but I'm stumped as to how.
First of all, I'm not sure I've got the code set up properly to pass the parameter (UserID) to the SelectMethod (cUser.Load). Secondly, I don't know how I can load this data to the DetailsView since I'm not actually returning the results from the Load method, I'm simply loading the object with the data...here's my code..
<asp:GridView runat="server" ID="gvUsers" DataKeyNames="UserID" BackColor="#eeeeee"     Width="85%"
                    HorizontalAlign="Center"
                    Font-Bold="True" Font-Names="Verdana"
                    Font-Size="10pt" AutoGenerateColumns="False"
                    OnRowDataBound="GridView1_RowDataBound"
                    OnRowDeleting="GridView1_RowDeleting"
                    OnSelectedIndexChanged="IndexChanged" >
            <HeaderStyle BackColor="Black" ForeColor="White"
                   Font-Bold="True" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="yellow" ForeColor="blue" />
            <AlternatingRowStyle BackColor="#ffffff" />
                   <Columns>
                         <asp:TemplateField>
                       <ItemTemplate>
                           <asp:LinkButton ID="LinkButton2"
                             CommandArgument='<%# Eval("UserID") %>'
                             CommandName="Select" runat="server">
                             Select</asp:LinkButton>
                         </ItemTemplate>
                         </asp:TemplateField>
                        <asp:BoundField DataField="UserID" Visible="false" />
                        <asp:BoundField DataField="FirstName" HeaderText="First Name"     />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                        <asp:TemplateField HeaderText="Delete?">
                         <ItemTemplate>
                           <asp:LinkButton ID="LinkButton1"
                             CommandArgument='<%# Eval("UserID") %>'
                             CommandName="Delete" runat="server">
                             Delete</asp:LinkButton>
                         </ItemTemplate>
                       </asp:TemplateField>
                    </Columns>
              </asp:GridView>

              <asp:DetailsView runat="server" ID="dvUser"     DataSourceID="ObjectDataSource1" AutoGenerateRows="False" Width="85%"
                    HorizontalAlign="Center" DataKeyNames="UserID" >
                  <Fields>
                    <asp:BoundField DataField="UserID" Visible="false" />
                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                    <asp:BoundField DataField="UserName" HeaderText="User Name" />
                    <asp:BoundField DataField="Password" HeaderText="Password" />
                    <asp:BoundField DataField="Birthdate" HeaderText="Birthdate" />
                    <asp:BoundField DataField="Address" HeaderText="Address" />
                    <asp:BoundField DataField="Apt" HeaderText="Apt" />
                    <asp:BoundField DataField="City" HeaderText="City" />
                    <asp:BoundField DataField="Province" HeaderText="Province" />
                    <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
                    <asp:BoundField DataField="PhoneNum" HeaderText="PhoneNum" />
                    <asp:BoundField DataField="Email" HeaderText="Email" />
                    <asp:BoundField DataField="ynAdminUser" HeaderText="ynAdminUser" />
                    <asp:CommandField ShowDeleteButton="False" ShowEditButton="True"     ShowInsertButton="True" />
>
                </Fields>
            </asp:DetailsView>
                <asp:ObjectDataSource ID="ObjectDataSource1"
                    runat="server" SelectMethod="Load" TypeName="cUser">
                    <SelectParameters>
                        <asp:ControlParameter ControlID="gvUsers" PropertyName="SelectedValue" Name="iUserID" Type="int32" />
                    </SelectParameters>
                </asp:ObjectDataSource>

is there a way to do what I'm trying to achieve?  if so, can you please give examples with the explanation?
Very much appreciated.  Thanks

A: you need to check this tutorial for detail help....
Master/Detail Using a Selectable Master GridView with a Details DetailView


text:
Q: change the row background-image width without effecting the max width of the row its like this  it needs to be like this I am trying to change the background-image width without affecting the max width of the whole row.
i have tried different size properties but the max width of the row is 80% i only need the background-image with a max width of 100%.
this the selector/rule for the row:
.et_pb_row {

    position: relative;
    width: 80%;
    max-width: 1920px;
    margin: auto;

}

and this the selector/rule for the background-image of the row:
.et_pb_row_0 {

    background-size: contain;
    background-position: top right;
    background-image: url(http://fordent.uk.w3pcloud.com/wp-content/uploads/2019/01/GettyImages-532174359.jpg);

}

A: Here check the link
 here i have set position relative to body in your case that could be the parent div of .et_pb_row to which you have given width: 80%; and setting a pseudo element to that ::after in that i have provided background-image
Hope this helps.


text:
Q: python - entry.focus_set() not working in tkinter I have an entry, a listbox(dropdown) and another listbox. Whenever more than 3 characters are typed inside the entry. A completion list is looked up and inserted to the dropdown and the dropdown is shown. If an item is selected from the dropdown. It's value should be inserted to the listbox and removed from the dropdown and the entry should get the focus again. But it doesn't.
Here is my code:
from tkinter import *

class Autocomplete(Frame, object):
    def __init__(self, *args, **kwargs):
        super(Autocomplete, self).__init__(*args, **kwargs)
        self.text = StringVar()
        self.entry = Entry(self, textvariable=self.text)
        self.frame = Frame(self)
        self.listbox = Listbox(self.frame)
        self.dropdown = Listbox(self.frame)

    def build(self):
        self.text.trace("w", lambda name, index, mode: self._update_dropdown())
        self.entry.focus_set()
        self.entry.pack()
        self.frame.pack()
        self.listbox.grid(column=0, row=0, sticky=N)
        self.dropdown.bind("<<ListboxSelect>>", lambda event: self._select_entry())
        self.dropdown.grid(column=0, row=0, sticky=N)
        self.dropdown.grid_forget()
        return self

    def _shorten_dropdown(self, index):
        self.dropdown.grid_forget()
        self.dropdown.delete(index)
        self.dropdown["height"] -= 1
        self.dropdown.selection_clear(0, END)
        self.dropdown.grid(column=0, row=0, sticky=N)

    def _select_entry(self):
        index = int(self.dropdown.curselection()[0])
        value = self.dropdown.get(index)
        self._shorten_dropdown(index)
        self.entry.focus_set()

This was the minimal code. Here is the testable version. And Here is the code to build an instance of autocompelete:
from tkinter import *
from autocomplete import Autocomplete

listt = ["a","aa","aaa","ab","bba","aba","abbnb","cd","c","abc","abcd"]
root = Tk()

autocomplete_frame = Autocomplete(
    60,
    10,
    listt
).build()
autocomplete_frame.pack()

mainloop()

A: So a few things I had to change to get this to work for at least one word. Currently it will not work if you wish to continue typing out more words in a continuous string.
I am sure I can eventually get that to work as well but I am trying to answer the problem of updating a word from the list box and getting focus back to the entry field.
I had to change a couple things.
First I had to change:
index = int(self.dropdown.curselection()[0])

To:
index = self.dropdown.curselection()[0]

as the returned value of self.dropdown.curselection()[0] is already an int. It not needed to make the integer an integer again.
Second I had to change:
def _add_course(self, value):
    self.listbox.insert(END, value)
    self.my_list.append(value)

To:
def _add_course(self, value):
    self.entry.delete(0,END)
    self.entry.insert(END, value)
    self.my_list.append(value)

As you were trying to insert a the value into a listbox not the entry field. Also note I changed self.list to self.my_list`. You should avoid naming things that might overwrite built in functions.
The last thing I needed to change was how we were setting the focus back to the entry field. I believe the problem with the focus is the fact that you are setting a focus on mouse click however you are still clicking on the list box and that is taking focus. We need to add a delay to the focus set so that we have time to finish out mouse click before the focus is set to the entry field.
Change:
self.entry.focus_set()

to:
self.master.after(200, lambda: self.entry.focus())

An alternative to setting the focus back to the entry field would be to bind() the button release event to the focus command instead.
You can force focus like this as well:
self.dropdown.bind("<ButtonRelease-1>", lambda x: self.entry.focus())

The below code should work for your main problem:
from tkinter import *

class Autocomplete(Frame, object):
    def __init__(self, width, height, entries, *args, **kwargs):
        super(Autocomplete, self).__init__(*args, **kwargs)
        self.my_list = []
        self._entries = entries
        self.listbox_height = height
        self.entry_width = width
        self.text = StringVar()
        self.entry = Entry(self, textvariable=self.text, width=self.entry_width)
        self.frame = Frame(self)
        self.listbox = Listbox(self.frame, height=self.listbox_height, width=self.entry_width)
        self.dropdown = Listbox(self.frame, height=self.listbox_height, width=self.entry_width, background="#cfeff9")

    def build(self):
        self.text.trace("w", lambda name, index, mode: self._update_dropdown())
        self.entry.focus_set()
        self.entry.pack()
        self.frame.pack()
        self.listbox.grid(column=0, row=0, sticky=N)
        self.dropdown.bind("<<ListboxSelect>>", lambda event: self._select_entry())
        self.dropdown.grid(column=0, row=0, sticky=N)
        self.dropdown.grid_forget()
        return self

    def _update_dropdown(self):
        self.dropdown["height"] = self.listbox_height
        self.dropdown.delete(0, END)
        text = self.text.get()
        print("update: " + text)
        if len(text) < 3:
            self.dropdown.grid_forget()
            return
        else:
            for entry in self._entries:
                if entry not in self.my_list and text.lower() in entry.lower():
                    self.dropdown.insert(END, entry)
        listbox_size = self.dropdown.size()
        if not listbox_size:
            self.dropdown.insert(END, "No results found for '{}'".format(text))
            self.dropdown["height"] = 1
        else:
            if listbox_size <= self.dropdown["height"]:
                self.dropdown["height"] = listbox_size
        self.dropdown.grid(column=0, row=0, sticky=N)

    def _shorten_dropdown(self, index):
        print("shorten: {}".format(str(index)))
        self.dropdown.grid_forget()
        self.dropdown.delete(index)
        if self.dropdown["height"] == 1:
            self.dropdown.insert(END, "No more results found for '{}'".format(self.text.get()))
        else:
            self.dropdown["height"] -= 1
        self.dropdown.selection_clear(0, END)
        self.dropdown.grid(column=0, row=0, sticky=N)

    def _select_entry(self):
        index = self.dropdown.curselection()[0]
        value = self.dropdown.get(index)
        print(value)
        if "results found for" in value:
            print("return")
            return
        print("select: {}".format(value))
        self._shorten_dropdown(index)
        self._add_course(value)
        self.master.after(200, lambda: self.entry.focus())

    def _add_course(self, value):
        self.entry.delete(0,END)
        self.entry.insert(END, value)
        self.my_list.append(value)

listt = ["a","aa","aaa","ab","bba","aba","abbnb","cd","c","abc","abcd"]
root = Tk()

autocomplete_frame = Autocomplete(60, 10, listt).build()
autocomplete_frame.pack()

mainloop()


text:
Q: Python Unicode and \xe2\x80\x98r\xe2\x80\x99 error
Python version 3.5.2

So I have file output from mitmproxy called enter code here, and I want to read it using:
from shelljob import proc

g = proc.Group()
command = "tail -f -c +0 output_file | mitmdump -n -r - --set flow_detail=1 --showhost"
p = g.run (command)

def read_process():
    while g.is_pending():
        lines = g.readlines()
        for proc, line in lines:
            print ("data:" + str(line) + '\n\n')

and returning
data:b'tail: invalid number of lines: \xe2\x80\x98r\xe2\x80\x99\n'

but if I change command to ping 127.0.0.1, like:
from shelljob import proc

g = proc.Group()
command = "ping 127.0.0.1"
p = g.run (command)

def read_process():
    while g.is_pending():
        lines = g.readlines()
        for proc, line in lines:
            print ("data:" + str(line) + '\n\n')

and it works fine!. returning:
data:b'64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.056 ms\n'

So what's the solution?

A: The data is returned in bytes, as indicated by the b in fron of the output.
You have to decode it to a string.
print ("data:" + line.decode('utf-8') + '\n\n')

A: I am pretty sure your command isn't being piped as you might expected when calling g.run - the arguments -n -r after mitmdump is somehow being passed to tail, thus running this:
$ tail -n -r
tail: invalid number of lines: 'r'

Produce that error message you are seeing.
Now that you tell us what g.run actually is, looking at the documentation for the function we can see that it takes a shell argument which is passed to Popen, which is the argument to enable the processing of shell commands.  To resolve this issue, you may try the following instead:
p = g.run(command, shell=True)


text:
Q: Not all request parameters showing ajax node.js I am building an app using node.js and have a GET endpoint in the form:
/api/car/:id
I have a GET request like:
var data = {
    color: 'red',
    mileage: '1000'
};

$.ajax({
    type: "GET",
    url: "/api/car/12345",
    data: {color: 'red', mileage: '1000'},
    success: function(data) {
        console.log(data)
    },
    error: function() {
        console.log('some error occurred');
    }
});

When I console.log the parameters on the server side I only get the '12345' but I do not get the parameters defined in data:
console.log(req.params)
{ id: '12345' }
Whereas it should be something like:
{ id: '12345', color: 'red', mileage: '1000' }
Can someone help? I need to use all 3 parameters on the server side...
Thanks in advance!

A: It looks like you are using Express.
Query string data (which is where jQuery will put the values you pass to data when you make a GET request) is found in req.query, not req.params (which only contains the parameters defined in your route specification).

A: req.params returns parameters matched in your defined route. To access the parameters sent in the query string part of the url, you need to use req.query

A: You can access the color with req.body.color.
But first you need a "body-parser" package.


text:
Q: match operator in function argument in elixir? I was going through elixir project code base and i encounter the following
please help me out what is here the matching operation is doing in function argument??
{ result, errors } = validate(schema, data, "", data)

def validate(root = %{ custom: validator }, data, path, full_data) when is_function(validator) do
  { result, errors } = if Map.has_key?(root, :type), do: validate( Map.drop(root, [:custom]) , data, path ), else: { data, [] }
  case validator.(full_data, result, path) do
    { :ok, value } -> { value, errors }
    { :error, error } -> { result, errors ++ [ %{ param: path, code: :validation_error, message: error  } ]  }
  end
end

A: This is very idiomatic code that serves several purposes:

*

*It ensures that the root parameter is a map that contains custom key (it might or might not contain other keys too, but we don't care about them)

*If so, it destructures it in place and binds custom's value to the validator

*It then additionally ensures (using a guard) that validator is a function

You can achieve the same via explicit checks within a function body, but this would be more verbose, probably less efficient, and for sure less idiomatic.

A: As the other answer is like a fish, I'd like to contribute a bit and show you how to fish.. You can use this technique to quickly try out all the wacky edge cases you're not sure about and see the behavior.
You can fire up iex and type something like this:
defmodule Foo do
   def validate(root = %{custom: validator}) do
     IO.puts(inspect(root))
     IO.puts(inspect(validator))
   end
end

Then go crazy and try it out:
> Foo.validate(%{custom: "custom-value", other: "yes"})
%{custom: "custom-value", other: "yes"}
"custom-value"

> Foo.validate(%{other: "yes"})
** (FunctionClauseError) no function clause matching in Foo.validate/1

    The following arguments were given to Foo.validate/1:

        # 1
        %{other: "yes"}

    iex:5: Foo.validate/1

inspect/1 returns a string representation of a structure, and IO.puts/1 prints it in the STDOUT.


text:
Q: Show the [about] link on the top of the page regardless of reputation? I was looking for the [about] link a little while ago, and was quite annoyed to discover that it wasn't at the top of the page where it used to be.
It was pointed out to me that the link disappears automatically when you hit a specific amount of reputation (5K on graduated sites, 2K on beta sites), which explains where it went, but it doesn't lessen the irritation it caused by not being where I expected it when I wanted it.
I can understand hiding popup reminders based on rep, or large blocks of text that take up a lot of screen space, but hiding a small static link when a user hits a specific rep threshold is unexpected and very aggravating when trying to find the link in the future.
So I would like to request that the [about] link stay visible at all times at the top of the page, and not disappear based on reputation.
(I found out later that there is another [about] link in the footer of the page, but I would not have noticed that without another user pointing it out to me, as I was used to the link being at the top of the page, and would not have thought to look for it in the footer)


text:
Q: How to view the databases in Android Device? I need to view the database in my android device but as it an un-rooted device, I am unable to do so. I have implemented the following code in my DBAdapter class and am calling it at another activity.
CODE :
void exportDB() {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//" + "com.example.facebook_integration"
                        + "//databases//" + "image_database.db";
                String backupDBPath = "//sdcard//FBDatabase";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                //Toast.makeText(getApplicationContext(), "Backup Successful!",Toast.LENGTH_SHORT).show();

            }
        } catch (Exception e) {

            //Toast.makeText(getApplicationContext(), "Backup Failed!", Toast.LENGTH_SHORT).show();

        }
    }

But the above code doesn't seem to work. I have already surfed well in Stackoverflow about this question(there are quiet a few) and also tried the adb commands but none of them has worked. Can you please tell me where am going wrong at the above code or an alternative to the above solution ? Help will be much appreciated guys.

A: You can dump DB into SDcard and open into SQLite Manager o SQLite Database Tools:
    File f=new File("/data/data/yourapppackagename/databases/database");
                    FileInputStream fis=null;
                    FileOutputStream fos=null;

                    try
                    {
                      fis=new FileInputStream(f);
                      fos=new FileOutputStream("/mnt/sdcard/folder/database.db");
                      while(true)
                      {
                        int i=fis.read();
                        if(i!=-1)
                        {fos.write(i);}
                        else
                        {break;}
                      }
                      fos.flush();
                      Toast.makeText(getParent(), "DB dump OK", Toast.LENGTH_LONG).show();
                    }
                    catch(Exception e)
                    {
                      e.printStackTrace();
                      Toast.makeText(getParent(), "DB dump ERROR", Toast.LENGTH_LONG).show();
                    }
                    finally
                    {
                      try
                      {
                        fos.close();
                        fis.close();
                      }
                      catch(Exception ioe)
                      {}
                    }

A:  you just select Database file and then export into your system.

A: You are not getting the output as your file backupDB does not physically exists.
File backupDB = new File(sd, backupDBPath); - this will only create a logical file object, it may not be physically present.So you should call,
backupDB.createNewFile();

in order to physically create  a file.


text:
Q: Jekyll: adding url and baseurl to post images and links Is there a way to have Jekyll apply the baseurl to image and link urls in markdown?
Here's the markdown syntax I want to use:
[![some image alt title](/wp-content/uploads/2013/08/my_image.jpg)](/wp-content/uploads/2013/08/my_image.jpg)

This should be deployed in a folder (id: http://example.com/portfolio) using baseurl: portfolio in _config.yaml. The problem is that the image and link URLs are not being given the relative_url when the page renders:

However, it works if I use the link tag:
[![some image alt title]({% link /wp-content/uploads/2013/08/my_image.jpg %})](/wp-content/uploads/2013/08/my_image.jpg)

The posts have hundreds of images (some with links, some without) and I'd rather not have to change all of the markdown. Is there a way to get the same effect programmatically in Jekyll?