text:
Q: remove object from NSMutableArray by key NSMutableArray *array = [NSMutableArray arrayWithObjects:@{@"name":@"Jenny",@"age":@23},@{@"name":@"Daisy",@"age":@27},nil];

Is it possible to remove object by key in the array's dictionary object?
For example. remove object by age = 27

A: To filter objects out of an NSArray, call filteredArrayUsingPredicate:
NSArray *array = @[@{@"name":@"Jenny",@"age":@23},@{@"name":@"Daisy",@"age":@27}];
NSArray *array2 =
  [array filteredArrayUsingPredicate:
   [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *d) {
      return ![[obj valueForKey:@"age"] isEqual:@27];
  }]];

Now array2 is the desired array - it is the first array without the one whose age is 27.
By the way, I know this is not what you asked, but that sort of thing is a great reason to switch to Swift. It is soooooo much simpler; this sort of problem is like a living neon technicolor advertisement for Swift:
let array = [["name":"Jenny", "age":23],["name":"Daisy", "age":27]]
let array2 = array.filter {$0["age"] != 27}

A: You can use NSPredicate to create a new array that's missing the unwanted entry. NSPredicate is similar to a database query where the input NSArray represents the database, and the output array is the response to the query.
NSArray *array = @[  @{@"name":@"Jenny",@"age":@23},
                     @{@"name":@"Daisy",@"age":@27}  ];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age != 27"];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];

NSLog( @"%@", array );
NSLog( @"%@", filtered );

A: I'm not sure if there's a more direct method or not, but one way to do it would be to simply iterate through the array and test the values. You can't mutate an array while enumerating, meaning you cant remove an object while iterating through it, so one method is to obtain the index of the object that matches your criteria, and if you find one, break, and remove the item at that index. Something like the following:
NSInteger indexToDelete = -1;

for (NSInteger i = 0; i < array.count; i++) {
   NSDictionary *dict = array[i];

   if ([dict[@"age"] integerValue] == 27) {
      indexToDelete = i;
      break;
   }
}

if (indexToDelete > 0) {
   [array removeObjectAtIndex:indexToDelete];
}

Intrigued by the other answers using filteredArrayUsingPredicate, I was curious about performance and decided to do a side-by-side performance test using Xcode's measureBlock feature. Iterating through an array of 1,000 dictionaries, removing one item that matches an integer value from each array, and comparing when the item is very close to the beginning of the array, the middle of the array, and the end of the array, both versions tended to complete within a few thousandths of a second of the other, with the predicate filter being very slightly faster in every case. (We're talking around .269 seconds vs .261 seconds)
With that in mind, I would think that neither is better than the other in any major sense, it just comes down to preference. I do think the filteredArrayUsingPredicate method is cleaner though. Just some additional food for thought for anyone curious, and gave me a reason to try out the measureBlock feature on my own. :)

A: In this case, you'll have to loop through each item and do a manual test against each object, which may be fine depending on the size of data you're dealing with and the complexity of your use cases.
Alternatively, consider storing the data in a sqlite database and querying against it if it's practical for you.


text:
Q: OpenVPN and Performance From my understanding RDP is encrypted and so is the OpenVPN connection so that is an encryption in an encryption.
My Setup:
LAPTOP <---> REMOTE SERVER <---> OFFICE SYSTEM

Due to firewalls I setup OpenVPN on SSL 443 to get out to my home systems by connecting them all to a remote openvpn server. However, the connection is very laggy and I am assuming this is due to the double encryption. Can I disabled the OpenVPN encryption some way to maybe improve performance?

A: To answer the actual question: you can disable encryption in OpenVPN with these configuration directives:
auth none
cipher none

Set these in your server configuration and you will have no security at all provided by OpenVPN. Obviously this is ludicrous and not at all recommended.
See for example: http://docs.openvpn.net/under-the-hood/change-encryption-cipher-in-access-server/

redpajama_set_name: RedPajamaStackExchange


text:
Q: xcode: application runs properly from Debug folder, but not if copied to any other folder I have a weirdness with my applescript application created in xcode.
When building for run, it runs properly. When copying the app from the Debug folder to another place, it does not run properly.
The application starts Photoshop, and then uses System Events UI scripting to open the Open File dialog. When not running from the Debug folder, it gets to start Photoshop, also activates System events, it seems to find the Photoshop process, but does not start with the UI scripting.
Being a noob, it baffles me, and I am stuck.
If further information is needed, please bear with me, and let me know what is needed.
Additional information: Another very similar application, which in particular uses exactly the same code, does work without issues.
Also, as asked in a comment, the application is given control to the machine in the Accessibility settings.
Edit: code as requested in comment
set myps to "com.adobe.Photoshop"
set applName to (get name of application id myps)

delay 1

tell application id myps
    -- activate
    using terms from application "Adobe Photoshop CC 2018"
        activate
        tell application "System Events"
            set ProcessList to name of every process
            if (applName is in ProcessList) then
                tell process applName
                    delay 0.8
                    display alert "here I am"
                    click menu item 2 of menu 1 of menu bar item 3 of menu bar 1
                    delay 0.8
                    tell window 1
                    -- and so on

"click menu item 2 of menu 1 of menu bar item 3 of menu bar 1" opens the Open File dialog.
When running automatically after building or form the Debug (or Build) folder, that dialog opens; when running from elsewhere, the last thing I get is the "I am here" alert.
Also note that there is another block of code omitted, which uses a plist file to pass some parameters at runtime, but these parameters are needed only later in the script.
Thanks in advance

A: This is most likely because you need to build for release instead of debug.  To do this go to Product -> Scheme -> Edit Scheme. Then click the Run tab on the side and change the Build Configuration to Release.
This will build an executable that should be completely self contained.


text:
Q: Address removed on checkout in guest checkout I have this problem in magento 1.9 with checkout one page.
In the checkout process when I select the guest checkout, complete the billing form and click continue,and after I go out in a category of the e-commerce because i forgot to add an item in the cart, I come back in the checkout to finish the process I must write another time the billing informations because the fields are empty. Is possible to add the informations only one time?
I found this article:http://www.samitrimal.com.np/magento-address-removed-on-checkout-in-guest-checkout/
should be a solution but i don't know how to implement, please can you help me?
thanks
Alberto
Update
I post here what i added in the system following the guide:
1) I created a folder inside App/etc/modules/Fix_billing.xml
inside the xml file there is:
<config>
<modules>
 <Fix_billing>
   <active>true</active>
        <codePool>local</codePool>
   </Fix_billing>
 </modules></config>

2) Another Folder in App/code/local/Fix/billing/
and after inside other folders:
Block
controllers
etc
Helper
Model
sql
inside etc folder I added config.xml with the code of the guide and inside the controllers folder a file IndexController.php with the code of the guide.
After all this what's my mistake? sorry but i the first time I di this  chenges..
Thanks
Alberto
Okay I tried but doesn't work, in this link I have all the data I inserted..please can you check if it's okay?
http://we.tl/SrfTX1gGdm
thanks Alberto


text:
Q: How to build a tree from an array of objects? I have array with data:
const data = [
  { id: 1, type: 'type 1' },
  { id: 2, type: 'type 2', subtype: 'subtype 2' },
  { id: 3, type: 'type 2', subtype: 'subtype 3' },
  { id: 4, type: 'type 2', subtype: 'subtype 4' },
  { id: 5, type: 'type 3', subtype: 'subtype 3' },
];

And I need to build the tree like this:
type 1
type 2
  subtype 2
  subtype 3
  subtype 4
type 3
  subtype 3

A: In case the OP's example data items keep their simple type/subtype structure the approach boils down to a grouping task where the type's value is the key (property name) of a new group of subtype entries (continuing the object structure) or items (changing to an array structure).
Aggregating (grouped) data at an object is a classic reduce task.
Used language features:

*

*Array.prototype.reduce

*Array.prototype.map

*Object.entries

*Arrow function expressions

*Destructuring assignments / Object destructuring

*Destructuring assignments / Default values

*Logical nullish assignment / ??=

*String.prototype.replace

*String.prototype.trim

const data = [
   { id: 1, type: 'type 1' },
   { id: 2, type: 'type 2', subtype: 'subtype 2' },
   { id: 3, type: 'type 2', subtype: 'subtype 3' },
   { id: 4, type: 'type 2', subtype: 'subtype 4' },
   { id: 5, type: 'type 3', subtype: 'subtype 3' },
];
console.log(
  'pure object based tree ...',
  data
    .reduce((result, { type, subtype = null }) => {

      const typeGroup = (result[type] ??= {});

      if (subtype !== null) {
        typeGroup[subtype] = {};
      }
      return result;

    }, {})
)
console.log(
  'object and array item based tree ...',
  data
    .reduce((result, { type, subtype = null }) => {

      const groupedSubtypeList = (result[type] ??= []);

      if (subtype !== null) {
        groupedSubtypeList.push(subtype);
      }
      return result;

    }, {})
)
console.log(
  'what the OP probably is looking for ...',
  Object
    .entries(
      // same reduce functionality as one example before.
      data
        .reduce((result, { type, subtype = null }) => {

          const groupedSubtypeList = (result[type] ??= []);

          if (subtype !== null) {
            groupedSubtypeList.push(subtype);
          }
          return result;

        }, {})
    )
    // additional mapping over the reduce result's entries.
    .map(([type, subtypes]) => {
      const typeItem = {
        type: type.replace('type', '').trim(),
      };
      if (subtypes.length >= 1) {
        typeItem.subtypes = subtypes
          .map(subtype => ({
            subtype: subtype.replace('subtype', '').trim(),
          }));
      }
      return typeItem;
    })
)
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: Edit 2 - edited for more structured way

const data = [{
    id: 1,
    type: 'type 1'
  },
  {
    id: 2,
    type: 'type 2',
    subtype: 'subtype 2'
  },
  {
    id: 3,
    type: 'type 2',
    subtype: 'subtype 3'
  },
  {
    id: 4,
    type: 'type 2',
    subtype: 'subtype 4'
  },
  {
    id: 5,
    type: 'type 3',
    subtype: 'subtype 3'
  },
];

var pretype = "";
//const newArr = data.map(change);

var pretype = "";
var preindex = -1;
const arr2 = []

data.forEach(function(idx) {
  if (pretype != idx.type) {
    //console.log(idx.type);
    arr2.push({
      //'id': idx.id,
      "type": idx.type.replace("type ", "")
    });

    preindex++;
  }

  if (idx.subtype) {
    //console.log("pr", preindex, arr2[preindex], arr2[preindex]["subtypes"])
    if (arr2[preindex]["subtypes"] == undefined)
      arr2[preindex]["subtypes"] = [];

    arr2[preindex]["subtypes"].push({
      "subtype": idx.subtype.replace("subtype ", "")
    })
  }
  pretype = idx.type;

});
console.log("arr2: ",arr2)
console.log("flat: ",JSON.stringify(arr2));

function change(id) {
  if (pretype != id.type)
    console.log(id.type);
  if (id.subtype)
    console.log(id.subtype)

  pretype = id.type;

}

