text:
Q: Find polynomial with specific constraints Say I am given a degree $d$, an upper and a lower limit $L_{min}$ and $L_{max}$ and a constant $k$ with $L_ {min} \leq k \leq L_ {max}$. How can I find a polynomial in the form of
$f(x)=k + a_1x^1+a_2x^2+a_3x^3 \ldots + a_dx^d$ for which the following properties hold:

*

*The polynomial degree must be $2 \leq d \leq 8$.

*For every $a_i$  there holds $L_{min} <= a_i \leq= L_{max}$

*For every $L_{min} \leq x \leq L_{max}$ every $L_{min} \leq f(x) \leq L_{max}$

A: Such a polynomial might not exist. For example, suppose $L_{min}=0$ and $L_{max}=1$ and $k=0$. Then for every polynomial $f(x)=k+a_1x+\ldots +a_dx^d$, one has $f(1)=k+a_1+\ldots+a_d \geq k+a_d \geq 2$, which contradicts condition (3).


text:
Q: Convert yyyymmdd string to Date class in R I would like to convert these dates with format YYYYMMDD to a Date class.
dates <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))

I tried:
dates <- as.Date(dates, "%Y%m%d")

And I get the following error:
Error in as.Date.default(dates, "%Y%m%d") :
  do not know how to convert 'dates' to class "Date"

What would be the correct way to set this format?

A: Classic R:
> start_numeric <- as.Date('20170215', format = '%Y%m%d');
> start_numeric
[1] "2017-02-15"
> format(start_numeric, "%Y%m%d")
[1] "20170215"

A: Use the lubridate package for an easy conversion:
date_test <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
date_test$Date <- ymd(date_test$Date)

date_test
        Date
1 2013-07-07
2 2013-07-06
3 2013-07-05
4 2013-07-04

A: You need to provide the Date column, not the entire data.frame.
R> as.Date(dates[["Date"]], "%Y%m%d")
[1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"

A: An extra conversion to characters works for me:
dates<-as.Date(as.character(dates),format="%Y%m%d")

Without the conversion the following error occurs:
dates<-as.Date(dates,format="%Y%m%d")
Error in as.Date.numeric(dates, format = "%Y%m%d") :
  'origin' must be supplied

Different error but this might help, works for POSIXct too, paste date and hours, format %Y%m%d%H

A: Instead of using brackets, you can use variable name:
dates <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
as.Date(dates$Date, "%Y%m%d")
[1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access the files present inside namespace to the outside in Linux Machine? I have linux system where i created network namespace "BLUE_NAME", requirement to access the /var/tmp files present in the BLUE_NAME network space to outside of the name space (Host Machine).Request you provide your suggestion.

A: Network namespaces itself create abstraction for network related components own list devices, routing tables, firewall rules.
Network namespace not affect filesystem.
But when we create namespace and run in namespace any utilities, this utilities will be works from user root, so we may run utils from needed to us user. <- Keep eye on this, I'm early run several times chrome* inside namespace and wondering where my settings.
Just try this:
#add namespace test
sudo ip netns add test

#run bash inside namespace, be carefull now you become root
sudo ip netns exec test /bin/bash

#create file in tmp "don't do this in scripts, in scripts use mktemp"
touch /tmp/test_from_namespace

Exit from bash inside namespace and destroy namespace
#destroy namespace
sudo ip netns del test

Then try as usual user list files in /tmp and you see created file


text:
Q: Puzzle: Need an example of a "complicated" equivalence relation / partitioning that disallows sorting and/or hashing From the question "Is partitioning easier than sorting?":

Suppose I have a list of items and an
  equivalence relation on them, and
  comparing two items takes constant
  time. I want to return a partition of
  the items, e.g. a list of linked
  lists, each containing all equivalent
  items.
One way of doing this is to extend the
  equivalence to an ordering on the
  items and order them (with a sorting
  algorithm); then all equivalent items
  will be adjacent.

(Keep in mind the distinction between equality and equivalence.)
Clearly the equivalence relation must be considered when designing the ordering algorithm.  For example, if the equivalence relation is "people born in the same year are equivalent", then sorting based on the person's name is not appropriate.

*

*Can you suggest a datatype and equivalence relation such that it is not possible to create an ordering?

*How about a datatype and equivalence relation where it is possible to create such an ordering, but it is not possible to define a hash function on the datatype that will map equivalent items to the same hash value.
(Note: it is OK if nonequivalent items map to the same hash value (collide) -- I'm not asking to solve the collision problem -- but on the other hand, hashFunc(item) { return 1; } is cheating.)
My suspicion is that for any datatype/equivalence pair where it is possible to define an ordering, it will also be possible to define a suitable hash function, and they will have similar algorithmic complexity.  A counterexample to that conjecture would be enlightening!

A: The answer to questions 1 and 2 is no, in the following sense: given a computable equivalence relation ≡ on strings {0, 1}*, there exists a computable function f such that x ≡ y if and only if f(x) = f(y), which leads to an order/hash function. One definition of f(x) is simple, and very slow to compute: enumerate {0, 1}* in lexicographic order (ε, 0, 1, 00, 01, 10, 11, 000, …) and return the first string equivalent to x. We are guaranteed to terminate when we reach x, so this algorithm always halts.

A: Creating a hash function and an ordering may be expensive but will usually be possible. One trick is to represent an equivalence class by a pre-arranged member of that class, for instance, the member whose serialised representation is smallest, when considered as a bit string. When somebody hands you a member of an equivalence class, map it to this canonicalised member of that class, and then hash or compare the bit string representation of that member. See e.g. http://en.wikipedia.org/wiki/Canonical#Mathematics
Examples where this is not possible or convenient include when somebody gives you a pointer to an object that implements equals() but nothing else useful, and you do not get to break the type system to look inside the object, and when you get the results of a survey that only asks people to judge equality between objects. Also Kruskal's algorithm uses Union&Find internally to process equivalence relations, so presumbly for this particular application nothing more cost-effective has been found.

A: One example that seems to fit your request is an IEEE floating point type. In particular, a NaN doesn't compare as equivalent to anything else (nor even to itself) unless you take special steps to detect that it's a NaN, and always call that equivalent.
Likewise for hashing. If memory serves, any floating point number with all bits of the significand set to 0 is treated as having the value 0.0, regardless of what the bits in the exponent are set to. I could be remembering that a bit wrong, but the idea is the same in any case -- the right bit pattern in one part of the number means that it has the value 0.0, regardless of the bits in the rest. Unless your hash function takes this into account, it will produce different hash values for numbers that really compare precisely equal.

A: As you probably know, comparison-based sorting takes at least O(n log n) time (more formally you would say it is Omega(n log n)).  If you know that there are fewer than log2(n) equivalence classes, then partitioning is faster, since you only need to check equivalence with a single member of each equivalence class to determine which part in the partition you should assign a given element to.
I.e. your algorithm could be like this:
For each x in our input set X:
    For each equivalence class Y seen so far:
        Choose any member y of Y.
        If x is equivalent to y:
            Add x to Y.
            Resume the outer loop with the next x in X.

    If we get to here then x is not in any of the equiv. classes seen so far.
    Create a new equivalence class with x as its sole member.

If there are m equivalence classes, the inner loop runs at most m times, taking O(nm) time overall.  As ShreetvatsaR observes in a comment, there can be at most n equivalence classes, so this is O(n^2).  Note this works even if there is not a total ordering on X.

A: Theoretically, it is alway possible (for questions 1 and 2), because of the Well Ordering Theorem, even when you have an uncountable number of partitions.
Even if you restrict to computable functions, throwawayaccount's answer answers that.
You need to more precisely define your question :-)
In any case,
Practically speaking,
Consider the following:
You data type is the set of unsigned integer arrays. The ordering is lexicographic comparison.
You could consider hash(x) = x, but I suppose that is cheating too :-)
I would say (but haven't thought more about getting a hash function, so might well be wrong) that partitioning by ordering is much more practical than partitioning by hashing, as hashing itself could become impractical. (A hashing function exists, no doubt).

A:  EDIT: This answer is wrong
 I am not going to delete it just because some of the comments below are enlightening
Not every equivalence relationship implies an order

As your equivalence relationship should not induce an order, let´s take an un-ordered distance function as relation.
If we get the set of functions f(x):R -> R as our datatype, and define an equivalence relation as:
f is equivalent to g if  f(g(x)) = g(f(x)  [commuting Operators][1]

Then you can't sort on that order (no injective function exists with the Real numbers). You just can't find a function which maps your datatype to numbers due to the cardinality of the function's space.

A: I believe that...

1- Can you suggest a datatype and equivalence relation such that it is
  not possible to create an ordering?

...it's possible only for infinite (possibly only for non-countable) sets.

2- How about a datatype and equivalence relation where it is
  possible to create such an ordering,
  but it is not possible to define a
  hash function on the datatype that
  will map equivalent items to the same
  hash value.

...same as above.

A: Suppose that F(X) is a function which maps an element of some data type T to another of the same type, such that for any Y of type T, there is exactly one X of type T such that F(X)=Y.  Suppose further that the function is chosen so that there is generally no practical way of finding the X in the above equation for a given Y.
Define F0=X, F{1}(X)=F(X), F{2}(X)=F(F(X)), etc. so F{n}(X) = F(F{n-1}(X)).
Now define a data type Q containing a positive integer K and an object X of type T.  Define an equivalence relation thus:
Q(a,X) vs Q(b,Y):
If a > b, the items are equal iff F{a-b}(Y)==X
If a < b, the items are equal iff F{b-a}(X)==Y
If a=b, the items are equal iff X==Y
For any given object Q(a,X) there exists exactly one Z for F{a}(Z)==X.  Two objects are equivalent iif they would have the same Z.  One could define an ordering or hash function based upon Z.  On the other hand, if F is chosen such that its inverse cannot be practically computed, the only practical way to compare elements may be to use the equivalence function above.  I know of no way to define an ordering or hash function without either knowing the largest possible "a" value an item could have, or having a means to invert function F.


text:
Q: npm install packagename --save-dev not updating package.json Are there simple or subtle reasons that package.json would not update after running a --save-dev? This is my command:
npm install modulename --save-dev
Run from the root of the project. The command succeeds, the new module shows up in the node_modules directory as expected. Help would be appreciated. I am using npm v 1.4.28
The entirety of my current package.json is:
{
    "name": "FooWeb",
    "version": "1.0.0",
    "description": "Foo Web",
    "devDependencies": {
        "gulp": "3.8.11",
        "gulp-jshint": "1.9.2",
        "gulp-concat": "2.5.2",
        "gulp-sass": "1.3.3",
        "gulp-sourcemaps": "1.4.0",
        "gulp-watch": "4.1.1"
    }
}

I do get warnings on install of a package that I have no repository field or README, but I think that is not related.

A: I had this problem as well, and it was driving me crazy.
What finally fixed it was running npm init. This added a bunch of stuff to my package.json, but afterwards --save-dev worked as expected. Even after I removed all the new stuff added by npm init, --save-dev still worked.

A: navigate to JSON file -> right click properties -> remove "read only" flag.

A: I ran into this recently, and figured out that for whatever reason it was Atom that was preventing the file from updating, even without the file being open.
I closed the editor, re-ran my npm install, opened the editor again and everything was as it should be.

A: Mustafah ELBanna's answer helped me, but i want to expand his answer for other newbies like myself. Please correct me if I miss something important.
If you remove the -g flag, the module is not installed globally for your machine, but only locally in your project. If you also want it to install globally, execute the same command again but now with -g instead of --save-devlike this :
npm install --save-dev [packagename]
npm install -g [packagename]
It seems to me that something might go wrong when calling -g and --save in one line.
But again, I'm new to this and I appreciate anyone who wants to improve/correct my answer.

A: I faced the same issue because nodemon was already installed globally.
I had to uninstall that first
npm uninstall -g nodemon
Then install it locally as a dev dependency
npm install --save-dev nodemon
The package.json file should then be updated. Sometimes your editor could also prevent the file from updating, so make sure to restart it if does not happen otherwise.

A: This can occur in VSCode (and other editors) if you have your package.json open and you've made changes without saving.
The file was being updated by npm on disk but the IDE wasn't auto reloading it to avoid a conflict.
So the solution was to just close and reopen package.json.

A: I had the -g flag there, when I removed it, it worked as expected ...

A: I tried all the commands stated in above answers but got success on installing npm-upgrade package.
npm i -g npm-upgrade then
npm-upgrade

A: I was trying to install the gruntjs using
    "npm install --save grunt-sass" but the package.json won't update
I did everything mentioned above but no luck. But funny thing is if i try adding a package say "underscore (npm install --save underscore)" the son gets updated. I am not sure if this is a problem with the nam as such. I did install as a super user.

A: There was a syntax error in my package.json that was causing this for me!

A: For me the issue was i copied the command from notepad++ it  may have had special chars in there or it was the spaces, and it was not updating my package.json.
e.g. did not work; npm install --save debug   pug  jwt-simple   method-override   mongoose
Make sure when you install,  you clean up the command line, e.g. any spaces between each module, because there might be special chars in there as well depending on your encoding.
When i corrected it to this it worked.
npm install --save debug pug jwt-simple method-override mongoose
Also, please make sure the package.json isn't opened in an editor when you run the command, because not all editors handle this gracefully.

A: After I used express generator I installed some packages with --s and none of them added to package.json.
Then I deleted the package.json and run npm init and all of them added without having to install again

A: I have an .npmrc file that uses an npm api built in-house to fetch packages. My issue was that I was not connected to my company's VPN.

A: The only way I was able to solve this was by using npm install --save-dev moduleName instead of npm install moduleName --save-dev. Using npm install moduleName --save works fine for me, though. Only when I use --save-dev, I have to put it before the moduleName. I hope this helps anyone.

A: You may first want to check your config (npm config ls command or ~/.npmrc file).
I had link=true.
In version 5.5.1, this option seems to be ignored when --save is active.
Given that --save-dev supersedes --save, the link mode is active again.
So for me things happens as if --save overrided --link which in turn overrided --save-dev.

A: I had the same problem. When i installed some package, it was not shown on the package.json. So then I deleted the package.json file and ran npm init again. After that it was working and the packages I installed before was also there under dependencies.

A: Removing the dependency from devDependencies in package.json file and installing again using only --save worked for me

A: With the accepted answer still my problem not resolve, then I try to change syntax position
Previously I am using the following command to install the module to devDependencies
npm i --save-dev moduleName

Then I toggle the position of moduleName and --save-dev and the moduleName successfully added in the package.json file
npm i moduleName--save-dev

Then the the package.json file updated with the moduleName.

A: This happened to me on Intellij
For anyone else having this issue, did you copy your project from an existing project?
If so, close Intellij and delete the .idea folder. (You can delete node_modules too get a fresh start)
Open the project again and this will be resolved.

A: Just wanted to add another possible answer that proved to be the solution for me.
Verify whether you are in the directory of your angular project. I wasn't and hence the changes were not getting reflected in my package.json file.

A: It can happen if you are not running the command from the package.json directory.
Will happen if you are placed in folder Project instead of Project\ClientApp for example.
You will notice that you only get a package-lock.json in the wrong location if this happens.


text:
Q: How to add image for buttons in flutter I am trying to add image for buttons in flutter like below the image. Here i have used ElevatedButton. So How to set background image for the ElevatedButton. I do not know how to add image for it. If anyone know please help to find the solution.
  child:SingleChildScrollView(
        child: Wrap(
          alignment: WrapAlignment.center,
          runSpacing:  20.0, // Or more
          spacing: 20, // Or more
          children: [
            const SizedBox(
              height: 520,
            ),
            SizedBox(
                width: double.infinity, // <-- Your width
                height: 50, // <-- Your height

            ),
            SizedBox(
                height: 50, // <-- Your height
                child: ElevatedButton(
                  onPressed: () {
                    onSignIn(context);
                  },
                  style: ElevatedButton.styleFrom(
                      primary: Color(0xff557de3),
                      shape: StadiumBorder()

                  ),
                  child: const Text(
                    "GMAIL",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                        fontWeight: FontWeight.bold
                    ),
                  ),
                ),
            ),
            SizedBox(
                height: 50, // <-- Your height

                child: ElevatedButton(
                  onPressed: () {
                    //validateForm();
                  },
                  style: ElevatedButton.styleFrom(
                      primary: Color(0xff557de3),
                      shape: StadiumBorder()

                  ),
                  child: const Text(
                    "Phone",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                        fontWeight: FontWeight.bold
                    ),
                  ),
                ),// Button
            ),
          ],
        ),
      ),

A: You can use:
ElevatedButton.icon(
                onPressed: (){},
                icon: Icon(Icons.phone),
                label: Text("hello"),
              ),

A: You can add image from asset:
ElevatedButton(
  onPressed: () {},
  child: Image.asset('your_asset_path')
)

Or you can add network image:
ElevatedButton(
  onPressed: () {},
  child: Image.network('your_image_url_path')
)

Or you can create your custom button:
GestureDetector(
  onTap: () {},
  child: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('your_asset_image_path'),
      ),
    ),
  )
)