A: Build any object from array. Merge the values when you have same keys

const data = [
  { id: 1, type: "type 1" },
  { id: 2, type: "type 2", subtype: "subtype 2" },
  { id: 3, type: "type 2", subtype: "subtype 3" },
  { id: 4, type: "type 2", subtype: "subtype 4" },
  { id: 5, type: "type 3", subtype: "subtype 3" },
];

const buildTreeObj = (arr) => {
  const obj = {};
  arr.forEach((item) => {
    if (obj[item.type]) {
      obj[item.type].subs.push(item.subtype);
    } else {
      obj[item.type] = {
        type: item.type,
        subs: item.subtype ? [item.subtype] : [],
      };
    }
  });
  return Object.values(obj);
};

console.log(buildTreeObj(data));


text:
Q: How to access dataframe column by variable / string I'm struggling to achieve something supposedly simple. I have dataframe df with columns a and b. If I call df$a, df$"a" df$`a`, it works. So I'm thiking I can assign a variable a string, and then use that. But if I do and try to get the column with it, I get Unknown or uninitialised column.
df = data.frame(a=(1:3), b=c("a", "b", "c"))
df$a # works
df$`a` # works
df$"a" # works

x <- "a"
df$x # error

How to solve this?


text:
Q: How to auto answer an incoming Skype call? Is it possible to auto answer to an incoming Skype call from specific Number or contact?
I Think this should work with a Python script using Skype4py but as I am not a programmer I don't have an idea how to do this.
Anybody has any suggestions?

A: Assuming your skype is online, i.e. that you have logged in and there are no network problems, you can do the following:

*

*In the skype list of phone numbers there is a buttom at the
bottom of the skype window which gives you access to settings. Click
on that, and the "options" menu pops up.

*Go to notifications,and select "incoming call ringing". Now select "Advanced View".

*At the bottom of the "advanced view" is an option to "Execute the
following script", in which you enter full the filepath of your
script.

*Press apply.

The script

global _proc
global use_growl

tell application "System Events" to set _proc to name of processes as list
if _proc contains "GrowlHelperApp" then
    set use_growl to true
    my growlRegister()
else
    set use_growl to false
end if

if _proc contains "Skype" then
    tell application "Skype"
        set calls to send command "SEARCH ACTIVECALLS" script name "AnsweringScript"
        set callID to last word of calls
        if callID is not "CALLS" then
            set status to send command "GET CALL " & callID & " STATUS" script name "AnsweringScript"
            if last word of status is "RINGING" then
                send command "ALTER CALL " & callID & " ANSWER" script name "AnsweringScript"
                my growlNotify("SkypeAnswer", "Answering call")
                return
            else
                send command "ALTER CALL " & callID & " HANGUP" script name "AnsweringScript"
                my growlNotify("SkypeAnswer", "Hanging up")
            end if
        else
            my growlNotify("SkypeAnswer", "No call found to answer or hang up")
        end if
    end tell
else
    my growlNotify("SkypeAnswer", "Skype not detected")
end if

using terms from application "GrowlHelperApp"
    on growlRegister()
        tell application "GrowlHelperApp"
            register as application "SkypeAnswer" all notifications {"Alert"} default notifications {"Alert"} icon of application "Skype.app"
        end tell
    end growlRegister

    on growlNotify(grrTitle, grrDescription)
        if use_growl is true then
            tell application "GrowlHelperApp"
                notify with name "Alert" title grrTitle description grrDescription application name "SkypeAnswer"
            end tell
        end if
    end growlNotify
end using terms from

Reference: 1
Kind Regards
BHM


text:
Q: UIDevice model vs. localizedModel I want to use the iOS device's model name in the UI.
Since my app is localized, I figure I should use the localizedModel property of UIDevice.
So far, I've tried a few languages (Japanese, Russian, Simplified Chinese, Arabic), and localizedModel is always "iPhone."
I can't seem to find any recommendations or descriptions about this property.
Does anyone know anything about it, such as whether its values ever diverge from what the model property returns? Why does it exist?

A: From the docs:

The model of the device as a localized string. (read-only)

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html
From my testing, It returned iPhone Simulator as model and localizedModel when the language was set to Russian, and iPhone for both on an iPhone 4.
I'm not sure whether model is the right method to use at all, as it reports and iPhone 4 to be just an iPhone, but if that's all you want that's fine.
I really don't think that the names would be particularly localized anyway, seeing as iPhone is a trademark, it's not going to return it in Cyrillic characters.
I would say just use localizedModel, it might magically localize at some point, and it won't return a blank string.


text:
Q: How to use loops statements in unix shell scripting How to use loop statements in unix shell scripting for eg while ,for do while.  I'm using putty server.

A: for: Iterate over a list.
$for i in `cat some_file | grep pattern`;do echo $i;done

while loop looks pretty much like C's.
$ i=0;while [ $i -le 10 ];do echo $i;i=`expr $i + 1` ;done

If you are going to use command line only, you could use perl, but I guess this is cheating.
$perl -e '$i=0;while ($i < 10){print $i;$i++;}'

More data
http://www.freeos.com/guides/lsst/

A: #!/bin/sh
items=(item1 item2 item3)

len=${#items[*]}

i=0
while [ $i -lt $len ]; do
  echo ${items[$i]}
  let i++
done

exit 0

A: As well as the 'for' and 'while' loops mentioned by Tom, there is (in classic Bourne and Korn shells at least, but also in Bash on MacOS X and presumably elsewhere too) an 'until' loop:
until [ -f /tmp/sentry.file ]
do
    sleep 3
done

This loop terminates when the tested command succeeds, in contrast to the 'while' loop which terminates when the tested command fails.
Also note that you can test a sequence of commands; the last command is the one that counts:
while x=$(ls); [ -n "$x" ]
do
    echo $x
done

This continues to echo all the files in the directory until they're all deleted.

A: to the OP, to iterate over files
for file in *
do
 echo "$file"
done

to generate counters
for c in {0..10}
do
 echo $c
done

A: using for loop
max=10
for (( i=0; i<=$max; i++ ));
do
echo $i
done

A: to iterate through a file in KSH
while read line ; do
echo "line from file $line"
done < filename.txt

A: echo "sample while loop"
i=0;
while [ $i -le 10 ]
do
echo $i
 (( i++ ))
done


text:
Q: Jenkins Declarative Pipeline Embedded Library Include Within a Jenkins declarative pipeline, one or more global libraries can be referenced through the Library annotation. ie.
@Library(['myLib1', 'myLib2', 'myLib3']) _

If myLib1 is refactored into 2 libraries, all pipelines that reference myLib1 need to be changed to reference both libraries.
@Library(['myLib1.a', 'myLib1.b', 'myLib2', 'myLib3']) _

Is there a way to load a dependent library inside a global library? Or some other mechanism that could aggregate including both the libraries in such a way that all the pipelines referencing myLib1 do not need to be modified to myLib1.a, myLib1.b?


text:
Q: voltage divider circuit design I am giving -8 to +8 V supply to the op-amp. So, output of the op-amp is varying from (-8 to +8) V. I want to give this to ADS1115 ADC module. But the ADC module's max. Vin is 5.5 V.
I decided to use voltage divider. What I need is one voltage divider circuit which gives the output that ranges from 0-5 V, when we give the -8 to +8 V as Vin.
Problem here is negative voltage of -8 V. How can I over come this problem ?

A: With a divider that has R1 = R3 and R1 = 1.2 * R2, you will scale the 8V to -8V range to 0 to 5V, as shown in the plot below.
At Vin = 8V you have a voltage divider with R1 || R3 and R2.  At Vin = -8V, if R1 = R3, you have Vout = 0V.  Doing the math from these two cases gets you R1 = 1.2 * R2.

A: Depending on your configuration, it is possible to connect the ground of your ADC to the negative rail of the opamp. -8V to +8V is just another way of saying 0V to +16V.
Then you need to scale the opamp voltage from 0-16V to 0-5V.

simulate this circuit – Schematic created using CircuitLab
When the input is 16V you want the output to be 5v. Therefore:
$$\frac{16*R2}{R1+R2} = 5$$
Lets make R2 1kΩ. Then:
$$\frac{16*1000}{R1 + 1000} = 5 $$
Some rearrangement:
$$R1 = \frac{16*1000 - 5 *1000}{5} = 2.2KΩ$$

A: You really need to do two things.

*

*Attenuate your +-8V signal to +-2.5V AND

*Offset the signal to a bias point of 2.5V.

The circuit below will do that for you.

simulate this circuit – Schematic created using CircuitLab

OA2 buffers the half rail voltage generated by divider R1, and R2, with C1 to provide some filtering of any rail noise.
OA3 buffers the input signal after it is divided down from +-8V to +-2.5V by divider R3 and R4.
OA1 is a summing amplifier that adds the half rail offset from OA2 to the attenuated input signal from OA3 and produces the 0 to 5V signal you require.
R9, D1 and D2, provide a little extra protection from events where OA1 outputs over 5V or negative voltages, especially during power up.
Simpler implementations are likely available that combine functionality, but I personally prefer to keep my linear functions distinct for debugging purposes.
Use of 1% or better resistors is warranted in circuits like this.

NOTE: ADCs normally work better when you use the internal reference rather than measuring as a proportion of the supply rail which can wander or be noisy. As such, feeding the reference voltage from the ADC to the top of R1 instead of Vcc, and changing the divider, R3 and R4, appropriately may provide better results.


text:
Q: Subspace of linear transformation proof legit? Let V and W be vectorspaces over a body $\mathbb{K}$ and U a subspace of W.
$f:V \rightarrow W$ is a linear transformation.
Proof that $S=\{v \in V |f(v) \in U\}$ is a subspace of V.
Because we can assume that the transformation is linear, the criteria for linearity always holds, right?
Let $v, v' \in V | f(v),f(v') \in U$
$f:V \rightarrow W$ be a linear transformation.
Thus any vector v,v' satisfies $f(v + v')=f(v)+f(v')$ and $f(av)=af(v)$.
Is the question proofed just by relying on the fact that the transformation is linear to begin with?

A: Yes, it relies on the fact that $f$ is a linear transformation. For $S$ to be a subspace of $V$, it has to satisfy three conditions.
$1.$ The additive identity of $V$ denoted $0$ is an element of $S$.
$2.$. $S$ is closed under addition.
$3. $ S is closed under scalar multiplication.
You have proved both of them apart from the first one. The first one is easy as a linear transformation always takes $0$ to $0$. Thus, $0\in V$ as $f(0)=0\in W$. Here the zero on the right side is the additive identity of $W$.
You have showed that it closed under addition and closed under scalar multiplication. Thus, $S$ is a subspace of $V$.
But I would word that part of the proof a bit differently. Let $u, v\in V$. We have to show that $u+v\in V$. Given that $u, v\in V$, we know that $f(u)$ and $f(v)$ are in $W$. Because $W$ is a vector space, it is closed under addition. Therefore $f(u)+f(v)\in W$. Now use the fact that $f$ is a linear transformation to deduce that $f(u+v)\in W$ and therefore $u+v\in V$.
The same goes for proving that $S$ is closed under scalar multiplication. Otherwise, the proof is good. Well done!


text:
Q: WSO2 ESB cache mediator timeout We are using cache mediator and want to make the timeout property of the cache mediator configurable (reading value from registry or some local property)
We tried few options but looks like it takes constant value integer value only .
Any inputs on the same

A: AFAIK You can not change this value dynamically. It is always going to take the value you give when creating the cache mediator nevertheless this value can not be change dynamically.


text:
Q: React + Redux + normalizr api request error handling I have implemented an abstract "entity" reducer for every single API call from my app. Now I would like to use normalizr, to keep API data in normalized shape. Until now I was saving my API request response, that came from API middleware by API actions, in reducer like:
case action.type.includes(API_ERROR):
case action.type.includes(API_SUCCESS):
  return {
    ...state,
    [action.payload.label]: {
      error: action.isError,
      data: action.payload.data
    }
  };

to keep my Error flag to be able to indicate (in Components) if the request did succeed or not.
If I do understand normalizr correctly, then entities reducer will be treated like "database". I suppose that having error or isError flag in normalized data is not right is it?.
I'm just not able to solve, how my Reducer will look when I use normalizr to normalize data and how I will be able to track (In components...) if the request succeeds or not after this code refactoring
The other thing is that if my request fails, response data will no contain ID or any other identification which tells what request did fail (I'm currently using Entity label from, e.g., fetchMembers() action as the indicator for that). Failed response data contains only status and reason (why).
Do you guys have any suggestions, please? Can I keep using only single abstract reducer for that, or I should better make custom reducers for all of my API actions?

SUBQUESTION:
And I'm also having requests, which response data are not significant in context of components and only significant info is if request SUCCED or FAILED (requests like log out, log in, ...). I'm assuming that their responses should not be assigned to the redux store to prevent bloating of the store. What can I do with requests like these, please?

A: Don't put isError or isLoading flags in normalized data because normalizr is for normalizing deeply nested objects. It essentially, takes a deeply nested javascript object and flattens it out and in this way you can get rid of redundant data which is its biggest advantage.
We used React + Redux-Sagas + normalizr. Hope this fiddle of code will help you out in setting up your reducer
Reducer
// @flow

import {
  FETCH_DETAILED_EXPERIENCE_DATA,
  FETCH_DETAILED_EXPERIENCE_DATA_SUCCESS,
  FETCH_DETAILED_EXPERIENCE_DATA_ERROR,
} from '../ActionTypes'
import Immutable from 'seamless-immutable'
import { createReducer } from '../CreateReducer'

const INITIAL_STATE = Immutable({
  experienceData: null,
  isFetching: false,
  error: null,
})

const reducers = {
  [FETCH_DETAILED_EXPERIENCE_DATA]: (state, action) => {
    return Immutable.merge(state, { experienceData: null, isFetching: true })
  },
  [FETCH_DETAILED_EXPERIENCE_DATA_SUCCESS]: (state, { data }) => {
    return Immutable.merge(state, { experienceData: data, isFetching: false, error: null })
  },
  [FETCH_DETAILED_EXPERIENCE_DATA_ERROR]: (state, { error }) => {
    return Immutable.merge(state, { error, isFetching: false })
  },
}

export const reducer = createReducer(INITIAL_STATE, reducers)

Sagas
import { FETCH_DETAILED_EXPERIENCE_DATA } from '../ActionTypes'
import { put, takeLatest, call } from 'redux-saga/effects'
import API from '../../Services/baseApi'
import * as ExperienceActions from './Actions'
import * as EntitiesActions from '../entities/Actions'

import parseExperienceDetailResponse from 'App/Schemas/APIResponse/ExperienceDetailResponse'

function* fetchExperienceDetails(action) {
  try {
    const response = yield call(API.get, 'URL')
    const { entities, result } = parseExperienceDetailResponse(response.data)
    yield put(EntitiesActions.updateEntities(entities))
    yield put(ExperienceActions.fetchDetailedExperienceSuccess(result))
  } catch (e) {
    yield put(ExperienceActions.fetchDetailedExperienceError(e.message))
  }
}

export default function* root() {
  yield [yield takeLatest(FETCH_DETAILED_EXPERIENCE_DATA, fetchExperienceDetails)]

Schema
// @flow

import { normalize, schema } from 'normalizr'

const experience = new schema.Entity(
  'experiences',
  {
    owner: user,
  },
  { idAttribute: 'Id' },
)

const response = new schema.Object({
  experience,
})

export default (input: any) => {
  const { entities, result } = normalize(input, response)

  return {
    entities,
    result: result,
  }
}

Hope this helps thanks.


text:
Q: Ms Excel Conditional Formt Text Ranges How do I automatically have excel color code the cells in my table, to the legend I have in column I based on the text values? Is there a formula I can use to do this as I do know VB. I don't mind entering a new rule for each color as long as it pulls the correct text in column I and matches it to the table.
Table = Cells B2:F13 containing all text values

Column I2:I5 = text "YELLOW,PINK,PURPLE,BLUE" Fill color to be Yellow

Column I7:I10 = text "GREY,TAN,TEAL,MUSTARD" Fill color to be Green

Column I12:I14 = text "GREEN,ORANGE,RED" Fill color to be Orange

A: First select cell B2. In the Conditional Formatting Rules you will need to make 3 rules, one for each fill color. Select the 'Use a formula to determine which cells to format' option. Now we will use Excel's formulas to determine if the text matches the legend. Enter the following formula into the conditional format for B2:
=IFERROR(MATCH(B2,$I$2:$I$5,0),0)>0
That is the code for matching to the Yellow, Pink, Purple, and Blue keywords. This takes the value in the cell it applies to and looks for it in the legend referenced, if the match function finds the text it returns the location in the array, a non-zero number. If match doesn't find a match it throws an error, which we catch with the iferror function which converts it into a 0. Finally, we compare our result to 0 which gives us the true/false that the conditional format needs.
Note that the first reference B2 is relative while the match array reference is absolute. This way when we expand the conditional format to cover the whole area it updates the reference to apply to each cell, but not the reference to our legend.
For the other 2 colors simply adjust the match array to the other references.
Then the final step is to go into the conditional formatting rules manager and adjust the 'applies to' range to the full range instead of just B2.


text:
Q: Allow Decimal value in number I have form filed in some amount has to be enter. Amount is separated by commas and decimal is not allowed. I want to allow decimal in amount. Thanks in advance...
Here is my Code :
(function($, undefined) {

    "use strict";

    $(function() {

        var $form = $( ".number" );
        var $input = $form.find( ".no" );

        $input.on( "keyup", function( event ) {

            var selection = window.getSelection().toString();
            if ( selection !== '' ) {
                return;
            }

            if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
                return;
            }

            var $this = $( this );

            var input = $this.val();

            var input = input.replace(/[\D\s\._\-]+/g, "");
            input = input ? parseInt( input, 10 ) : 0;

            $this.val( function() {
                return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
            });

        });

    });

})(jQuery);

A: $(function() {

var $form = $( ".number" );
var $input = $form.find( ".no" );

$input.on( "keyup", function( event ) {

    var selection = window.getSelection().toString();
    if ( selection !== '' ) {
        return;
    }

    if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
        return;
    }

    var $this = $( this );

    var input = $this.val();

            input = input ? parseFloat( input) : 0;

            $this.val( function() {
                return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
            } );
} );

  });
   })(jQuery);


text:
Q: Color points of a scatterplot according to row numbers I made a simple scatterplot with this code:
plot(FB_MW$Ärger, w2v$aerger,
 main = "Ärger",
 xlab = "Rating Fragebogen (MW)",
 ylab = "word2vec")

Now I would like to colours according to the rows in my tablet called "w2v". Rows 1 to 6 should be depicted in blue, Rows 7 to 12 in red.
Another option might be to determine the the colour by a colum of the tablet called w2v$D which contains "yes" and "no" values.
Thanks a lot!
Lorena

A: You could try:
w2v$color <- "blue"
w2v$color[w2v$D == "no"] <- "red"

plot(FB_MW$Ärger, w2v$aerger,
 main = "Ärger",
 xlab = "Rating Fragebogen (MW)",
 ylab = "word2vec",
 col  = w2v$color)

Another option is using ggplot2, which is usally a little bit more complex. In this case it's straight forward:
ggplot(w2v, aes(x=FB_MW$Ärger, y=aerger, color=D)) +
  geom_point() +
  xlab("Rating Fragebogen (MW)") +
  ylab("word2vec") +
  labs(title="Ärger") +
  theme(plot.title = element_text(hjust = 0.5))


text:
Q: Linq to Entitites query cannot convert Int to String I am making a search index. I got it working pretty good but I cannot incorporate ItemID (item numbers) in my search because i am having trouble converting the String in the TextBox.Text to a int in order for it to be a comparable type.
var q = (from t0 in db.Item
         join t1 in db.Categories on t0.CategoryID equals t1.CategoryID
         join t2 in db.Divisions on t0.DivisionID equals t2.DivisionID
         where t0.DivisionID == DDLInt &&
         //Contains
         (t0.ItemName.Contains(txtSearch.Text.Trim()) ||
         t0.Email.Contains(txtSearch.Text.Trim()) ||
         t0.Description.Contains(txtSearch.Text.Trim()) ||
         t0.Phone.Contains(txtSearch.Text.Trim()) ||
         t0.ItemID.Equals(txtSearch.Text.Trim()))
               // ^ This is the line where
               //   it breaks because it is not a comparable type
         group t0 by new
         {

I am not sure how to convert or parse it and still have the search work properly.

A: Either parse the string to an int:
t0.ItemID.Equals(Convert.ToInt32(txtSearch.Text.Trim())))

or convert the int to a string:
t0.ItemID.ToString().Equals(txtSearch.Text.Trim()))

or take the conversion out of the query:
int searchID;
if !int.TryParse(txtSearch.Text.Trim(),out searchID)
    searchID = -1;  // set to an invalid ID

var q = (from t0 in db.Item
     <snip>
     t0.ItemID.Equals(searchID))

A: Should simply be:
t0.ItemID.Equals(int.Parse(txtSearch.Text.Trim()))