A: You can use gestures detector
     GestureDetector(
          onTap: () {
            debugPrint('The image button has been tapped');
          },
          child: SizedBox(
            width: 300,
            height: 100,
            child: Image.network(
              'https://picsum.photos/250?image=9',
              fit: BoxFit.cover,
            ),
          ),
        ),

or use icon button
          IconButton(
          splashRadius: 100,
          iconSize: 200,
          icon: Ink.image(
            image: const NetworkImage(
                'https://picsum.photos/250?image=9'),
          ),
          onPressed: () {
            // do something when the button is pressed
            debugPrint('Hi there');
          },
        ),

A: Instead of using the ElevatedButton, have you tried IconButton, GestureDetector, InkWell, InkResponse and Material?
 IconButton(
        splashRadius: 100, // optional
        onPressed: {YOUR_LOGIC_COMPONENT}
        icon: Container(
           child : {YOUR_WIDGET},
       ),
      ),

or
GestureDetector(
  child: SizedBox(child: {YOUR_WIDGET}),
  onTap: {YOUR_LOGIC_COMPONENT},
);

or
InkWell(
  child: CircleAvatar(child: {YOUR_WIDGET}),
  onTap: {YOUR_LOGIC_COMPONENT},
);

A: You can use MaterialButton and customize it according to your need.
 MaterialButton(
        padding: EdgeInsets.all(8.0),
        textColor: Colors.white,
        splashColor: Colors.red,
        elevation: 8.0,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(''), //some asset image
                fit: BoxFit.cover),
          ),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: SizedBox(),
          ),
        ),
        // ),
        onPressed: () {
          print('Tapped');
        },
      ),


text:
Q: Booting Kali Linux On To A Windows 8.1 Tablet~ I am having some trouble booting kali onto my tablet, now my goal is a simple portable penetration testing machine that I can carry on the go.
hmm where to start.
Ok so I have created the bootable usb it has kali on it, now windows 8.1 tablet is awkward and so I can't do the regular f2 on start up and go to the BIOS, instead I have to go to settings in the tablet and hit "change advanced start-up options" so then it restarts the tablet and prompts me with the following options
Continue
Use a Device (usb drive,network connection or windows recovery cd)
TroubleShoot
So the first thing i thought well use a device of course :) then it prompts me with
EFI USB DEVICE
so then I click this and it reboots, it then attempts to boot but then it says
"system doesn't have any usb boot option. Please select another in boot manager menu"
hmm so I assume either my machine is not capable of doing this or I need to disable something (I have disable quick boot already).
so I go all the way back to the options from before which were
Continue,
Use a Device (usb drive,network connection or windows recovery cd),
TroubleShoot
I click trouble shoot and decide to enter advanced options - UEFI Firmware Settings, then it restarts and provides the following options.
Continue
Boot Manager
Device Management
Boot From File
Secure Boot Option
SCU
looked at EFI Boot Order comes up with
windows boot manage
Internal EFI Shell
Ive tried all options but no success :(
Any assistance would be greatly appreciated.
Thanks
(quick Edit: I also receive this message when attempting to boot directly from the ISO file.
this program does not support windows 6.2.9200 sp0 yet)

A: Put your Kali Live USB disk in the USB 3 port on the Surface Pro, and head back to the Settings menu on the Charm Bar. Navigate back to the General PC settings and boot into Advanced Startup. Tap the icon with the USB stick and the DVD labeled Use a Device one the Surface has booted into the Advanced settings.
From here, you will be presented with a list of available boot options that are currently detected. Your USB disk will be clearly labeled in the list, and when you tap on the icon for your drive the Surface will reboot. From this point, you will no longer be in Windows, as you will be booting from the USB drive.
When the Surface reboots, you'll be greeted by impossibly small white text on a black background. The GRUB menu is prompting you to either install Kali linux or boot from the Live USB and try it out for yourself before you install. As a rule, you should always try it out before you blow away your perfectly functional OS.
Personally I do not recommend kali linux as a starting operating system. Try using mint etc. The same process will work


text:
Q: Create github site/custom page/multiple project How to host sub project/another webapp on GitHub pages in a single account. I mean more than one. For ex: By default it is username.github.io but how can I host multiple like username.github.io/site2,username.github.io/site3, username.github.io/site4

A: https://help.github.com/articles/user-organization-and-project-pages/
Are you using "User Pages"? There is also "Project Pages" that can do exactly what you are looking for.
Say you have a repo my_repo, you can have a page with address http(s)://username.github.io/my_repo. Unlike User Pages repo(username.github.io), you may not want to use your master branch for Project Page. you have a couple more options - using only docs directory in your master branch, or use gh-pages branch.
This link kindly guides how to use.


text:
Q: AppLocalizations without context in flutter I want to use
AppLocalization.of(context)!.home,

without context. I'm using this in my class model where there's no context.
Here's my class:
class MenuItems {

 static const home = MenuItem('Home',Icons.home);
 static const frequentQuestion = MenuItem('Frequent Questions', Icons.question_answer);

 static const all = <MenuItem>[
      home,
      frequentQuestion,
 ];
}

A: I have solved this issue by
declaring variable global like
BuildContext? kAppcontext

Then I initialized in main.dart under build
now wherever I need it I used it as
 static const frequentQuestion = MenuItem(AppLocalizations.of(kAppcontext!)!.home,Icons.home);


text:
Q: How to resolve external domain names using MaraDNS in windows 7 I have installed maradns in windows 7 machine, I have configured it, It can able to handle internal requests, But not external ones
marac file
ipv4_bind_addresses = "127.0.0.1"
timestamp_type = 2
random_seed_file = "secret.txt"

csv2 = {}
csv2["myapp.com."] = "db.lan.txt"

upstream_servers = {} # Initialize dictionary variable
upstream_servers["."] = "8.8.8.8, 8.8.4.4"

db.lan.txt
private.%       192.168.1.21 ~
blog.%          192.168.1.16 ~

For external requests, its giving me the below error
C:\Program Files\maradns-2-0-06-win32>askmara.exe Agoogle.com.
# Querying the server with the IP 127.0.0.1
# Remote server said: REFUSED
# NS replies:
# AR replies:

For internal requests, Its working fine as below
C:\Program Files\maradns-2-0-06-win32>askmara.exe Aprivate.myapp.com.
# Querying the server with the IP 127.0.0.1
# Question: Aprivate.myapp.com.
private.myapp.com. +86400 a 192.168.1.21
# NS replies:
#myapp.com. +86400 ns synth-ip-7f000001.myapp.com.
# AR replies:
#synth-ip-7f000001.myapp.com. +86400 a 127.0.0.1

And when i start the server, I am getting a prompt with a warning as well

How to resolve this issue.

A: i had the same problem.. fixed it by replacing the latest version with the version 1.4..
after that the only i did was run the mkSecretTxt.exe to create the secret.txt file and configured the mararc file like this:
this is my current mararc file:
# Win32-specific MaraRC file; this makes a basic recursive DNS
# server.

hide_disclaimer = "YES"
ipv4_bind_addresses = "127.0.0.1"
recursive_acl = "127.0.0.1/8"
timestamp_type = 2

csv2 = {}
csv2["local.com."] = "db.lan.txt"

# This is insecure until the secret.txt file is edited
random_seed_file = "secret.txt"

upstream_servers = {}
upstream_servers["."] = "208.67.222.222,208.67.220.220"

db.lan.txt
% 192.168.1.33 ~

As you can see i've used the openDNS servers, if your still get the error try them as well.
http://www.opendns.com/support/article/105
cheers

A: For anyone following along with this, it seems the current solution as of MaraDNS > 2.0 is to use MaraDNS in conjunction with the included Deadwood recursive server to be able to handle both local and external resolution.  I was able to get this working on my Windows 10 machine with the following configs...
Assume that the Windows machine's IP address is 192.168.1.2
In the MaraDNS mararc file:
ipv4_bind_addresses = "127.0.0.1"
timestamp_type = 2
random_seed_file = "secret.txt"

csv2 = {}
csv2["mylocalnet.com."] = "db.lan.txt"

In the db.lan.txt file:
% 192.168.1.XXX ~

And in the Deadwood dwood3rc.txt config file:
upstream_servers = {}
upstream_servers["."]="8.8.8.8, 8.8.4.4"
upstream_servers["mylocalnet.com."]="127.0.0.1"

bind_address="192.168.1.2"

recursive_acl = "127.0.0.1/16, 192.168.1.1/24"

# By default, for security reasons, Deadwood does not allow IPs in the
# 192.168.x.x, 172.[16-31].x.x, 10.x.x.x, 127.x.x.x, 169.254.x.x,
# 224.x.x.x, or 0.0.x.x range.  If using Deadwood to resolve names
# on an internal network, uncomment the following line:
filter_rfc1918 = 0

You could potentially set up multiple machines to act as independent servers, but my config above was particular in that in enabled me to run both servers on the same machine.  You can see that in the Deadwood config, I'm using Google's DNS servers to handle all upstream requests with the exception of mylocalnet.com. which gets forwarded to localhost and handled by MaraDNS.
From here, you just need to launch both programs and point DNS to 192.168.1.2.  Should be good to go!


text:
Q: R: transforming specific rows into columns I have quite messy data imported from json file, it looks like this:
raw_df <- data.frame(text = c(paste0('text', 1:3), '---------- OUTCOME LINE ----------', paste0('text', 4:6), '---------- OUTCOME LINE ----------'),
                              demand = c('cat1', rep('', 2), 'info', 'cat2', rep('', 2), 'info2')
                     )

raw_df
                                text demand
1                              text1   cat1
2                              text2
3                              text3
4 ---------- OUTCOME LINE ----------   info
5                              text4   cat2
6                              text5
7                              text6
8 ---------- OUTCOME LINE ----------  info2

(BTW, ---------- OUTCOME LINE ---------- is the actual string that I have in text column)
I want to tidy it up so that it has the following format:
final_df
                  text demand outcome
1 text1. text2. text3.   cat1   info1
2 text4. text5. text6.   cat2   info2

What would be the quickest and most efficient way to do this? thanks for the tips.

A: A dplyr & tidyr solution:
raw_df %>%
    mutate(outcome = demand,
           demand = replace(demand, demand == '', NA),
           outcome = replace(outcome, outcome == '', NA),
           outcome = gsub("^cat\\d+", NA, outcome)) %>%
    fill(demand) %>%
    fill(outcome, .direction = "up") %>%
    filter(!grepl("-----", text)) %>%
    group_by(demand, outcome) %>%
    summarize(text = gsub(",", "\\.", toString(text))) %>%
    select(text, everything())

*

*fix up the text to display as desired, swap out blanks for NAs, and prep the outcome column.

*fill the demand column in the default down direction, and the outcome column in an up direction.

*filter out the  ----- OUTCOME LINE ------ based upon its hyphens.

*generate the group_concat for the text column, and then swap the default , out with ..

*select the columns into the desired sequence.

# A tibble: 2 x 3
# Groups:   demand [2]
                 text demand outcome
                <chr> <fctr>   <chr>
1 text1. text2. text3   cat1    info
2 text4. text5. text6   cat2   info2

A: Here we create a logical index using 'grepl' based on the presence of - in the 'text' column, subset the 'raw_df' to remove those rows, create a grouping column by getting cumulative sum of 'indx', aggregate to paste the 'text' column grouped by 'demand' after replacing the '' with NA and using na.locf to fill the non-NA previous values.  Then, create the 'outcome' from the 'demand' by subsetting with 'indx'
indx <- grepl("-", raw_df$text)
transform(aggregate(text~demand, transform(raw_df[!indx,],
  demand = zoo::na.locf(replace(demand, demand=="", NA))), toString),
    outcome = raw_df$demand[indx])
#  demand                text outcome
#1   cat1 text1, text2, text3    info
#2   cat2 text4, text5, text6   info2

Or this can be done with data.table
library(data.table)
setDT(raw_df)[demand == "", demand := NA][!indx, .(text= paste(text, collapse='. ')),
          .(demand = zoo::na.locf(demand))][, outcome := raw_df$demand[indx]][]


text:
Q: Do pre-processor directives protect server code from the client? I'm developing a client-server library. Some of the classes can be used by either the client or the server but are executed differently and yield slightly different results for each. As well, the server code may contain additional methods that will not be called from the client build.
A class may look like this:
public class StuffDoer {

    public void DoStuff(object msg)
    {
        ServerDoStuff(msg);
        ClientDoStuff(msg);
    }

    [Conditional("SERVER")]
    private void ServerDoStuff(object msg)
    {
        // Do secret server stuff...
    }

    [Conditional("CLIENT")]
    private void ClientDoStuff(object msg)
    {
        // Do client sutff...
    }

    [Conditional("SERVER")]
    public void DoCoolStuff(object msg)
    {
        // server does cool stuff...
    }

}

I've read that the Conditional attribute still compiles the code and would therefore be in the build, unlike pre-processor directives which would completely remove the code and not even compile it.
I'm concerned that a dishonest client may hack the product by unobfuscating the source code and figure out how the server works.
Are my fears unfounded or would I need to place pre-processor directives in order to hide the source code?

A: According to the documentation:

Applying ConditionalAttribute to a method indicates to compilers that
  a call to the method should not be compiled into Microsoft
  intermediate language (MSIL) unless the conditional compilation symbol
  that is associated with ConditionalAttribute is defined.

When you compile with CLIENT defined, the code to call a method marked with SERVER will not be present in the final assembly. But the code for the method will be present. You cannot achieve what you need in this way.

A: When "SERVER" is not defined, The method be marked as "SERVER" will always compile to the final assembly but all of callings to the method will be removed.
This is code
This is decompiled result


text:
Q: how to run multiple jobs using spring batch as of now i am running spring batch with single job. then now i want to run multiple jobs which is different to each other means different functionality.
in my configuration file i configured two jobs with different id and different names.
now i have to run those jobs. can you please tell me how can i run.
here my doubt is
in my java class i have written this code for run the batch.
 @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;

CompositeWriter compositeWriter=new CompositeWriter();
            JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
            Long startTime=System.nanoTime();
            JobExecution execution = jobLauncher.run(job, jobParameters);

for other job how can i call the run method of jobLauncher.
and my  configuration file is
<bean id="pagingItemReader" class="com.tcs.UserRowMapper">
    </bean>

     <job id="testJob" xmlns="http://www.springframework.org/schema/batch">
        <step id="step1">
            <tasklet>
                <chunk reader="pagingItemReader" processor="testApp" writer="itemWriter"
                    commit-interval="1" />
            </tasklet>
        </step>
    </job>
     <job id="testJob2" xmlns="http://www.springframework.org/schema/batch">
        <step id="step2">
            <tasklet>
                <chunk reader="itemReaderForNotification" processor="processforNoticeHeader" writer="itemUpateForNoticeHeader"
                    commit-interval="1" />
            </tasklet>
        </step>
    </job>

A: Your posted code seems incomplete; but you can just get the job from the config by its id, no ? Something like this :
ApplicationContext context = new ClassPathXmlApplicationContext(config);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job1 = (Job) context.getBean("testJob");
Job job2 = (Job) context.getBean("testJob2");

JobExecution execution1 = jobLauncher.run(job1, new JobParameters());
System.out.println("Exit Status : " + execution1.getStatus());
JobExecution execution2 = jobLauncher.run(job2, new JobParameters());
System.out.println("Exit Status : " + execution2.getStatus());


text:
Q: A better approximation of $H_n $ I'm convinced that
$$H_n \approx\log(n+\gamma) +\gamma$$ is a better approximation of the $n$-th harmonic number than the classical $$H_n \approx \log(n) +\gamma$$
Specially for small values of $n$. I leave some values and the error:

Just to make things clearer, I calculate the value between two numbers as follows.
Say $n$ is the optimal and $a$ is the apporximation, then $E = \frac{n-a}{n}$. $L_1$ stands for my approximation and $L_2$ for the classical one, and the errors $E_2$ and $E_1$ correspond to each of those (I mixed up the numbers).
It is clear that this gives an over estimate but tends to the real value for larger $n$.
So, is there a way to prove that the approximation is better?

NOTE: I tried using the \begin{tabular} environment but nothing seemed to work. Any links on table making in this site?

A: The true approximation, from the Euler-Maclaurin formula, is
$$H_n = \ln n + \gamma + 1/2n + O(1/n^2).$$
Your expansion is
$\ln (n+\gamma) + \gamma
= \ln \ n + ln(1+\gamma/n)+\gamma
= \ln \ n + \gamma + \gamma/n + O(1/n^2)
$.
Since $\gamma = .577...$, your error is
about $.077/n$,
which is better by .077/.5 ~ .154 ~ 1/6
which explains the table.
I see another answer has just been posted.
If it differs much from mine, I will be surprised.

A: Actually, you do better still with $ H_n \approx \gamma + \log \left( n + \frac{1}{2} \right),$ with
$$  H_n =  \gamma  + \log \left( n + \frac{1}{2} \right)   + O \left( \frac{1}{n^2} \right). $$
As you can see from the other answers, this minimizes the error among approximations of type $H_n \approx \gamma + \log \left( n + c \right)$ with constant $c,$ by erasing the $\frac{1}{n} $ error term.
A fuller version of the asymptotic above is just
$$  H_n =  \gamma  + \log \left( n + \frac{1}{2} \right)  + \frac{1}{24 \left( n + \frac{1}{2} \right)^2} - \frac{7}{960 \left( n + \frac{1}{2} \right)^4} + \frac{31}{8064 \left( n + \frac{1}{2} \right)^6} - \frac{127}{30720 \left( n + \frac{1}{2} \right)^8} + O \left( \frac{1}{n^{10}} \right). $$

A: The asymptotic expansion of the Harmonic numbers $H_n$ is given by
$$\log n+\gamma+\frac{1}{2n}+\mathcal{O}\left(\frac{1}{n^2}\right).$$
The Maclaurin series expansion of the natural logarithm tells us $\log(1+x)=x+\mathcal{O}(x^2)$, and we can use this in your formula by writing $\log(n+\epsilon)=\log n+\log(1+\epsilon/n)$ and expanding:
$$\log(n+\gamma)+\gamma=\log n+\gamma\;\;\;+\frac{\gamma}{n}+\mathcal{O}\left(\frac{1}{n^2}\right).$$
Your approximation is asymptotically better than the generic one because the $\gamma=0.577\dots$ in its expansion is closer to the true coefficient $\frac{1}{2}$ than the illicit coefficient $0$ in the generic formula given by the usual $H_n\sim \log n +\gamma+0/n$. This also explains why it is asymptotically an over estimation.

As marty said in his answer, the expansion comes from the Euler-Maclaurin formula:
$$\sum_{n=a}^b f(n)=\int_a^b f(x)dx+\frac{f(a)+f(b)}{2}+\sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}\left(f^{(2k-1)}(b)-f^{(2k-1)}(a)\right).$$
Here we let $a=1,b=n$ (rewrite the index to a different letter) and $f(x)=1/x$.