A: t0.ItemID.Equals(Int32.Parse(txtSearch.Text.Trim());

A: If you are sure that it will be a valid integer you can use int.Parse.  If you are unsure if it's a valid integer you can use int.TryParse and possibly prompt the user to re-enter if it's not valid.
It is generally best to validate all items before building the query (check that numbers are numbers, dates are dates, choice values are a valid choice, etc.).  If something is invalid you can save yourself a database query by checking it at the start.

A: You can use int.Parse
t0.ItemName.Contains(txtSearch.Text.Trim())

would be
int.Parse(t0.ItemName.Contains(txtSearch.Text.Trim()))


text:
Q: PDO SQLSTATE[HY093] <?php
$server   = 'mysql:dbname=test;host=localhost';
$user     = 'root';
$password = '';
$pdo      = new PDO($server, $user, $password);
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$test=0;
$teest=3;
$query = $pdo->prepare('SELECT * FROM imgdb LIMIT :staaart,8');
$query -> execute(array('staaart' => $test, 'eeend' => $teest));
$result=$query->fetchAll();
print_r($result);
?>

This is my PHP/PDO and i get this Warning:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampplite\htdocs\pdo_db_connection.php on line 11
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number in C:\xampplite\htdocs\pdo_db_connection.php on line 11
Array ( )
EDIT: Now it works for me
$server   = 'mysql:dbname=test;host=localhost';
$user     = 'root';
$password = '';
$pdo      = new PDO($server, $user, $password);
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$test=0;
$teest=2;
$teeest='Bochum';
$query = $pdo->prepare('SELECT * FROM imgdb WHERE stadt = :stadt LIMIT :staaart,:eeend');
$query->bindParam(':stadt', $teeest, PDO::PARAM_STR);
$query->bindParam(':staaart', $test, PDO::PARAM_INT);
$query->bindParam(':eeend', $teest, PDO::PARAM_INT);
$query -> execute();
$result=$query->fetchAll();
print_r($result);

A: You only have one parameter in your prepared query, but are attempting to bind two:
$query = $pdo->prepare('SELECT * FROM imgdb LIMIT :staaart,8');
$query -> execute(array('staaart' => $test, 'eeend' => $teest));

Either prepare both staaart and eeend:
$query = $pdo->prepare('SELECT * FROM imgdb LIMIT :staaart,:eeend');
$query -> execute(array('staaart' => $test, 'eeend' => $teest));

Or execute with just staaart:
$query = $pdo->prepare('SELECT * FROM imgdb LIMIT :staaart,8');
$query -> execute(array('staaart' => $test));


text:
Q: $\frac{\sin(\pi x)}{\pi x}$ is differentiable in $0$ Define a function $g:\mathbb{R}\rightarrow\mathbb{R}$ by $g(x)=\frac{\sin(\pi x)}{\pi x}$  if $x\neq0$ and $g(x)=1$ if $x=0$. I want to show that $g$ is two times differentiable and i want to compute $g'(0)$ and $g''(0)$. Can someone help me with this? Can you do something with L'Hospital? since both functions are differentiable? Or do you have to do something more basically? Thanks a lot.

A: It's better to consider
$$
G(x)=\begin{cases}
\dfrac{\sin x}{x} & \text{if $x\ne0$}\\[6px]
1 & \text{if $x=0$}
\end{cases}
$$
because $g(x)=G(\pi x)$ and $g$ is (twice) differentiable if and only if $G$ is.
The function $G$ is continuous at $0$, by a well known limit. The derivative, for $x\ne0$, is
$$
G'(x)=\frac{x\cos x-\sin x}{x^2}
$$
and
$$
\lim_{x\to0}G'(x)=
\lim_{x\to0}\frac{x(1-\frac{1}{2}x^2+o(x^2))-x+\frac{1}{6}x^3+o(x^3)}{x^2}=0
$$
Thus $G$ is differentiable at $0$, by l'Hôpital. Consequently, $g'(0)=\pi G'(0)=0$.
Can you compute the second derivative and argue similarly?

There's an alternative way, with Taylor expansion:
$$
\sin(\pi x)=\pi x-\frac{\pi^3 x^3}{3!}+o(x^3)
$$
so
$$
g(x)=1-\frac{\pi^2 x^2}{6}+o(x^2)
$$
so (in a neighborhood of $0$),
$$
g'(x)=-\frac{\pi^2 x}{3}+o(x)
$$
and
$$
g''(x)=-\frac{\pi^2}{3}+o(1)
$$
so $g''(0)=-\pi^2/3$.

A: At zero, the function is continuous and you can use the bilateral definition of the first derivative,
$$\lim_{h\to0}\frac{f(h)-f(-h)}{2h}.$$
As the function is even, the limit is $0$.
Then,
$$f''(0)=\lim_{h\to0}\frac{f(h)-2f(0)+f(-h)}{h^2}=2\lim_{h\to 0}\frac{\sin(\pi h)-\pi h}{\pi h^3}=-2\lim_{h\to 0}\frac{\pi^2\sin(\pi h)}{6\pi h}=-\frac{\pi^2}3,$$
applying L'Hospital twice.


text:
Q: searching for calendar extension for TYPO3 (upcoming events, month view, widget) I'm searching for a calendar which can be easily embedded on a site (Typo3 / php).
Requirements:

*

*month view

*widget (small calendar view)

*internationalization

*events should be added

The calendar should show the upcoming events with a detailed view when clicking on it. My problem is to find such a calendar extension, which is also regularly updated/maintaned and easy to integrate. I can create events, when using mbl_newsevent but I need the widget in month view. Extensions like Extended Calendar or Calendar Base don't provide me such a widget view. Also it should support different languages (english, german). What about multiple events on a day or events which intersect (same time)?
So taking a PHP calendar or jQuery calender together with mbl_newsevent is my only option? Do you know a solution?
Currently it seems that PHP Calendar and mbl_newsevent is my best chance for realizing such a project. But it seems that it only supports one event on a day ...


text:
Q: Flot Charts and IE 11? We're developing an app using flot charts.  When we look at the same data rendered on Internet Explorer 11 vs, Firefox, we see different lines and different (stacked) bar charts.  That is, the data displayed by flot in IE looks plausible; it's just not correct.  It looks correct in Firefox.
Also, a line chart updated in real time (every 2 seconds) tends to "freeze" (get stuck on a single value) in IE, but not in FF.
Has anyone else experienced anything like this, or are we doing something wrong?

A: Well I could find the answer to this question finally .
The issue here is When we use $http to get the data from the server in AngularJS a small issue arises only in Internet Explorer. The major problem of this issue is that if we want to refresh the data by sending the same call again to the server, Internet Explorer fetches the data from the cache and do not show the updated result.
In case of Flot charts we make the same URL calls to receive the data for the subsequent time range so instead of fetching the new data it fetches the data from the cached URL so we can see that only one 1 request is made from UI to server to fetch the data as a result of which we just get a single data point for all time range .
Fix : POST method of the URL should be used instead of GET to prevent the caching .
$http.post(url) should be used instead of $http.get(url)


text:
Q: If I use Glad and not GLEW will I miss on something? I want to use OpenGL but I don't know how to set up GLEW. Would I lose something if I am going to use Glad? Could I learn from tutorials that use GLEW?

A: If you're starting programming with OpenGL on a desktop platform then either one will work and the choice isn't that critical. Switching later is also still an option. The choice only becomes more important, and more objective, for advanced use cases.
Glad is typically used by selecting the necessary extensions in the web interface, downloading the generated source and header files and copying them into your project. GLEW is a library that needs to be installed and is usually added as an dependency in, e.g., CMake.
Advantages of Glad:

*

*Being able to select only the extensions you use, leading to (slightly) faster compile times and initialization at runtime.

*No additional dependency for your project.

*Also supports the APIs OpenGL ES, EGL, GLX, and WGL.

*Also supports the languages D, Volt, Nim and Pascal.

Advantages of GLEW:

*

*Adding GLEW as a dependency to, e.g., your CMakeLists.txt is enough to make it work.

*No large additional header and source files in your repository.

*GLEW can detect which extensions are available at runtime.
This allows your program to adapt to the available extensions. For example, it can select a fallback path if a certain extension is not available on older hardware.

Other OpenGL loading libraries exists as well. See here: https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library
Disclaimer: The answer is based on my own (limited) experience with both libraries and reading the experiences of others.


text:
Q: Knockout mapping ko.mapping.fromJS I have static method "objectToMyObject" for convert object properties to MyObject properties  objectToMyObject.
I'm trying change "objectToMyObject" to "mapping.fromJS(data)". But I can't decidedd that. Hom implement this problem?
// My get method:
 getMyObject(url: string, params: any, onSuccess: () = > {}, onError: (message: string) = > {}) {
     this.invokeAjax(url, params, (data) = > {
             if (!data.succeeded) {
                 onError(data.error);
             } else {
                 this.editMyObject(MyObject.objectToMyObject(data));
                 //this.editMyObject(<any>this.editMyObject((<any>ko).mapping.fromJS(data)));
                 onSuccess();
             }
         });
 }

 // My invoke method:
 invokeAjax(url: string, params, callback: (result: any) = > {}) {
     $.ajax({
             url: url,
             type: 'GET',
             data: params,
             dataType: 'json',
             cache: false,
             success: (data) = > {
                 callback(data);
             },
             error: (data) = > {
                 this.succeeded(false);
             }
         });
 }

A: I changed your code. As you can see it always calls the callback function with a success parameter.
In your code "if(!data.succeeded)" statement will always returns false. If you want to check the "succeeded" value you should write this : "if(!data.succeeded())"
// My get method:
 getMyObject(url: string, params: any, onSuccess: () = > {}, onError: (message: string) = > {}) {
     this.invokeAjax(url, params, (data, success) = > {
             if (!success) {
                 onError(data.error);
             } else {
                 ko.mapping.fromJS](vm /*your view model (may be this)*/, {}, data)
                 //this.editMyObject(MyObject.objectToMyObject(data));
                 //this.editMyObject(<any>this.editMyObject((<any>ko).mapping.fromJS(data)));
                 onSuccess();
             }
    });
 }

 // My invoke method:
 invokeAjax(url: string, params, callback: (result: any, success : any) = > {}) {
     $.ajax({
             url: url,
             type: 'GET',
             data: params,
             dataType: 'json',
             cache: false,
             success: (data) = > {
                 callback(data, true);
             },
             error: (data) = > {
                 callback(data, false);
             }
    });
 }

My response to your first question
Early, in your code you bound the view model to the view by calling ko.applyBindings(vm).
Now, when you receive the refreshed data from the ajax callback, you can call ko.mapping.fromJS(vm, {}, data);
I hope it helps


text:
Q: Killing Threads with pthreads - C I have a C pthread program that creates N threads in main that update a global variable. Main also calls pthread_join on all of these update threads to wait for them to finish. I also have 2 watcher threads that use pthread condition variables to check to see if the global variable goes above or below certain numbers, and if so, it kills all update threads and the other watcher thread. However, I'm having trouble with this last part..killing the other threads. My program does what it is supposed to do but never completes... it just gets stuck. Calling exit(0) at the end of each watcher thread works but I feel like that's too lazy of a solution, I'd really like to learn how to kill other threads from a separate thread and return to main.
Here's my code:
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void *update(void *i);
void *watchIncrease();
void *watchDecrease();

//init globals
double marketValue;
int numThreads;
double *stocks;
double ceiling;
double floor_;
int flag;

pthread_t *threads;
pthread_t watchIncreaseThread;
pthread_t watchDecreaseThread;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t threshold_ceiling;
pthread_cond_t threshold_floor_;