text:
Q: Linux clock loses 10 minutes every week One of my linux server's clock loses 10 minutes every now and then, nearly every week. I update the time so it stays correct, and although it doesn't really bother me, i'd like to fix it.
I've been searching around a bit. Nothing can be responsible in the crontab, and i can't find any related message in the logs.
Some people seem to use ntp to fix that kind of issue, but i'd prefer not to use an unecessary component on it.
Uname result :
Linux unis-monitor 2.6.32-5-686 #1 SMP Mon Feb 25 01:04:36 UTC 2013 i686 GNU/Linux
Cat message :
cat messages
Jul 14 06:25:06 unis-monitor rsyslogd: [origin software="rsyslogd" swVersion="4.6.4" x-pid="882" x-info="http://www.rsyslog.com"] rsyslogd was HUPed, type 'lightweight'.
Jul 15 06:25:05 unis-monitor rsyslogd: [origin software="rsyslogd" swVersion="4.6.4" x-pid="882" x-info="http://www.rsyslog.com"] rsyslogd was HUPed, type 'lightweight'.

Cat syslog
cat syslog
Jul 15 06:25:05 unis-monitor rsyslogd: [origin software="rsyslogd" swVersion="4.6.4" x-pid="882" x-info="http://www.rsyslog.com"] rsyslogd was HUPed, type 'lightweight'.
Jul 15 06:39:01 unis-monitor /USR/SBIN/CRON[15272]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete)
Jul 15 07:09:01 unis-monitor /USR/SBIN/CRON[15465]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete)
Jul 15 07:17:01 unis-monitor /USR/SBIN/CRON[15521]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Jul 15 07:39:01 unis-monitor /USR/SBIN/CRON[15662]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete)
Jul 15 08:09:01 unis-monitor /USR/SBIN/CRON[15855]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete)
Jul 15 08:17:01 unis-monitor /USR/SBIN/CRON[15911]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Jul 15 08:39:01 unis-monitor /USR/SBIN/CRON[16052]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete)
Jul 15 09:09:01 unis-monitor /USR/SBIN/CRON[16273]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete)

So if you have any clue of where to look or what i could use to monitor those date change ?
Here is some more infos : the server is a virtual server hosted on HyperV on a win 2012 server. Don't know if it changes anything, seen the other servers hosted don't have this issue...

A: In my tests I discovered that Hyper-V virtual machine clocks are very unreliable and frequently have a clock drift exceeding 500ppm. This is enough to cause even ntpd to fail. I had to switch to using chrony in these VMs to provide reasonably accurate wall clocks; it defaults to 1000ppm for this scenario and can be adjusted even further if necessary.
I no longer seriously consider Hyper-V for any application where timekeeping is especially important.

A: HyperV is the disease, NTPd is the cure.
Where to look or what i could use to monitor those date change?
You can query the NTPd daemon (via the ntpq client) to get the difference between local clock and the NTPd servers reference clock. But that implies actually running NTPd so you are not monitoring your changes alone, you're monitoring the combined effect of your running local clock and NTPd keeping it in sync.
I don't actually know if you can configure NTPd to run (and give you the above mentioned metrics) but not to actually adjust the system clock. A different, and less efficient, way would be to periodically (cron?) run ntpdate -q against a set of reference NTPd servers and monitor its output, which will give you the difference between your clock and the reference without actually touching the local clock. Output will be like this:
$ ntpdate -q $YOUR_TLD.pool.ntp.org
[... list of queried servers ...]
17 Jul 12:14:11 ntpdate[42868]: adjust time server 109.168.106.59 offset -0.002517 sec

You could filter the last number and graph it to get a nice view of how much and when your clock jumps around:
$ OFFSET=$( ntpdate -q $YOUR_TLD.pool.ntp.org | grep adjust | awk '{ print $10 }' )
$ echo $OFFSET
0.002970

A: Clock drift in a linux vm running in Hyper-V is very common if you don't have the correct integration components installed and enabled. Hyper-V will adjust the hardware clock of any VM it runs, but linux by default does not rely on the hardware clock once the system is booted. The integration components gives the kernel hints about the actual clock time and eliminates this problem.
If integration components are not an option for your distro, then the correct solution is to install something like ntpd and sync to the Hyper-V host or your local clock pool.

A: NTP is not an unnecessary component.
It's the only sane way to keep a system clock updated against an atomic time source.
You should install NTP, configure it to use your local pool time source, and everything will be fine.

A: The "problem" is that your running a version of Linux that does not support Pluggable Time Source Infrastructure. Several distros support it, but commonly only in their 64-bit OSes, and not in their 32-bit.
As others have mentioned, Integration Services allows for clock synchronization, but only if PTSI is supported. Most distros that support PTSI have the HV source already. See if there is a adjtimex port/package available for your distro.
Using NTP is a valid alternative, if you can't get PTSI working correctly. There are also some hacks including the tickadj command, and changing kernel boot variables - these should be avoided.