int main(int argc, char **argv){

    numThreads = atoi(argv[1]);
    int level = atoi(argv[2]);

    marketValue = 100 * numThreads;
    //initialize personal stocks for threads
    stocks = (double *) malloc(sizeof(double) * numThreads);
    int i;
    for(i = 0; i < numThreads; i++) stocks[i] = 100;
    //initialize floor/ceiling
    double percent = (double) level / 100;

    double cap = marketValue * percent;
    ceiling = marketValue + cap;
    floor_ = marketValue - cap;

    //seed rand()
    srand(time(NULL));
    //create threads
    pthread_cond_init(&threshold_ceiling,NULL);
    pthread_cond_init(&threshold_floor_,NULL);

    int rc = pthread_create(&watchIncreaseThread,NULL,watchIncrease,NULL);
    assert(rc == 0);
    rc = pthread_create(&watchDecreaseThread,NULL,watchDecrease,NULL);
    assert(rc == 0);

    threads = (pthread_t *)malloc(sizeof(pthread_t) * numThreads);
    assert(threads != NULL);
    for(i = 0; i < numThreads; i++){
        int rc = pthread_create(&threads[i],NULL,update,(void *)i);
        assert(rc == 0);
    }

    int j;
    for(j = 0; j < numThreads; j++){
        pthread_join(threads[j],NULL);
    }

    return 0;
}

void *update(void *i){

    int index = (int)i;
    double max = 2;
    double val;

    while(1){
        int rc = pthread_mutex_lock (&lock);
        assert(rc == 0);
        val = max * ((double)rand()/(double)RAND_MAX - 0.5);
        stocks[index] += val;

        marketValue += val;
        pthread_cond_signal (&threshold_ceiling);
        pthread_cond_signal (&threshold_floor_);
        pthread_mutex_unlock(&lock);

    }

}

void *watchIncrease(){

    int rc = pthread_mutex_lock(&lock);
    assert(rc == 0);
    while(marketValue < ceiling){
        pthread_cond_wait(&threshold_ceiling, &lock);
    }
    printf("Market Up to %.2f\n",marketValue);
    int i;
    double sum = 0;
    for(i = 0; i < numThreads; i++){
        sum += stocks[i];
    }
    printf("Total Market Price of %d stocks: %.2f\n",numThreads,sum);
    for(i = 0; i < numThreads; i++){
        rc = pthread_cancel(threads[i]);
        assert(rc == 0);
    }
    pthread_cancel(watchDecreaseThread);
    pthread_mutex_unlock(&lock);
    pthread_exit(NULL);

    //exit(0);
}

void *watchDecrease(){

    int rc = pthread_mutex_lock(&lock);
    assert(rc == 0);
    while(marketValue > floor_){
        pthread_cond_wait(&threshold_floor_, &lock);
    }
    printf("Market Down to %.2f\n",marketValue);
    int i;
    double sum = 0;
    for(i = 0; i < numThreads; i++){
        sum += stocks[i];
    }
    printf("Total Market Price of %d stocks: %.2f\n",numThreads,sum);
    for(i = 0; i < numThreads; i++){
        rc = pthread_cancel(threads[i]);
        assert(rc == 0);
    }
    pthread_cancel(watchIncreaseThread);
    pthread_mutex_unlock(&lock);
    pthread_exit(NULL);
    //exit(0);

}