text:
Q: Python search column of text and return if there are any matching keywords from a list of words I have a dataframe with two columns, message_id and msg_lower. I also have a list of keywords called terms. My goal is to search the msg_lower field for any words that are in the terms list. If they match, I would like to return a tuple that contains the message_id and keyword.
the data looks like this:
|message_id|msg_lower                      |
|1116193453|text here that means something |
|9023746237|more text there meaning nothing|

terms = [text, nothing, there meaning]

Terms can be longer than one word as well
and for the given example i would like to return:
[(1116193453, text),(9023746237,text),(9023746237,nothing),(9023746237,there meaning)]

Ideally I would like to do this as efficiently as possible

A: You can zip both columns for possible loop by tuples, loop by terms and test is membership in splitted values:
terms = ['text', 'nothing']
a = [(x,i) for x, y in zip(df['message_id'],df['msg_lower']) for i in terms if i in y.split()]
print (a)
[(1116193453, 'text'), (9023746237, 'text'), (9023746237, 'nothing')]

EDIT:
terms = ['text', 'nothing', 'there meaning']

a = [(x, i) for x, y in zip(df['message_id'],df['msg_lower']) for i in terms if i in y]
print (a)
[(1116193453, 'text'), (9023746237, 'text'),
 (9023746237, 'nothing'), (9023746237, 'there meaning')]

Another idea is use findall with word boundaries for extract values:
a = [(x, i) for x, y in zip(df['message_id'],df['msg_lower'])
            for i in terms if re.findall(r"\b{}\b".format(i), y)]

A: list(df.apply(lambda x: [(i, x['message_id']) for i in re.findall('|'.join(terms),x['msg_lower'])], axis=1).apply(pd.Series).stack())

Output
[('text', 1116193453), ('text', 9023746237), ('nothing', 9023746237)]