A: pthread_cancel is discouraged, instead the proper way of doing this is replacing while(1){ by while(!killed[index]){. Then, to kill a thread you set killed[index]. If you have C11 compiler, use http://en.cppreference.com/w/c/atomic/atomic_flag, otherwise you may need a pthread_mutex to protect the killed array.
Example: https://gustedt.wordpress.com/2012/01/22/simple-c11-atomics-atomic_flag/


text:
Q: Does $1.0000000000\cdots 1$ with an infinite number of $0$ in it exist? Does $1.0000000000\cdots 1$ (with  an infinite number of  $0$ in it) exist?

A: If a sequence $1.00000\dots $ is infinite it can't have an end $\cdots 0001$. Infinite means endless.

A finite sequence is a line of (mathematical) objects $a_0,a_1,a_2,\dots, a_n$. But it seems to be some disagreement what an infinite sequence is. At least I disagree.
Obviously, the object $a_k$ represent a function $k\mapsto a_k$ with ordered indices $k$, but could it be any function? Due to Wikipedia:
Most precisely, a sequence can be defined as a function whose domain is a countable totally ordered set, such as the natural numbers.
In that case a function $\mathbb N\cup\{\infty\}\rightarrow A$ (for some set $A$) is a sequence $a_0,a_1,a_2,\dots$ with a last element $a_\infty$, without an immediately preceding element in the sequence.
In my intuition and in my opinion any element in a sequence, except the first, has an immediately preceding element.
Latin: sequentia ("a following").
However, it's possible to generalize to "bi-sequences" $(S_1,S_2)$ when
$S_1=(1,0,0,\dots)$ is the initial sequence and $S_2=(\dots,0,0,1)$ is the termimal sequence, and define an arithmetic for "numbers" defined by bi-sequences as $(S_1,S_2)$.

A: First let me tell you that the idea that an infinite sequence "ends with something" is a solid idea. It's a perfectly natural one. The point is that the sequence is not indexed by $\Bbb N$, anymore, but rather by $\Bbb N\cup\{\infty\}$, where $\infty$ is another point, which lies after all the natural numbers.
The point is that an "infinite sequence" is a very general notion. People just often like to think about sequences which are indexed only using the natural numbers (with their natural ordering, that is). But as you will progress in your studies you might meet other objects which are indexed using other infinite sets.
And the reason people often limit themselves to sequences indexed by the natural numbers is that for the real numbers (and similar concepts), these sequences are enough. In this case, of the real numbers, we have that each real number can be defined as a limit of decimal digits, as others have explained, and therefore $1.\underbrace{000\ldots}_{\text{infinite }0\text{'s}}1$ is not a definition of a real number.
Note that this is not the limit of $1+(\frac1{10})^n$, either, which colloquially might be written as $1+(\frac1{10})^\infty$. That limit would be the limit of $1.1,1.01,1.001,\ldots$ and you can see that at no point in this sequence there is a number with infinitely many $0$'s written after it. And indeed this limit would be equal to $1$.
This is also different from the $0.999\ldots$ situation, since it is a sequence indexed by $\Bbb N$, which can be seen as the limit of its initial segments. Whereas a sequence indexed by $\Bbb N\cup\{\infty\}$ is not the limit of its initial segments, since none of them include information about the last digit.
So does it exist? Yes. It's just not a real number. It's a sequence of digits indexed by something other than $\Bbb N$.

Finally, Let me point out that as far as the concept of infinity goes in calculus, it's not quite unique. There is one infinity which signifies arbitrarily large values, another which signifies arbitrarily large negative values, there are infinities which ignore the sign at all, when you talk about a smooth function that can be differentiated infinitely many times, the infinity here is in fact "infinite sequence" rather than the infinities mentioned before, and it's a completely different type of infinity.
And there are other infinities which you might encounter, even in a calculus class.

A: In the real number system $\mathbb R$, there is no such number.
P.S. There is no such number in the complex numbers $\mathbb C$, either.
P.P.S. Sorry.

A: In the hyperreal number system which is an extension of the real number system you have infinite integers and the corresponding extended decimal expansions where it is meaningful to talk about digits at infinite rank (more precisely, rank defined by an infinite integer).  In this system your decimal makes sense.
Extended decimals were discussed in detail in an article by Lightstone:
Lightstone, A. H.
Infinitesimals.
Amer. Math. Monthly  79  (1972), 242–251.

A: As @Lehs said, infinite means endless - every integer value $n$ is finite, so if you assume infinite sequence of 'zero' digits, then whatever number $n$ you think, the $n$-th position holds digit 0. Consequently there's no space where you can append 'one'.

A: The bad news:
That string of symbols
$$
1.0\cdots01
$$
has no meaning as a real number.
Meaning or rather semantics would be a valid mapping from an infinite string $s$, e.g. from $\Sigma^\omega$ (link), to $\mathbb{R}$.
The string representation of a floating point real number in base $10$ by convention means e.g.
$$
(1.0\cdots)_{10} =
(\underbrace{d_0.d_1 d_2 d_3 \cdots }_{\mbox{string}})_{10} =
\underbrace{\sum_{k=0}^\infty d_k 10^{-k}}_{\mbox{real number}}
$$
Where would you like to add that last $1$ digit?
The good news:
It might be something else.
Of course you can define your own semantics and operations on the strings but you will most likely end up with something that behaves more or less differently from the real numbers (like finite IEEE floats and their operations are not the same as the full set of real numbers and the basic operations on it, but something very close).
And the ugly news:  $\tiny \mbox{(c) by Asaf Karagila}$
As fellow user Hyrkel noticed, that finite string I used
$$
[1] [.] [0] [.] [.] [.] [0] [1]
$$
to suggest an infinite string with two ends
(prefix "$1.$" and suffix "$1$") and
infinite many $0$ symbols in between is problematic too - interpreted as a string
already.
Is this a proper string? is it even a proper infinite string?
How would you be able to recognise it?
Next step would be to attach a meaning to it, preferably some number, but I will only argue on the above questions which are not simple already.
Computer scientists stick to mathematical machine models,
like the finite automaton or the Büchi automaton
to reason about strings.
These machines can either accept or reject a string
they are presented with.
Their recognition process resembles the process
of a sensor reading a linear tape or track from left to right.
Even the variants for infinite strings act like this.
The infinity here is not so much problematic because of it's sheer
size but rather because of it's dullness:
what reason should the automaton have to stop the recognition of
the infinite part and proceed with the finite suffix?
The recognizable infinite strings seem to be of the variant
one end finite, one end infinite. (Do not nail me on this)
I am not sure if a non-deterministic (multiple choices possible)
Büchi automaton that would
accept the string $1.0^\omega$ could be properly
extended to recognise $1.0^\omega 1$.
I would attempt it by adding another arc from the final state to itself which is accepting the final $1$ symbol. That would work to accept $1.0^\omega1$ but it would also still accept just $1.0^\omega$. That makes it not much useful, what I can not distinguish is practically the same.
The solution is probably another automaton that starts recognition simultaneously from both ends or some mapping which lists the infinite sequence alternating from both sides at once, something like
$$
(1 1) \,  (. 0) \, (0 0) \cdots
$$
this would resort to established structures but I am not aware of such approaches.

A: In real analysis, $$\lim_{n\rightarrow\infty}\left( 1+\frac{1}{10^n}\right )=1$$
Even if it does not mean anything to say "infinite number of zeros" in real analysis, we can suppose this number is equal to $1$.
But in the field of surreal numbers, it's not the same. This number exists and will be equals to $1+\frac{1}{\omega}$, if you consider the infinity number of zeros to be $\omega$.

A: Looking at the answers seems to exhibit a rather chaotic mixup of concepts.
Of course, the question is not uninvolved since it talks about whether a particular number representation "exists".  Obviously, in its informal manner, it exists or could not have been written down.  Since we are talking about calculus here, the next question would be whether some real number value can be associated with that loose description.  It would appear that it would mean something akin to
$$\lim_{n\to\infty} \left(1 + 10^{-n}\right)$$
It turns out that this number perfectly well exists and is the same as the real number $1$.  So far, so straightforward.
The really interesting thing is that the majority of answers diverge from this.  If you asked whether a number like $2-1$ exists, few people would deny its existence on the basis that its specification looks different from $+1$.  Or would refuse to acknowledge the existence of octal $10_8$ because it would be the same as $8_{10}$.
So given that the majority of answers look different, it would appear that the question is not as much about calculus as it is about number psychology.  Is this the same as numerology?
Next question.


text:
Q: How to use mysqli query instead of mysql_query without getting FATAL ERROR? I have change the mysql_query statement to mysqli as below
 $sqlordlod = "SELECT * FROM order_list
          WHERE user_id = '$user_id'
          ORDER by order_id LIMIT $offset, $rec_limit ";
 $result = $mysqli->query($sqlordlod);
 $countrw = $result->num_rows;
 echo $countrw;

DB connection file
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

Anyway, follow to the suggestions I have made the above modifications, but got:

Warning: mysqli::query() expects parameter 1 to be string, object given in /Applications/XAMPP/xamppfiles/htdocs/_/globe/ru/profile.php on line 487
Fatal error: Call to a member function fetch_array() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/_/globe/ru/profile.php on line 487

Below is line 487
while($rowld = $mysqli->query($result)->fetch_array())
{
// flip flop controling the tr class to change the color
if ($classchk ==3){
        $classchk =1;
    }
if ($classchk ==2){
  $classname = "alt";
}else{
  $classname = "none";

    }

A: num_rows is a property, not a method:
$countrw = $result->num_rows;
                            ^--- no function call

A: num_rows is a property not a method.
$sqlordlod = "SELECT * FROM order_list
              WHERE user_id = '$user_id'
              ORDER by order_id LIMIT $offset, $rec_limit ";
$result = $mysqli->query($sqlordlod);
$countrw = $result->num_rows;
echo $countrw;

Edit: something is really wrong with your code. I guess you would like to do the following:
while($rowld = $result->fetch_array())
{
// flip flop controling the tr class to change the color
if ($classchk ==3){
        $classchk =1;
    }
if ($classchk ==2){
  $classname = "alt";
}else{
  $classname = "none";

    }

A: Replace
 $result = $mysqli->query($sqlordlod);

with
$result = $mysqli->query($serverconnection,$sqlordlod);

Here $serverconnection is your db connection result
try this one
here is the easy and working code for counting the rows
$dbhost="localhost";
$dbusername="root";
$dbpassword="";
$dbname="test";

$con=mysqli_connect($dbhost,$dbusername,$dbpassword,$dbname);

/* check connection */
$sqlordlod = "SELECT * FROM tablename";
//$resultordlod = mysql_query($sqlordlod);
//$countrw = mysql_num_rows($resultordlod);
$result = mysqli_query($con, $sqlordlod);
// fetch the result row.
$countrw = mysqli_num_rows($result);
echo $countrw;


text:
Q: JavaFX 2: resizable rectangle containing text I want to display a rectangle that contains a text/label. For this purpose I created a stackpane and added a rectangle and a label to it. However the text/label is not centered correctly. It is placed outside of the rectangle (to the left). This is the code I am currently using:
createRectangle(String name) {
   pane = new StackPane();
   text = new Label(name);
   rect = new Rectangle();
   // bind rectangle width to text width and add 10
   rect.widthProperty().bind(text.widthProperty().add(10));
   rect.heightProperty().bind(text.heightProperty().add(10));

   // add to stackpane
   pane.getChildren().addAll(rect,text);

   // display stackpane
   getChildren().add(pane)
}

I have tried binding the xProperty() and yProperty() of the rectangle, changing the alignment of the stackpane (setAlignment(Pos.CENTER)) and other things, but without success.
When I use a fixed rectangle size (e.g. new Rectangle(30,30)) and do not use the bindings, the label is centered correctly within the rectangle. However, the rectangle's size needs to adjust depending on the label size:
// label is placed correctly in the center of the rectangle
createRectangle(String name) {
   pane = new StackPane();
   text = new Label(name);
   rect = new Rectangle(30,30);

   // add to stackpane
   pane.getChildren().addAll(rect,text);

   // display stackpane
   getChildren().add(pane)
}

A: For a Background Sized to the Label
Just use CSS directly on the Label, you don't need any other nodes.
Label label = new Label("Sally collects seashells on the seashore");
label.setStyle("-fx-background-color: coral; -fx-padding: 10px;");

The padding can be used to adjust the size of the rectangular background area around the label.

For a Resizable Background
You don't need a Rectangle node, put the label in a StackPane and set a background on the StackPane:
Label label = new Label("Sally collects seashells on the seashore");
StackPane centeredLabel = new StackPane(label);
centeredLabel.setStyle("-fx-background-color: coral;");

Executable sample
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class LabelBackground extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        Label label = new Label("Sally collects seashells on the seashore");
        StackPane centeredLabel = new StackPane(label);
        centeredLabel.setStyle("-fx-background-color: coral;");

        StackPane root = new StackPane(centeredLabel);
        root.setPadding(new Insets(10));

        stage.setScene(new Scene(root));
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

Note: Inline styles in this answer are just for easy demonstration purposes, best practice is to use a CSS stylesheet for CSS style definitions.

I also want to use other shapes (especially rounded rectangles and circles) instead of plain rectangles. Is this achievable by styling the stackpane or the label itself as proposed in your answer?

Yes, anything which derives from Region (which includes layout panes such as StackPane and Controls such as Label), can be styled pretty extensively via CSS.
To get a rounded background, you can use -fx-background-radius.
To get an arbitrary shaped background, you can use fx-shape, though you may find it tricky to position your text within the arbitrarily shaped background.
You can also write a shape in code and use bindings to make things fit inside it as you originally tried in your question.
If things need a lot of fine-tuning then you can subclass region and over-ride the layoutChildren method to perform precise layout calculations for all of the children inside that method (this is the way that most of the in-built JavaFX controls handle layouts in their skin classes).
Anyway, a seemingly simple question doesn't always have a simple answer, because there ends up lots of variations both in the way you can do things and many subtle differences in what you might want to do, such as how to handle wrapped text, insets, whether to elide the text beyond a minimum size, etc.
However, for the most common tasks of rectangular or rounded rectangular backgrounds, I'd just stick to using CSS styles directly on labels.  By using style sheets, you can easily completely change the app style for your labels.
Here is a more extensive, overkill sample:

LabelBackground.java
import javafx.application.Application;
import javafx.beans.binding.DoubleBinding;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;

public class LabelBackground extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        Pane starLabel = labelOnStyledBackground(
                "Practical Principles of Plain and Perfect Pronunciation.",
                "star-label"
        );

        StackPane labelOnResizableBackground = labelOnStyledBackground(
                "Sally collects seashells on the seashore",
                "resizable-background"
        );
        labelOnResizableBackground.setPrefHeight(60);

        Label squareLabel = createLabel(
                "Betty Botter bought a bit of butter.",
                "square-label"
        );

        Label roundedLabel = createLabel(
                "Peter Piper picked a peck of pickled peppers.",
                "rounded-label"
        );

        Node ellipticalLabel = createEllipticalLabel(
                "Round and round the rugged rock the ragged rascal ran.",
                "elliptical-label"
        );

        VBox root = new VBox(
                10,
                starLabel,
                labelOnResizableBackground,
                squareLabel,
                roundedLabel,
                ellipticalLabel
        );
        VBox.setVgrow(labelOnResizableBackground, Priority.SOMETIMES);
        root.setAlignment(Pos.TOP_CENTER);
        root.setPadding(new Insets(10));

        Scene scene = new Scene(root);
        scene.getStylesheets().add(
                LabelBackground.class.getResource(
                        "label-styles.css"
                ).toExternalForm()
        );
        stage.setScene(scene);
        stage.setTitle("Resize me!");
        stage.show();
    }

    private Label createLabel(String text, String styleClass) {
        Label label = new Label(text);
        label.getStyleClass().add(styleClass);

        return label;
    }

    private StackPane labelOnStyledBackground(String text, String styleClass) {
        Label label = new Label(text);
        StackPane container = new StackPane(label);
        container.getStyleClass().add(styleClass);

        return container;
    }

    private Group createEllipticalLabel(String text, String styleClass) {
        final double INSET = 20;

        Label label = new Label(text);

        Ellipse ellipse = new Ellipse();
        ellipse.getStyleClass().add("ellipse");

        DoubleBinding halfWidth  = label.widthProperty().divide(2).add(INSET);
        DoubleBinding halfHeight = label.widthProperty().divide(4).add(INSET);

        ellipse.radiusXProperty().bind(halfWidth);
        ellipse.radiusYProperty().bind(halfHeight);

        ellipse.centerXProperty().bind(halfWidth);
        ellipse.centerYProperty().bind(halfHeight);

        label.setLayoutX(INSET);
        label.layoutYProperty().bind(halfHeight.subtract(label.heightProperty().divide(2)));

        Group group = new Group(ellipse, label);
        group.getStyleClass().add(styleClass);

        return group;
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

label-styles.css
.root {
    -fx-font-size: 16px;
}

.rounded-label {
    -fx-background-color: cadetblue;
    -fx-padding: 10px;
    -fx-background-radius: 10px;
}

.square-label {
    -fx-background-color: plum;
    -fx-padding: 10px;
}

.star-label {
    -fx-background-color: gold;
    -fx-padding: 120px;
    /* shape courtesy of Smiffy's star place: http://www.smiffysplace.com/stars.html */
    -fx-shape: "M 0.000 20.000 L 23.511 32.361 L 19.021 6.180 L 38.042 -12.361 L 11.756 -16.180 L 0.000 -40.000 L -11.756 -16.180 L -38.042 -12.361 L -19.021 6.180 L -23.511 32.361 L 0.000 20.000";
}

.resizable-background {
    -fx-background-color: coral;
}

.elliptical-label .ellipse {
    -fx-fill: lightpink;
}

If you are super-keen for further samples, look at the way the QuoteMaker app handles styling of resizable label backgrounds.


text:
Q: iCloud Calender and task in Mozilla Thunderbird/Lightning Does anyone know how i can get the calender and tasks from iCloud to Mozilla Thunderbird/Lightning - and tey are editable?
I know how to make a public agenda in iCloud, but that agenda is read only.
I hope anyone can help ....

A: There is a German solution that has recently worked for me, while Ronny's link does unfortunately not work since I just do not get any responses from the server: https://www.nico-beuermann.de/blogging/archives/115-Zugriff-auf-iCloud-Kalender-mit-Thunderbird.html
You will need three ingredients for Thunderbird:
a. your calendar's server (especially, the number xx in pxx-caldav.icloud.com)
b. your user ID (dsid)
c. the calendar's UID (guid)
In short (and English):

*

*Logging in to your iCloud calendar in the browser is the first important step

You can either use Firefox' or Chrome's functionality to look at the network; I will continue with Chrome for this explanation.

*Press Ctrl + Shift + I and click on the Network tab; it might be that it is empty for now since logging might also start after pressing Ctrl + Shift + I; if it is empty, just reload having the network tab still open

*In my case, it was helpful to right-click on a column to additionally show the domain

*checking the domain or just hovering over the links, you can find the xx in pxx, this is your specific server; the remainder of the domain does not matter (information a)

*I then clicked on one entry with domain pxx-calendarws.icloud.com

*in the upcoming new sub-window, you can click on Headers and find dsid somewhere below under Query string parameters; alternatively, you can find it in the URL; dsid corresponds to your user id (information b)

*now, switch from "Headers" to "Reponse"; you might need to check multiple URL get lines to find one with the right response, but you will find a number of guid entries which correspond to your calendar IDs (information c)
Now, you have all three pieces of information. In Thunderbird with the Calendar plugin Lightning, now add a network calendar of type "CalDAV" (iCalendar will not work!). There, you can enter the following url with the pieces of information marked in bold:
https://pxx-caldav.icloud.com/dsid/calendars/guid
Et voìla. You will need to enter your credentials for iCloud. This has worked at the date of this post with Thunderbird 45.8.0 with Lightning 4.7.8.
Update 18 July 2017:
Apparently, sometime in June Apple has changed something with the system. You need to activate two-factor authentication now in order to create app-specific passwords. You can do that with any of your apple devices. Then, you should log in to your apple account. In the security area, you can generate some password. Use this one to login to your caldav in Thunderbird with your email address. This seems to work fine.
Without two-factor authentication, you cannot activate app-specific passwords. And without an app-specific password, CalDAV does not seem to be accessible anymore.
Update 05 September 2017: It seems that pGuid sometimes works but guid does not for the calendar ID. So, take care here.

A: After a lot of research i have found an solution.
This is provided by https://icloud.niftyside.com/
They have a php script, where you can fill in the credentials and the right CardDAV/Contacts servers, which you can add to Mozilla Thunderbird/Lightning


text:
Q: How to implement form authentication for metro apps c#,xaml? I am trying to develop a metro style app where I have to authenticate the user with his/her Live ID (ex gmail or Hotmail) using Form authentication .Can I do it in metro apps ?If so how to implement it and any specific sites where I can get code .

A: Have a look at this Single sign-on for apps and websites

Because Windows 8 enables users to sign in to their devices by using a
  Microsoft account, app developers can provide a single sign-on
  experience across Windows Store apps and companion websites.


text:
Q: Using large $\lambda$ value when the orginal one was suitable for Poisson Please read the question carefully to prevent unnecessary comments!
I know that the real value and poission distribution is getting closer and closer when $n$ is large and $p$ is small. Generally , books say that it is good to use poison when $\lambda < 7$ .
I wonder something such that there are some types of question :

On the average there are $6$ no-shows per airplane flight. If there are
$10$ flights scheduled, find the prob of $4$ no-shows

Solution: If there are $6$ no-shows per airplane flight , then there are $60$ no-shows for ten flights. Hence , our $\lambda$ is $60$ $$P(4)=\frac{(60)^4e^{-60}}{4!}$$

This is a classical Poisson distribution question. However , something stuck in my mind. In the beginning  , our $\lambda$ was $6$ , and it was suitable value for applying Poisson , but we used $\lambda =60 $ to apply Poisson for ten flight. My question is that if the real value and the result of Poisson get diverging for large $\lambda$ such as $\lambda > 7$  , is  using $\lambda =60$ a good idea ?


text:
Q: Cut 'binding' with Entity Data context after object retrieval I have a GridView that has its DataSource set to BindingSource, which in turn has its Datasource property set to a custom IEnumerable <SomeObject> variable. This custom object comes from Entity Framework's Data context. When I try to modify values from GridView I get an error 'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection error'.  This is understandable since I do these modifications when my data context is already disposed but is there a way to just store these changes in the IEnumerable  variable and disable it's 'binding' to that disposed data context?
Edit: To simplify,  If I declare a new List and set it as a DataSource to the upper mentioned BindingSource, then when updating the rows from GridView, I can see the changes propagated to this List object. But how to do the same when this object is a result of several queries in Data context of Entity Framework which seems to be 'attaching' some kind of remnant to the resulting object.
Here is the relevant code:
using (AmboliCardEntities context = new AmboliCardEntities(Globals.StrEntityConnecitonString))
                {

                    var transaction = context.tblTransactions.AsNoTracking().FirstOrDefault(a => a.GUID == gTransaction);
                    if (transaction != null)
                    {
                        var ret = new TransactionData
                        {
                            Transaction = transaction,

                            ConstantAccumulations = context.tblConstantAccumulations.AsNoTracking()
                                .Where(a => a.transactionid == gTransaction && a.removed == false).AsNoTracking().ToList(),

                            Cashbacks = context.tblCashbacks.AsNoTracking()
                                .Where(a => a.transactionid == gTransaction && a.removed == false).AsNoTracking().ToList(),

                            PurchasedProducts = context.tblPurchasedProducts.AsNoTracking().Include(a => a.tblProduct)
                                .Include(a => a.tblProduct.tblProductBrand)
                                .Include(a => a.tblProduct.tblProductBrand.tblProductCategory)
                                .Include(a => a.tblVehicle)
                                .Include(a => a.tblVehicle.tblVehicleTrim)
                                .Include(a => a.tblVehicle.tblVehicleTrim.tblVehicleModel)
                                .Include(a => a.tblVehicle.tblVehicleTrim.tblVehicleModel.tblVehicleMake)
                                .Where(x => x.transactionid == gTransaction)
                                .AsNoTracking()
                                .ToList()
                        };

                        var vehicles = context.tblVehicles.AsNoTracking().Include(x => x.tblVehicleTrim)
                            .Include(x => x.tblVehicleTrim.tblVehicleModel)
                            .Include(x => x.tblVehicleTrim.tblVehicleModel.tblVehicleMake)
                            .Where(a => a.cardid == transaction.cardguid)
                            .AsNoTracking()
                            .ToList();

                        return ret;

                    }

                }

A: I disabled the Lazy Loading of Entity Framework's data context using:
context.Configuration.LazyLoadingEnabled = false;

And that forced the data context to retrieve all the values at once. I would, however, like to hear an explanation as to why AsNoTracking() method did not work.


text:
Q: WebSocket Server https I'm new with websocket things. I tried to make a simple chat application, and i've followed ratchet hello world tutorial. I ran it locally with
'ws://localhost:8080'

It's works perfectly fine. I can chat via javascript console like the tutorials said. Now, i try to put it on my webserver https://some.domain.co/websocket. I've tried to do the same thing like
'ws://some.domain.co:8080'
'ws://some.domain.co:8080/websocket'
'ws://some.domain.co/websocket:8080'
'wss://some.domain.co:8080'
'wss://some.domain.co:8080/websocket'
'wss://some.domain.co/websocket:8080'

But none of them work. By browser still give error

WebSocket connection to 'wss://some.domain.co/' failed: Error during
  WebSocket handshake: Unexpected response code: 200

or

WebSocket connection to 'wss://some.domain.co:8080/' failed: Error in connection establishment: net::ERR_TIMED_OUT

I think i had something wrong with my url. Any advice? Thanks before
Edit
chatServer.php

require dirname(__DIR__) . '/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
include("Chat.php");

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ), 8080
);
$server->run();

Chat.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
   protected $clients;

public function __construct() {
    $this->clients = new \SplObjectStorage;
    echo "Server is Running\n";
}

public function onOpen(ConnectionInterface $conn) {
    // Store the new connection to send messages to later
    $this->clients->attach($conn);

    echo "New connection! ({$conn->resourceId})\n";
}

public function onMessage(ConnectionInterface $from, $msg) {
    $numRecv = count($this->clients) - 1;
    echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
        , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

    foreach ($this->clients as $client) {
        if ($from !== $client) {
            // The sender is not the receiver, send to each client connected
            $client->send($msg);
        }
    }
}

public function onClose(ConnectionInterface $conn) {

    $this->clients->detach($conn);

    echo "Connection {$conn->resourceId} has disconnected\n";
}

public function onError(ConnectionInterface $conn, \Exception $e) {
    echo "An error has occurred: {$e->getMessage()}\n";

    $conn->close();
}
}


text:
Q: How to increase scrolling performance of large JTable? The following is a rudimentary sample of scrolling with large amounts of data and 1 Renderer.
With 7,000 row and 10 columns, the slow performance is visible when you used the mouse to drag the scroll button up/down quickly. This is with the Renderer simply returning the same string.
If you edit the renderer in the example to uncomment the IF (and else if) statements which does extra work on the data in the first 3 columns, you will notice the performance get significantly worse as you move the scroll button up/down quickly.
//Remove these comments from the code.
//  if (vColIndex == 0)
//        setText("...
//  else if (vColIndex == 1)
//      setText("...
//  else if (vColIndex == 2)
//      setText("...

The following command was used in an attempt to improve performance :
scrollpane.getViewport().setBackingStoreEnabled(true);

Since the above is deprecated, the following command was used with all 3 available options but there still was no improvement.
  scrollpane.getViewport().setScrollMode(2);

Here is the actual code.
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class RendererTest
{
    static JTable table;
    TableColumn tcol;

  public static void main(String[] argv) throws Exception
  {
      JFrame frame = new JFrame("Creating a Custom Cell Reanderer!");
      frame.setSize(800, 800);

      JPanel panel = new JPanel();
      int rows = 7000;
      int cols = 10;
      Object data[][] = new Object[rows][cols] ;
      for (int i = 0; i<rows; i++)
      {
          for (int j=0; j<cols; j++)
          {
              data[i][j] = "Hello World";
          }
      }
      String columns [] = {"Colum 1","Column 2","Column 3","Column 4","Column 5",
              "Column 6","Column 7","Column 8","Column 9","Column 10"};
      DefaultTableModel model = new DefaultTableModel(data,columns);
      table = new JTable(model);
      JScrollPane scrollpane = new JScrollPane(table);
//    scrollpane.getViewport().setBackingStoreEnabled(true);
//    scrollpane.getViewport().setScrollMode(2);
//    System.out.println(scrollpane.getViewport().getScrollMode());
      scrollpane.getViewport().setScrollMode(2);
      table.setDoubleBuffered(true);
      scrollpane.setPreferredSize(new Dimension(700, 1000));
      scrollpane.setViewportView(table);

      panel.add(scrollpane);
      frame.add(panel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

    int vColIndex = 0;
    table.getColumnModel().getColumn(vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
    table.getColumnModel().getColumn(++vColIndex).setCellRenderer(new MyTableCellRenderer());
  }
}

class MyTableCellRenderer extends JLabel implements TableCellRenderer {
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int rowIndex, int vColIndex) {
    setText(value.toString());
//      if (vColIndex == 0)
//            setText("
??????????????
");
//      else if (vColIndex == 1)
//          setText("
??????????????
");
//      else if (vColIndex == 2)
//          setText("
???????????????????
");
    setToolTipText((String) value);
    return this;
  }
}

Are there any other built-in options to try?
How can you tell when the slower performance is expected and you are hitting max performance?
Are there any tools other than JVisualVM to help pinpoint the slowness?


text:
Q: Windows Server Shared Folder is Visible to 192.168.1.0 but not 192.168.2.0 I face an issue regarding file sharing between Windows computers over different sub-networks.
The network topology is as shown here:

There are two sub-networks which are connected together with PPPT by using two Mikrotik routers (please ignore the figure showing PPPoE).
The purpose is to make the Windows 2008 server (that is part of the 192.168.1.0 sub-network) accessible to all computers for file sharing.
So far, computers A and B are able to access the shared folders of the server.
Unfortunately, the shared folders of the server are not visible to computers C and D.
I would like to mention that computers A and B can ping computers C and D and vice versa even if they belong in different sub-networks.
Also, all computers can ping the Server.
So, even if all computers are visible to each other why can't computers C and D "see" the shared folders of the server?
All computers use Windows 10.
Please let me know if you need more information.
Thank you!

A: Dont have rep to comment..
Try enabling insecure guest logons in your GP restart and try that.
If you torch 192.168.1.3 on your mikrotik can you see the request reaching that machine?

A: The solution is the following given by user grawity:

Please define "see" more precisely. Are you trying to: a) use Windows
  network device discovery to automatically list computers with shared
  folders? b) directly connect to remote computers using their hostnames
  (\hostname\share)? c) directly connect to remote computers using
  their IP addresses (\192.168.1.3\share)?


text:
Q: Splitting the string at Enter key I'm getting the text from editbox and I'd want to get each name separated by enter key like the character string below with NULL characters.
    char *names = "Name1\0Name2\0Name3\0Name4\0Name5";

    while(*names)
    {
        names += strlen(names)+1;
    }

how would you do the same for enter key (i.e separated by /r/n) ? can you do that without using the std::string class?

A: Use strstr:
while (*names)
{
    char *next = strstr(names, "\r\n");
    if (next != NULL)
    {
        // If you want to use the key, the length is
        size_t len = next - names;

        // do something with a string here.  The string is not 0 terminated
        // so you need to use only 'len' bytes.  How you do this depends on
        // your need.

        // Have names point to the first character after the \r\n
        names = next + 2;
    }
    else
    {
        // do something with name here.  This version is 0 terminated
        // so it's easy to use

        // Have names point to the terminating \0
        names += strlen(names);
    }
}

One thing to note is that this code also fixes an error in your code.  Your string is terminated by a single \0, so the last iteration will have names point to the first byte after your string.  To fix your existing code, you need to change the value of names to:
// The algorithm needs two \0's at the end (one so the final
// strlen will work and the second so that the while loop will
// terminate).  Add one explicitly and allow the compiler to
// add a second one.
char *names = "Name1\0Name2\0Name3\0Name4\0Name5\0";

A: If you want to start and finish with a C string, it's not really C++.
This is a job for strsep.
#include <stdlib.h>
void split_string( char *multiline ) {
    do strsep( &multiline, "\r\n" );
    while ( multiline );
}

Each call to strsep zeroes out either a \r or a \n. Since only the string \r\n appears, every other call will return an argument. If you wanted, you could build an array of char*s by recording multiline as it advances or the return value of strsep.
void split_string( char *multiline ) {
    vector< char* > args;
    do {
        char *arg = strsep( &multiline, "\r\n" );
        if ( * arg != 0 ) {
            args.push_back( arg );
        }
    } while ( multiline );
}

This second example is at least not specific to Windows.

A: Here's a pure pointer solution
   char * names = "name1\r\nName2\r\nName3";
   char * plast = names;

   while (*names)
      {
      if (names[0] == '\r' && names[1] == '\n')
         {
         if (plast < names)
            {
            size_t cch = names - plast;
            // plast points to a name of length cch, not null terminated.
            // to extract the name use
            // strncpy(pout, plast, cch);
            // pout[cch] = '\0';
            }
         plast = names+2;
         }
      ++names;
      }

   // plast now points to the start of the last name, it is null terminated.
   // extract it with
   // strcpy(pout, plast);

A: Since this has the C++ tag, the easiest would probably using the C++ standard library, especially strings and string streams. Why do you want to avoid std::string when you're doing C++?
std::istringstream iss(names);
std::string line;
while( std::getline(iss,line) )
  process(line); // do process(line.c_str()) instead if you need to


text:
Q: APR (Apache Portable Runtime) 1.2.2 RegEx? Does APR 1.2.2 have regex support?  Any documentation or tutorials on using it?
The documentation sucks.  Like really bad.

A: Following is straight from the book   Writing Apache modules with Perl and C
regex_t *ap_pregcomp (pool *p, const char *pattern, int cflags);
    void ap_pregfree (pool *p, regex_t *reg);

Apache supports regular expression matching using the system library's regular expression
routines regcomp(), regexec(), regerror(), and regfree(). If these functions are not available, then Apache uses its own package of regular expression routines. Documentation for the regular expression routines can be found in your system manual pages. If your system does not support these routines, the documentation for Apache's regular expression package can be found in the regex/ subdirectory of the Apache source tree.
Regular expression matching occurs in two phases. In the first phase, you call
regcomp() to compile a regular expression pattern string into a compiled form. In the second
phase, you pass the compiled pattern to regexec() to match the search pattern against a source string. In the course of performing its regular expression match, regexec() writes the offsets of each matched parenthesized subexpression into an array named pmatch[]. The significance of this array will become evident in the soon.
Apache provides wrapper routines around regcomp() and regfree() that
make working with regular expressions somewhat simpler. ap_pregcomp() works like
regcomp() to compile a regular expression string, except that it automatically allocates
memory for the compiled expression from the provided resource pool pointer. pattern
contains the string to compile, and cflags is a bit mask of flags that control the type of
regular expression to perform. The full list of flags can be found in the regcomp() manual
page.
In addition to allocating the regular expression, ap_pregcomp() automatically installs a
cleanup handler that calls regfree() to release the memory used by the compiled regular
expression when the transaction is finished.
Speaking of which, the cleanup handler installed by ap_pregcomp() is ap_pregfree(). It frees
the regular expression by calling regfree() and then removes itself from the cleanup handler
list to ensure that it won't be called twice. You may call ap_pregfree() yourself if, for some unlikely reason, you need to free up the memory used by the regular expression before the cleanup would have been performed normally.
char *ap_pregsub (pool *p, const char *input, const char *source, size_t nmatch,
regmatch_t pmatch[ ])

After performing a regular expression match with regexec(), you may use ap_pregsub() to
perform a series of string substitutions based on subexpressions that were matched during the operation. This function uses the pmatch[] array, which regexec() populates with the start and end positions of all the parenthesized subexpressions matched by the regular expression. You provide ap_pregsub() with p, a resource pool pointer, input, a character string describing the substitutions to perform, source, the source string used for the regular expression match, nmatch, the size of the pmatch array, and pmatch itself.
input is any arbitrary string containing the expressions $1 through $9. ap_pregsub() replaces these expressions with the corresponding matched subexpressions from the source string. $0 is also available for your use: it corresponds to the entire matched string.
The return value will be a newly allocated string formed from the substituted input string.
The following example shows ap_pregsub() being used to replace the .htm and .HTM
filename extensions with .html. We begin by calling ap_pregcomp() to compile the desired
regular expression and return the compiled pattern in memory allocated from the resource
pool. We specify flags that cause the match to be case-insensitive and to use the modern
regular expression syntax. We proceed to initialize the pmatch[] array to hold two regmatch_t elements. Two elements are needed: the first which corresponds to $0 and the
second for the single parenthesized subexpression in the pattern. Next we call regexec() with the compiled pattern, the requested filename, the pmatch[] array, and its length. The last argument to regexec(), which is used for passing various additional option flags, is set to zero. If regexec() returns zero, we go on to call ap_pregsub() to interpolate the matched subexpression (the filename minus its extension) into the string $1.html, effectively replacing the extension.
ap_regmatch_t pmatch[2];
ap_regex_t *cpat = ap_pregcomp(r->pool, "(.+)\\.htm$",
    AP_REG_EXTENDED|AP_REG_ICASE);
if (ap_regexec(cpat, r->filename, cpat->re_nsub+1, pmatch, 0) == 0)
{
  r->filename = ap_pregsub(r->pool, "$1.html",
      r->filename, cpat->re_nsub+1,
      pmatch);
}

A: I agree, the documentation is terrible.
Looking here:
http://apr.apache.org/docs/apr-util/1.2/files.html
I'd venture a guess that no, there's no regex in 1.2.2.


text:
Q: If R is an integral domain then (R,+) is NOT isomorphic to (U(R),*) If $R$ is an integral domain, then $(R,+)$ is NOT isomorphic to $(U(R),*).$
That is, the additive group of an integral domain is not isomorphic to the group of units of the domain.
I tried to prove it, but I'm not very sure about the validity of my proof:
For the sake of argument, assume there is an isomorphism.
If $|R|=n, n \in \mathbb{N}$ then $|U(R)| \leq n-1$ because zero (identity element wrt addition) is not in the units since $0r=r0=0$ for every $r \in R.$
But this contradicts the fact that there is a bijection. Hence we conclude that there is no isomorphism in the case when $R$ is finite.
The following is false but I want to fix it and I don't know how.
Now assume $R$ is infinite, and suppose $\phi: (U(R),*) \rightarrow (R,+) $ is isomorphism.
Then $\phi(ab)= \phi(a)+\phi(b)$ and $\phi(1)=0$.
Therefore if $r \in (U(R),*),$ then so $r^{-1}$.
Let $r$ be arbitrary, then $\phi(1) = \phi(rr^{-1}) = \phi(r) + \phi(r^{-1}) = 0$
So $\phi(r) = - \phi(r^{-1}) \Rightarrow \phi(r) = \phi((r^{-1})^{-1}) $
Since $\phi$ is isomorphism, then $r=r^{-1}$.
But $r$ was arbitrary, and thence we get a contradiction.
I need to fix this
Another "proof" to the infinite case:
If the characteristic is zero:
$0 =\phi(1)=\phi(-1(-1))=\phi(-1)+\phi(-1)=2 \phi(-1) \Rightarrow  \phi(-1)=0$ but as $\phi$ is 1-1 then $-1=1$, contradiction.
If the characteristic is not zero I don't know what to do.

A: Let $\phi:R^*\to R$ be a group isomorphism. Let's prove that $1+1=0$. In fact, if $1+1\ne0$, then $0=\phi(1)=\phi((-1)^2)=(1+1)\phi(-1)$, and therefore $\phi(-1)=0=\phi(1)$. Therefore, $-1=1$ as well. Therefore $1+1=0$.
Then, for all $x\in R^*$, we have $\phi(x^2)=\phi(x)+\phi(x)=0$. Therefore $x^2=1$ for all $x\in R^*$. But this means $(x-1)(x+1)=0$, i.e. $(x-1)^2=0$. Therefore, $x=1$.
This means that $R^*=\{1\}$. Since the zero ring isn't a domain, $\lvert R\rvert\ge2>\lvert R^*\rvert$.