A: If your keywords are just words (don't contain spaces), you could use sets. I don't know exactly how your data is stored, with 2-dimensional arrays it could work like this:
data = [["1116193453", "text here that means something"],
        ["9023746237", "more text there meaning nothing"]]
terms = {"text", "nothing"}

matches = []
for row in data:
    for word in set(row[1].split()) & terms:
        matches.append((row[0], word))

print(matches)
# [('1116193453', 'text'), ('9023746237', 'text'), ('9023746237', 'nothing')]


text:
Q: WUSA 2359302 Error Code when installing WMF silent I'm trying to add WMF via WUSA.exe to use powershell 3.0 on Windows 7. This to rename a computer, because I don't find the right NETDOM.Exe installer, and the WMI command doesn't work.
The WUSA silent installer gives me the 2359302 error.
What does this mean?
.Net 4.0 is already installed.

A: 2359302 converts to 0x00240006 (which should be in the update log) and it means the patch is already applied according to this page. http://support.microsoft.com/kb/938205


text:
Q: Image in JSON iOS I try to get an image in JSON, but how can I get the image into a NSData?
All I get is an __NSCFArray with my binary data, but how to convert it?
EDIT:
This is my result in json
Printing description of resDict:
{
Details = "Foo";
GroupingInfo = LRU;
HeaderLeft = "Bar";
HeaderRight = "Foo";
Id = "cb217aeb-14e3-4bd5-8895-3217238deb2c";
IsGray = 0;
AnotherId = "<null>";
MainImage =     (
    137,
    80,
    78,
    71,
 ...

A: You first have to parse the JSON, then take the binary part, into NSData. UIImage has a method to do change NSData into image
UIImage *myimage = [UIImage imageWithData:mydata];

Update : (hope no one minds)
After making myself such a demo, NSJSONSerialization always returns strings, and after having a small back and forth conversation below. I tried to send an image as a Base64 coded string and read back in as data using base64 decode. This works as a charm.
This is the code I use (since this works on all iOS versions, from 3.0 and up) :
NSData+PHBase64.h
@interface NSData (PHBase64)

+ (id)dataWithBase64EncodedString:(NSString *)string;     //  Padding '=' characters are optional. Whitespace is ignored.
- (NSString *)base64Encoding;
@end

NSData+PHBase64.m
#import "NSData+Base64.h"

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation NSData (PHBase64)

+ (id)dataWithBase64EncodedString:(NSString *)string;
{
    if (string == nil)
        [NSException raise:NSInvalidArgumentException format:nil];
    if ([string length] == 0)
        return [NSData data];

    static char *decodingTable = NULL;
    if (decodingTable == NULL)
    {
        decodingTable = malloc(256);
        if (decodingTable == NULL)
            return nil;
        memset(decodingTable, CHAR_MAX, 256);
        NSUInteger i;
        for (i = 0; i < 64; i++)
            decodingTable[(short)encodingTable[i]] = i;
    }

    const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if (characters == NULL)     //  Not an ASCII string!
        return nil;
    char *bytes = malloc((([string length] + 3) / 4) * 3);
    if (bytes == NULL)
        return nil;
    NSUInteger length = 0;

    NSUInteger i = 0;
    while (YES)
    {
        char buffer[4];
        short bufferLength;
        for (bufferLength = 0; bufferLength < 4; i++)
        {
            if (characters[i] == '\0')
                break;
            if (isspace(characters[i]) || characters[i] == '=')
                continue;
            buffer[bufferLength] = decodingTable[(short)characters[i]];
            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
            {
                free(bytes);
                return nil;
            }
        }

        if (bufferLength == 0)
            break;
        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
        {
            free(bytes);
            return nil;
        }

        //  Decode the characters in the buffer to bytes.
        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
        if (bufferLength > 2)
            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
        if (bufferLength > 3)
            bytes[length++] = (buffer[2] << 6) | buffer[3];
    }

    realloc(bytes, length);
    return [NSData dataWithBytesNoCopy:bytes length:length];
}

- (NSString *)base64Encoding;
{
    if ([self length] == 0)
        return @"";

  char *characters = malloc((([self length] + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;

    NSUInteger i = 0;
    while (i < [self length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [self length])
            buffer[bufferLength++] = ((char *)[self bytes])[i++];

        //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }

    return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
}

@end


text:
Q: Migrating a filter from XML to pure Java Config I am trying to migrate a project from a mixed XML/Java configuration to pure Java Config (not yet Java DSL, but annotated @Bean methods).
So far, I managed to convert channels, inbound channel adapters, transformers and service activators), but I'm stuck with the conversion of a filter.
The integration.xml file define the following filter (the Message carries a Java.io.File payload)
<int:filter input-channel="channelA" output-channel="channelB"
            ref="integrationConfiguration" method="selector"/>

The selector is defined in the IntegrationConfiguration class (that also holds all other SI-related @Bean methods:
@Configuration
public class IntegrationConfiguration {

    // channels
    @Bean
    public MessageChannel channelA() { return new DirectChannel(); }
    @Bean
    public MessageChannel channelB() { return new DirectChannel(); }
    // some other required channels
    // ...

    // inbound channel adapters
    @Bean
    @InboundChannelAdapter(channel = "channelA")
    public MessageSource<File> fileReadingMessageSource() {
        var source = new FileReadingMessageSource();
        // source configuration (not relevant here)
        return source;
    }
    // ...

    // filter on Message<File>
    public boolean selector(@Header("file_name") String name,
                            @Header("file_relativePath") String relativePath) {
        // do stuff with name and relativePath and return true or false
        return true;
    }

    // transformers
    @Bean
    @Transformer(inputChannel = "channelB", outputChannel = "channelC")
    public HeaderEnricher enrichHeaders() {
        var expression = new SpelExpressionParser().parseExpression("...");
        var headers = Map.of("additional_header",
                new ExpressionEvaluatingHeaderValueMessageProcessor<>(expression, String.class));

        return new HeaderEnricher(headers);
    }
    // ...

    // service activators
    @Bean
    @ServiceActivator(inputChannel = "channelC")
    public FileWritingMessageHandler fileWritingMessageHandler() {
        var handler = new FileWritingMessageHandler(
                new SpelExpressionParser().parseExpression("headers.additional_header")
        );
        // handler configuration (not relevant here)
        return handler;
    }
    // ...
}

I tried to replace the XML-defined bean with:
@Bean
@Filter(inputChannel = "channelA", outputChannel = "channelB")
public boolean filter() {
    // get the "file_name" and "file_relativePath" headers
    var expression1 = new SpelExpressionParser().parseExpression("headers.file_name");
    var name = expression1.getValue(String.class);

    var expression2 = new SpelExpressionParser().parseExpression("headers.file_relativePath");
    String relativePath = expression2.getValue(String.class);

    // do stuff with name and relativePath and return true or false
    return true;
}

When I run the code, it gives me a BeanCreationException:
Error creating bean with name 'filter' defined in class path resource [.../IntegrationConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [boolean]: Factory method 'filter' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
What did I do wrong?
UPDATE after Artem's answer and insightful comments:
Using @Bean isn't necessary for a POJO method, keep it for

out-of-the-box type: MessageHandler, Transformer, MessageSelector etc

In this case, one can use a (not an out-of-the-box) @Bean MessageSelector, but it is actually more lines of code for the same result:
@Bean
@Filter(inputChannel = "channelA", outputChannel = "channelB")
public MessageSelector messageSelector() {
    return new MessageSelector(){
        @Override
        public boolean accept(Message<?>message){
            var headers = message.getHeaders();
            var name = headers.get("file_name", String.class);
            var relativePath = headers.get("file_relativePath", String.class);

            return selector(name, relativePath);
        }
    };
}

A: There is just enough to do like this:
@Filter(inputChannel = "channelA", outputChannel = "channelB")
public boolean selector(@Header("file_name") String name,
                        @Header("file_relativePath") String relativePath) {

See docs for that @Filter:
 * Indicates that a method is capable of playing the role of a Message Filter.
 *

 * A method annotated with @Filter may accept a parameter of type
 * {@link org.springframework.messaging.Message} or of the expected
 * Message payload's type. Any type conversion supported by default or any
 * Converters registered with the "integrationConversionService" bean will be
 * applied to the Message payload if necessary. Header values can also be passed
 * as Message parameters by using the
 * {@link org.springframework.messaging.handler.annotation.Header @Header} parameter annotation.
 *

 * The return type of the annotated method must be a boolean (or Boolean).

The @Filter is similar to the @ServiceActivator or @Transformer: you mark the method and point to the channels. The framework creates an endpoint and use that method as a handler to consume messages from the channel. The result of the method call is handler respectively to the endpoint purpose. In case of filter the request message is sent to the output channel (or reply channel from header)  if result is true. Otherwise the message is discarded.
See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/configuration.html#annotations


text:
Q: PHP: Rawurlencode inside Preg-replace while($row = mysql_fetch_array($result)){
    $search = '' . $row['searchquery'];
    echo '' ...
but if someone types in äöü, it doesnt show the letters - with rawurlencode thats possible, but I want to remove the blank spaces with pregreplace and replace it with +
is that possible?

A: Do you have an objection to the str_replace function? If not then you can use it with rawurlencode. It would be a lot simpler and faster.

A: The answer to your question would be to use a regular expression function that can actually handle UTF-8 strings.
mb_internal_encoding("UTF-8");
mb_regex_encoding('UTF-8');

// eliminate the first spaces
$search = mb_ereg_replace('^\s*', '', ''.$row['searchquery']);
// replace the other spaces with '+' signs
echo '';

You could also use the /u modifier for the preg functions:
echo ''

This seems better, but you should be careful. I've tried it now, and it outputs your characters fine, but I noticed it stripped out some other UTF-8 characters I've given it as input (ăşţ).
zaf is right, there are easier ways to do this :).


text:
Q: Testing if an object is dependent to another object Is there a way to check if an object is dependent via parenting, constraints, or connections to another object? I would like to do this check prior to parenting an object to see if it would cause dependency cycles or not.
I remember 3DsMax had a command to do this exactly. I checked OpenMaya but couldn't find anything. There is cmds.cycleCheck, but this only works when there currently is a cycle, which would be too late for me to use.
The tricky thing is that these 2 objects could be anywhere in the scene hierarchy, so they may or may not have direct parenting relationships.

EDIT
It's relatively easy to check if the hierarchy will cause any issues:
children = cmds.listRelatives(obj1, ad = True, f = True)
if obj2 in children:
    print "Can't parent to its own children!"

Checking for constraints or connections is another story though.

A: depending on what you're looking for, cmds.listHistory or cmds.listConnections will tell you what's coming in to a given node.  listHistory is limited to a subset of possible connections that drive shape node changes, so if you're interested in constraints you'll need to traverse the listConnections for your node and see what's upstream. The list can be arbitrarily large because it may include lots of hidden nodes like like unit translations, group parts and so on that you probably don't want to care about.
Here's simple way to troll the incoming connections of a node and get a tree of incoming connections:
def input_tree(root_node):
    visited = set()  # so we don't get into loops

    # recursively extract input connections
    def upstream(node,  depth = 0):
        if node not in visited:
            visited.add(node)
            children = cmds.listConnections(node, s=True, d=False)
            if children:
                grandparents  = ()
                for history_node in children:
                    grandparents += (tuple(d for d in  upstream(history_node, depth + 1)))
                yield node,  tuple((g for g in grandparents if len(g)))

    # unfold the recursive generation of the tree
    tree_iter = tuple((i for i  in upstream(root_node)))
    # return the grandparent array of the first node
    return tree_iter[0][-1]

Which should produce a nested list of input connections like
 ((u'pCube1_parentConstraint1',
   ((u'pSphere1',
     ((u'pSphere1_orientConstraint1', ()),
     (u'pSphere1_scaleConstraint1', ()))),)),
   (u'pCube1_scaleConstraint1', ()))

in which each level contains a list of inputs.  You can then troll through that to see if your proposed change includes that item.
This won't tell you if the connection will cause a real cycle, however: that's dependent on the data flow within the different nodes. Once you identify the possible cycle you can work your way back to see if the cycle is real (two items affecting each other's translation, for example) or harmless (I affect your rotation and you affect my translation).

A: This is not the most elegant approach, but it's a quick and dirty way that seems to be working ok so far. The idea is that if a cycle happens, then just undo the operation and stop the rest of the script. Testing with a rig, it doesn't matter how complex the connections are, it will catch it.
# Class to use to undo operations
class UndoStack():
    def __init__(self, inputName = ''):
        self.name = inputName

    def __enter__(self):
        cmds.undoInfo(openChunk = True, chunkName = self.name, length = 300)

    def __exit__(self, type, value, traceback):
        cmds.undoInfo(closeChunk = True)

# Create a sphere and a box
mySphere = cmds.polySphere()[0]
myBox = cmds.polyCube()[0]

# Parent box to the sphere
myBox = cmds.parent(myBox, mySphere)[0]

# Set constraint from sphere to box (will cause cycle)
with UndoStack("Parent box"):
    cmds.parentConstraint(myBox, mySphere)

# If there's a cycle, undo it
hasCycle = cmds.cycleCheck([mySphere, myBox])
if hasCycle:
    cmds.undo()
    cmds.warning("Can't do this operation, a dependency cycle has occurred!")


text:
Q: how can I stop animation buildup in jQuery? I have the following script to open a side menu.
The menu opens line by line.
But if you rapidly click the menu button there is a animation buildup.
How can I stop this from happening? Tried with .stop(true) and .finish() before .animate but did not get the desired effect. I'm new to jQuery so I'm probably doing something wrong.
        var s = 0;
        var navMenu = document.getElementById("nav_menu");
        var navBtn = document.getElementById("btn");
        var speed = 100;

            function menuOpen() {
                if (s==0){

                    $("#nav_menu").scrollTop(0);
                    navBtn.classList.add('close');
                    navMenu.style.zIndex = "4";
                    navMenu.style.overflowY = 'auto';

                    $('ul').each(function() {
                        $(this).children().each(function(i) {
                            $(this).delay(i * speed).animate({
                                left: 0
                            });
                        });
                    });

                    s++;

                    $("li").promise().done(function() {
                        navMenu.style.zIndex = "4";
                        navMenu.style.overflowY = 'auto';
                    });

                } else {

                    navBtn.classList.remove('close');

                    $('ul').each(function() {
                        $(this).children().each(function(i) {
                            $(this).delay(i * speed).animate({
                                left: "100%"
                            });

                        });
                    });

                    s=0;

                    $("li").promise().done(function() {
                        navMenu.style.zIndex = "0";
                        navMenu.style.overflowY = 'hidden';
                    });

                };

            };

Please explain your answer if possible.
Thanks

A: Yes, animation must be stops with stop() method of jQuery, please check with your code. you have to call stop() first and then have to call animate()
$(this).stop().animate({left: 0},i * speed);

$(this).stop().animate({left: "100%"},i * speed);


text:
Q: Error in Setting up virtual Env by calling python file Problem :- My aim is to create a python file that will set-up virtual enviroment and will activate virtual enviroment by calling setup_env.py file.
In cmd,
python setup_env.py
with this line i am calling my file and this will setup virtual env automatically.
import os
import sys
import subprocess

def create_venv():
      subprocess.check_call([sys.executable, "-m", "venv", "env"])

def activate_venv():
      if os.name == 'nt': # for windows
    activate_script = os.path.join("env", "Scripts", "activate.bat")
else: #Unix/Linus/MacOS
    activate_script = os.path.join("env", "bin", "activate")
activate_this = os.path.abspath(os.path.join(os.getcwd(), activate_script))
with open(activate_this) as f:
    code = compile(f.read(),activate_this,'exec')
    exec(code,dict(__file__=activate_this))

if __name__ == '__main__':
    create_venv()
    activate_venv()

Now after this my virtual enviroment is generated and activated also, but in cmd i am getting this error, as follows :-
PS C:\Setup_env> python .\Setup_env.py
Traceback (most recent call last):
  File "C:\Setup_env\Setup_env.py", line 20, in <module>
    activate_venv()
  File "C:\Setup_env\Setup_env.py", line 15, in activate_venv
    code = compile(f.read(),activate_this,'exec')
  File "C:\Setup_env\env\Scripts\activate.bat", line 1
    @echo off
          ^
SyntaxError: invalid syntax


text:
Q: Having trouble with the manager functionality in django Designing code to handle transfers of objects called "contractBundles". Have this in the models.py in a "contract" app:
class contractBundleManager():
 #   def trade(self, buyer, seller, amount):
     def add (self, user=pgamedb_models.Player, contractName=str, amount=float):
         contractList = contract.objects.all()
         for c in contractList:
             if contractName == c.contractText:
                 user.money = user.money - (amount * c.value)
                 return self.create(contract=c, volume=amount, owner=user)

class contractBundle(models.Model):
    objects = contractBundleManager()

    contract = models.ForeignKey('contract')
    volume = models.FloatField()
    owner = models.ForeignKey(pgamedb_models.Player)

    def __str__(self):
        return '%10.2f x %s -> %s' % (self.volume, self.contract.shortName, self.owner.user.username)

Elsewhere, I want to let people purchase the bundles by pressing a button:
from contracts import models as cmodels
...
 if request.method == 'POST':
          ...
        elif 'Buy' in request.POST:
            [set up activeUser, polName, amount]
            cmodels.contractBundle.objects.add(user=activeUser, contractName=polName, amount=amount)

Yet when the code calls the contractBundle.objects.add() method, I get the following error:
AttributeError at [url]
'Manager' object has no attribute 'add'
Request Method: POST
Request URL:    [url]
Django Version: 1.3.1
Exception Type: AttributeError
Exception Value:
'Manager' object has no attribute 'add'
Exception Location: ...views.py in [method], line 56
Python Executable:  /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.1

Any thoughts why this might be happening?

A: There are a couple of things here that are wrong.
Firstly, your manager class needs to inherit from models.Manager:
class contractBundleManager(models.Manager):

This is where all the code like create is defined.
Also, it seems like a really bad idea to use classes/types as default values for function parameters. If you want to document what types a function needs, you should use a docstring.
Edit after comment No, I'm not referring to the return statement or the way you're calling  self.create. I'm referring to the default values in the contractBundleManager.add method. You should never do this. If someone calls your method without passing the user parameter, the function will use the default value you have defined - which is a class.  Classes in Python are mutable, so your function will actually modify the definition of the Player class.
Really, this is not the way to show the correct types to call the function with. Leave out the default values, and use a docstring.

A: #model
class contractBundle(models.Model):
    objects = models.Manager( )
    contact_bundle_manager = contractBundleManager( )
#view
cmodels.contact_bundle_manager.add(user=activeUser, contractName=polName, amount=amount)


text:
Q: When should I use `Dispatchers.Unconfined` vs `EmptyCoroutineContext`? When is it appropriate to use Dispatchers.Unconfined vs EmptyCoroutineContext?
My use case is that I want to create an API for intercepting network calls. I want to provide an optional parameter to control what dispatcher the interception is executed on. For the default value of this parameter, should it be Dispatchers.Unconfined or EmptyCoroutineContext?

A:
For the default value of this parameter, should it be Dispatchers.Unconfined or EmptyCoroutineContext?

Most of the time it is Dispatchers.Unconfined.
EmptyCoroutineContext has no elements in it, semantically it is a null object. Coroutine builders, such as launch, specify their behaviour for that case: If the context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used. Most of the time you should not use EmptyCoroutineContext as you don't use nulls or null objects.
Dispatchers.Unconfined is different: it executes coroutine immediately on the current thread and later resumes it in whatever thread called resume.
It is usually a good fit for things like intercepting regular non-suspending API or invoking coroutine-related code from blocking world callbacks.


text:
Q: Defining a Threshold level for the Mahalanobis distance in R I would like to know if there is any function in R that calculates the threshold level for the Mahalanobis distance such that the probability mass of the ellipsoid is set equal to a certain α, say 0.99.
Thanks,
Juan.


text:
Q: Correct code formatting with sublime text? I have a large block of code. Something like this but much larger:

Here is some text

How can I correct the indentation to make it something like this with Sublime text?:

Here is some text

A: The best solution I've found is the HTML-CSS-JS Prettify plugin from Package Control. Please make sure you read all of the directions carefully, as the plugin depends on node.js, and has to be set up properly.


text:
Q: Passport.js signup appears to work but user credentials not inserted into database Using Scotch.io and the official passport docs as reference, I'm implementing a Node/Express/Sequelize application where I have a basic signup form with fields for email and password:
./views/signup.ejs
<form action="/signup" method="post">

        Email
        <input type="text" class="form-control" name="email">

        Password
        <input type="password" class="form-control" name="password">

    <button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>

with the passport-local strategy defined as follows:
./config/passport.js
const db = require('./sequelize');

const passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(user, done) {
    db.User.findById(id, function(err, user) {
        done(err, user);
    });
});

passport.use('local', new LocalStrategy({
    emailField : 'email',
    passwordField : 'password',
    passReqToCallback : true
    },
    function(email, password, done){
        process.nextTick(function() {
            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            db.User.findOne({ email : email }, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(null, false, {message: err});

                // check to see if theres already a user with that email
                if (user) {
                    return done(null, false, {message: 'User already exists'});
                }

                else {
                    // if there is no user with that email
                    // create the user
                    db.User.create({
                        email: email,
                        password: password
                    });
                    return done(null, false, {message: 'User created'});
                }
            });
         });
      }
 ));

module.exports = passport;

and lastly the routes are taken care of in
app.js
const express = require('express');
const http = require('http');
const https = require('https');
const sequelize = require('sequelize');
const db = require('./config/sequelize');
const querystring = require('querystring');
const config = require('./config/config');
const passport = require('./config/passport');
const bodyParser = require( 'body-parser' );

const env = 'development';

const app = express();

const port = 3000;

app.use( bodyParser.urlencoded({ extended: true }) );
app.use(passport.initialize());
app.use(passport.session());

app.set('view engine', 'ejs');

app.listen(port);

app.post('/signup', function(req, res, next){

const user = req.body;
passport.authenticate('local', function(err, user, info){
        if (err){
            res.send({success: false, message: 'authentication failed'});
        }
        else{
            console.log(info);
            res.json({message: "success"});
        }
    })(req, res, next)
});

What I expect to happen if the local strategy works is for the res.json({message: "success"}) to appear on the browser and for the database to be updated per the specifications of ./config/passport.js. The {message: "success"} is appearing on the screen, but the database is not being updated, which leads me to believe that something is wrong with my implementation in ./config/passport.js. In app.js, the console.log(info) statement shows the following message on cmd:
Executing (default): SELECT `id`, `username`, `email`, `password`, `createdAt`,
`updatedAt` FROM `Users` AS `User` LIMIT 1;

which makes it look like the insertions might be going through but inspections of the db reveal otherwise. I have done previous sanity checks with CRUD updates to confirm that the basic implementation of Sequelize works, and will provide the schema of the table upon request. How else can I debug this situation?

A: Read about how to make queries in sequelize
http://docs.sequelizejs.com/en/latest/docs/querying/
you should use promises, like this:
db.User.findOne({ where: {email : email }})
.then(function(user){
   //do smth;
})
.catch(function(error){
   console.log(error);
});


text:
Q: Association models managing classes in a "uncommon way" I am using Ruby on Rails 3 and I have a class List and some other child classes that "compose" that List in a "uncommon way". That is, I have a List model with the following attributes:
# LIST ATTRIBUTES
id       : integer
kind_of  : string
class_id : integer

kind_of values can be "school", "house", ... and for each kind_of I have a class ListSchool, ListHouse, ... The class_id refers to the primary key of the child class of kind_of "school", "house", ... (so I can have multiple equal values for class_id but each of those referring to a particular class ListSchool, ListHouse, ... depending on the kind_of value).
In few words, I would like to refer to a unique class (the class List) in order to reach all kind of child classes (ListSchool, ListHouse, ...) basing on an attribute value of the parent class (the kind_of of the class List).
How can I write the association code in order to associate those models (maybe using :conditions  => "kind_of = 'school'", :conditions  => "kind_of = 'house'", ... in the association statement has_one)? What do you advice about this approach of "dividing classes"?

A: It sounds very much like you are looking for Single Table Inheritance (STI). Rails supports this out of the box; all you need to do is define a type column on the List class, then inherit ListSchool and ListHouse from List. There is no need for the kind_of or class_id columns with STI.
A web search for 'rails sti' turns up some good resources, including this StackOverflow question.


text:
Q: React textarea with value is readonly but need to be updated I have a textarea in my React app who is filled with a value. I want this textarea to be updated and the form submited to update the row in the database.
<textarea id="description" className="materialize-textarea" length="120" value={description} disabled={isDisabled}></textarea>

The description variable fill the textarea with the value from the database. The field is not disabled.
I tried to attach an onChange event who dispatch an action (redux) to change the value of the textarea, but it trigger for each letter and it's too slow.
How can i create a textarea who is filled by a value and is editable?
Thank you!

A: Here is a component with two textareas. There is a controlled relation between props and state. That is the key for inputs. Note componentWillReceiveProps.
    import React, {Component} from 'react';

    import Actions from '../../flux/Actions';

    let CurrentSnipDivSty = {
        height: 'calc(((100% - 40px) * .4) - 3px)',
        minHeight: '9.5em',
        width: '100%'
    };

    let CurrentSnipTextAreaSty = {
        backgroundColor: '#213919',
        border: '1px solid #314929',
        color: '#afac87',
        fontSize: '1em',
        height: 'calc(50% - 20px)',
        overflowY: 'auto',
        padding: '5px',
        width: 'calc(100% - 12px)'
    };

    class SnipsDetailRender extends Component {
        render() {
            let snip = this.state.snip.snip;
            let comment = this.state.snip.comment;

            return (
                <div id='CurrentSnipDivSty' style={CurrentSnipDivSty}>
                    <textarea
                        value={snip}
                        onChange={this.handleSnipChange}
                        style={CurrentSnipTextAreaSty} />
                    <textarea
                        value={comment}
                        onChange={this.handleCommentChange}
                        style={CurrentSnipTextAreaSty} />
                </div>
            );
        }
    }

    export default class SnipsDetail extends SnipsDetailRender {
        constructor() {
          super();
            this.state = { snip: {snip: '', comment: ''} };
        }
        componentWillReceiveProps = (nextProps) => {
            if ((nextProps.data.snip != this.state.snip.snip) || (nextProps.data.comment != this.state.snip.comment))
             this.setState({snip: nextProps.data});
        }
        handleSnipChange = (ev) => {
            let newSnip = {snip: ev.target.value, comment: this.state.snip.comment};
            this.setState({snip: newSnip});
            Actions.saveSnipEdit(newSnip);
        }
        handleCommentChange = (ev) => {
            let newSnip = {snip: this.state.snip.snip, comment: ev.target.value};
            this.setState({snip: newSnip});
            Actions.saveSnipEdit(newSnip);
        }
    }

A: If you're finding using the onChange event too slow, you can simply read from the DOM in the submit handler using refs. An example is shown here:
https://facebook.github.io/react/docs/tutorial.html#adding-new-comments
Since you're using redux, you can probably export a lot of that functionality to an action creator.


text:
Q: How make listview horizontally I'm confused about changing the vertical scroll listview to horizontal, I've looked for it in the forum, but nothing works, maybe someone can help, this is the script I found
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="0dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lvList"
            android:layout_weight="1"/>

    </LinearLayout>

</HorizontalScrollView>

and it didn't work.
and this is my original script
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="0dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lvList"
            android:layout_weight="1"/>

    </LinearLayout>

A: You can use recyclerview with horizontal  linear layout manager.


text:
Q: Why still get data from localstorage after removed in React? I define my localstorage like this:
export default new class LocalStorage {
  setItem(key, data) {
    window.localStorage.setItem(key, JSON.stringify(data));
  }

  getItem(key) {
    return JSON.parse(window.localStorage.getItem(key));
  }

  removeItem(key) {
    window.localStorage.removeItem(key);
  }
}();

and my RestrictionRoute like this:
const localStorageData = LocalStorage.getItem("root");
export const RestrictionRoute = ({ component: Component, ...rest }) => {
      console.log(localStorageData);
      return (
        <Route
          {...rest}
          render={props =>
            localStorageData && localStorageData.token ? (
              <Redirect to="/" />
            ) : (
              <Component {...props} />
            )
          }
        />
      );
    };

My logout action:
export function logOut() {
  return function(dispatch) {
    dispatch(changeLoadingStatusTo(true));
    LocalStorage.removeItem("root");
    dispatch(changeLoadingStatusTo(false));
    dispatch(push("/login"));
  };
}

When I click logout in header, my logout action is triggered, the data also removed in local storage, and in RestrictionRoute, I check localstorage again by console.log(localStorageData), then the data still exist. This make me confused.

A: Try check directly "LocalStorage.getItem("root") instead of printing the value stored in the variable, since localStorage is the copy of the data present where you initialized your class.


text:
Q: javascript ES6 dynamically chaining promises I'm trying to chain promises dynamically in order to deal with an unknown amount of asynchronous calls that need to happen in order. I'm using IO.JS/chrome which supports Promise's natively.
The creation of the promise fires immediately (at least relatively to console output). I was expecting to be able to collect promises then pass to Promise.all, but by that time they've already fired for reasons I don't understand.
Here's one method of chaining then, suggested by a comment on Dynamic Chaining in Javascript Promises
            var lastPr = null;
            console.log(" exit setup......................");
            while(this.statesToExit.length > 0) {

                var v = this.statesToExit.shift();
                console.log("new Promise...");
                var pr = new Promise(function (resolve, reject) {

                    console.log("doing Exit stuff at time " +curTime);
                    resolve();  //SOMETHING MORE SUBSTANTIAL GOES HERE

                });

                console.log("lastPr.then.");
               if (lastPr != null) {
                    lastPr.then(pr);
                }
                lastPr = pr;
              //  console.log("adding pr to worklist");
               // promiseList.push(pr);
                // });
            }

The other approach is
            var promiseList= [];
            console.log(" exit setup......................");
            while(this.statesToExit.length > 0) {

                var v = this.statesToExit.shift();
                console.log("new Promise...");
                var pr = new Promise(function (resolve, reject) {

                    console.log("doing Exit stuff at time " +curTime);
                    resolve();  //SOMETHING MORE SUBSTANTIAL GOES HERE

                });

                console.log("adding pr to worklist");
                promiseList.push(pr);
                 });
            }
 console.log("Transition *START*-" +promiseList.length +" ");
       Promise.all(promiseList).catch(function(error) {
            console.log("Part of TransitionCursor Failed!", error);
        }).then(this.summarizeWorkDone());

In both cases the output is like
new Promise...
doing Exit stuff at time 0
new Promise...
doing Exit stuff at time 0
    "Transition *START*-"

vs the expected
new Promise...
new Promise...
    "Transition *START*-"
doing Exit stuff at time 0
doing Exit stuff at time 0

How do I dynamically create a list of promises to later execute?

A: Ok,
So people are voting down my answer because I provided the external link, which in fact was written by me. So sad! So modifying the answer and the previous answer goes at the bottom of this answer.
Here, I shall focus some light on the problems on the first example because that's what I have explained in the link at the bottom of this post.
First of all: you are not chaining promises but creating multiple promises. When you create a promise, the function that you pass to the constructor gets called immediately. Check section 1 of the tutorial in the link below for details. That's why you get the output line 'doing Exit stuff at time ...' after 'new promise' line. You did not say anything about curTime but it seems that the values are not right although that's not the focus of this post.
Secondly, you should assign lastPr.then() to lastPr() but you are assigning the newly created pr to lastPr. This was explained in section 2 of the link below.
Thirdly, I would say that your expected output says that I should remind you that the function passed to promise constructor starts immediately. So you should not print anything during the promise creation and rather push them down in then() methods. However, I am not doing this here and so you will see that the first 'doing Exit stuff at time 0' line appears just after the first 'new Promise...' line.
Fourthly, you did not show 'lastPr.then.' in expected output
Note: I changed your code's curTime and statesToExit (removed 'this' reference and assigned test array)
I would suggest something like this:
var curTime = 0;
var lastPr = null;
console.log(" exit setup......................");
var statesToExit = [1, 2, 3]; // NOTE: the change to make this code runnable.
while (statesToExit.length > 0) {
    var v = statesToExit.shift();
    console.log("new Promise...");

    if (lastPr == null) {
        lastPr = new Promise(function (resolve, reject) {
            console.log("doing Exit stuff at time " + curTime);
            resolve();  //SOMETHING MORE SUBSTANTIAL GOES HERE
        });
    }
    else {

        console.log("lastPr.then."); // NOTE: This does not appear in your expected output
        lastPr = lastPr.then(result => {
            console.log("doing Exit stuff at time " + curTime);
            return Promise.resolve();  //SOMETHING MORE SUBSTANTIAL GOES HERE
        });
    }
    //  console.log("adding pr to worklist");
    // promiseList.push(pr);
    // });
}

// NOTE: now you need to esecute the chain:
// you should handle promise rejection:
// check the tutorial link:
// https://github.com/tuhinpaul/syp-model/wiki/Programmatic-Chaining-and-Recursive-Functions-with-JavaScript-Promise
lastPr.catch(err => { console.log(err); });

The output of the above code:
 exit setup......................
new Promise...
doing Exit stuff at time 0
new Promise...
lastPr.then.
new Promise...
lastPr.then.
doing Exit stuff at time 0
doing Exit stuff at time 0

I described dynamic promise chaining in the following tutorial: check the following tutorial for

*

*programmatic (dynamic) chaining of javascript/node.js promises and

*Promise chaining using recursive functions

Programmatic-Chaining-and-Recursive-Functions-with-JavaScript-Promise

A: My understanding of promises was indeed off, as mentioned on this excellent page: http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html first they do start execution immediately, second to do dynamically you have to use a factory function to defer execution like so:
first create the chain start.
    var chain = Promise.resolve();
   //     chain.then(this.doTranStart);

then for each of the states (an array), then create a proxy closure so that the function can be called back with appropriate data. I'm not sure if there is something built into javascript for this, so I ported a library from actionscript 2.0, back when it had similar problems.
    this.statesToExit.forEach(function (state) {
            console.log("new Exit Promise Chain...");
              var pxfn = GetProxy.getProxy(self, self.doExitFactory, [curTime,state._fn,state]);
               chain = chain.then(pxfn);
            });

then later run the chain of factories, which will then call the factory and then execute the promise.
chain.catch(function(error) {
            console.log("Part of TransitionCursor Failed!", error);
        }).then(this.summarizeWorkDone);

the first is the factory method, very simple.
   doExitFactory(curTime,fn,stateScope) {
        console.log("doExitFactory " );//+ curTime,fn,stateScope );
        return this.doExit(curTime,fn,stateScope);
    }

this is the actual function to do the work. Calling a function dynamically on the given scope.
    doExit(curTime, _fn, stateScope) {
        console.log("doExit");
        return new Promise(function (resolve, reject) {
          //  console.log("doing actual Exit stuff at time ");//+ curTime);
            _fn.apply(stateScope, [{sig: STATE.EXIT}, resolve, reject]);
            resolve();

        })
    }

The output looks like
TransitionCursor.setRoute
starting to create chain
new Exit Promise Chain...
new Exit Promise Chain...
finishing create chain

calling chain to start............
Transition *START*--------------------------
doExitFactory
doExit
IS_s11 (EXIT)
doExitFactory
doExit
IS_s1 (EXIT)
summarizeWorkDone:---------------

where IS_s11, and IS_s1 are the actual async functions I want to run in order.

A: You wrote:
new Promise((r)=>r()).then(new Promise((r)=>r());

What you want to write:
new Promise((r)=>r()).then(()=>new Promise((r)=>r()));

To make your code works the way you want, change
lastPr.then(pr);

to
lastPr.then(()=>pr);


text:
Q: Другой alert при повторном клике Создал простенькую анимацию текста. Написал скрипт, который при клике выключает анимацию и выводит сообщение "Анимация текста выключена". Хотел сделать так, чтобы при повторном клике анимация запускалась и выводилось уже другое сообщение "Анимация текста снова работает", анимация запускается, но нужное мне сообщение не появляется =(

let Second_text = document.querySelector(".second_text");

Second_text.addEventListener('click', function(e){

if(Second_text){
this.classList.toggle('no_animation');
alert('Анимация текста выключена');
}

else{
alert('Анимация текста снова работает'); // Это сообщение должно выводиться при повторном клике
}

});
.second_text{
width:400px;
padding:10px;
text-align:center;
color:white;
font-size:40px;
font-weight: bold;
font-family:arial;
animation: 2s neon-2 alternate-reverse infinite;
position:absolute;
left: 50%;
margin-right: -50%;
transform: translate(-50%, 0%);
padding-bottom:60px;
}

.no_animation{
animation: none;
}

@keyframes neon-2 {
from {
text-shadow: 0 0 5px #87CEEB,
0 0 10px #87CEFA,
0 0 15px #00BFFF,
0 0 20px #1E90FF;
}
to {
text-shadow: 0 0 20px #7478AE,
0 0 35px #7478AE,
0 0 40px #7478AE,
0 0 50px #7478AEk,
0 0 800px #7478AE;
}
}
<p class="second_text">
Я ТЕБЕ ПОКУШАТЬ ПРИНЕС =)
</p>

A: Например вот так:
...
this.classList.toggle('no_animation');
if(this.classList.contains('no_animation'))
  alert('Анимация текста выключена');
else
  alert('Анимация текста снова работает');
...


text:
Q: Isekai manga where a guy getting transported to his favorite game but as sss rank side character who's a mercenary and is fated to die The main character reincarnated in his favorite game but as a sss rank side character who's a mercenary who is fated to die by a demon. The hero's party open a giant door that unsealed the demons. The whole kingdom is up in flames, but he knows what's going on and changes his fate and kills the demon that was fated to kill him and is now with the hero's party.

A: This is I'm Not the Hero!

"Reincarnated as a sub-character of a video game that I used to play!?" After saving a girl and then getting run over by a car in the process, "I" was reincarnated as "Rex" in a video game world. Rex is handsome and has skills in all fields, but he is a helper character in the early stages. Though Rex has a high level, balanced skill set, and multitude of abilities…He's useless in the later stages of the game!!

Rex is described as an A-rank adventurer, not a mercenary, but the two are similar. He isn't explicitly described as being SSS-rank or having SSS stats, just that he's extremely strong for the opening scene. He's supposed to die in the early stages of the game, but uses his knowledge to avoid this. He uses a sword.
The plot of the opening is similar to what you described, but some of it was just thinking about the regular future, and didn't actually happen after he reincarnates. He meets the hero and his party, stops them from opening the door, and exits the cave. The city is still in flames, and manages to kill the Doom Demon that was supposed to kill him by using his in-game knowledge.


text: Q: What is the assign operator in tikz I'd like to know if there is a separate assign operator like "=" in tikz for assigning results from certain operations. I know \pgfmathparse can do it through \pgfmathresult, but it seems too complicated.