text:
Q: Automatic calculation in one attribute table based on values in another attribute table using python I am trying to fill the fields of one gdb table based on some statistics over the attributes of another shape file. As it was not possible in ARCgis directly, I am trying to use python coe for this case.
I have table A where:
Work_done   Length
  1
  50
  100
I would like to say that fill the legth field with sum of the Shape_Length in table B where "work_Done" field is equal another feild in table B.
the following code is what I am thinking and I want to use it in the field_calculator but I got failed. I am not really pro in python therfore I would be really happy if sombody could guide me.
  import arcpy

  from arcpy import env

  # Set the current workspace
  env.workspace = "C:/Python27/ArcGIS10.1"

  table = "Corriodr_stat.dbf"
  ft = "Length"
  fc = "Corridor_test.shp"
  f1, f2 = "Corridor_S", "SHAPE_Leng"

  for row1 in sorted(arcpy.da.SearchCursor(fc, [f1, f2])):
     for row2 in sorted(arcpy.da.UpdateCursor(fc, [ft])):
        if fc.f1 <= 1:
           table.row2 = getvalueField(sum row1.f2)
        elif (fc.f1 > 1 and fc.f1 <= 60)
           table.row2 = getvalueField(sum row1.f2)
        elif (fc.f1 > 60 and fc.f1 <= 100):
           table.row2 = getvalueField(sum row1.f2)

A: The basic problem is the assumption that referring to a feature classes or table by name gives it any intelligence, and to be able to write any substantial python code you need to understand basic python types, and I suggest you find a basic python tutorial (not an ArGIS/python tutorial!)

*

*fc is not a feature class, it is a string which happens to contain the path to a feature class.  As far as python is concerned its just a bunch of characters, and would be treated exactly the same if you wrote fc = 'I am not a feature class'.  The line rowsFc = arcpy.SearchCursor(fc) calls a function (SearchCursor) which takes the path to a feature class, opens the feature class and returns a search cursor to it.

*See 1.  fc is a string, and strings do not have an attribute Corridor_S.  A record returned by a cursor in the feature class may though, so this might run:
for row in rowsFc:
    print(row.Corridor_S)

*valueTable is not a table, it is just a variable, so storing a value to it doesn't mean that anything is going to be written to a database table.  It is possible that you want something along the lines of:
for row in rowsTable:
    row.valueField = 42

Without the full error including traceback, it is not really possible to say what the error you're experiencing is, but your code certainly won't run unless you fix these errors.


text:
Q: Return well-formed numbers I found this in an interview questions forum:

Write a function to return well formed
  numbers of size n. A well formed
  number is one in which digit i is less
  than digit i+1, for example 123, 246, 349 etc

So here's how I would do it in Python:

*

*input number of digits (x)

*loop over all the numbers of x digits

*for each number n, if str(n) == "".join(sorted(str(n))), print number

So my question is... Is this method efficient and pythonic? I'm sure there should be a more elegant way out there, so any tips would be great appreciated.
Craig

A: How about this solution?
[int("".join(x)) for x in itertools.combinations("123456789", n)]

A: In my opinion, you've already lost if you're checking every number.
I'd implement this with a stack. Start by putting 1-9 on the stack. When you take a number off of the stack, add another number to it if you can following those rules. If it's n digits, then print it. If it's not n digits, put it back on the stack.
Let's say you grab 7 from the stack. 8 and 9 are the only numbers bigger than 7, so in o(1) time you can put 78 and 79 on the stack.

A: Your implementation doesn't ensure either the number of digits, or the strictly less than part of the well-formedness requirement.

Anyway, here's an efficient way to produce the sequence without any library functions (conversion to python is left as an exercise for the reader):
void find_well_formed(char* pfirst, char* pnext, int min, int slack, int digits_left)
{
    if (!digits_left) puts(pfirst);
    else for( int i = 0; i <= slack; ++i )
        find_well_formed(pfirst, pnext+1, (*pnext=min+i)+1, slack - i, digits_left-1);
}

char* result = malloc(n+2);
result[n] = '\n';
find_well_formed(&result[0], &result[0], '1', 9-n, n);
free(result);

Demo: http://ideone.com/0oZAV
If python is requiring more code to solve this than C++, something's wrong.

A: 1) You are trying to return well formed numbers 'up to' n digits in your approach, that is probably not the thing they were asking for
2) Sorting each number in that range is a bit silly. You may check whether each number is a well formed one by comparing the consecutive digits, which will take O(d) time for each number. However, sorting will definitely take more than that.

A: My thought would be to follow the logic:

*

*For a given number, the digits we can add to the beginning of it and still get a well-formed number are all less than the minimum digit in the number

*For a given well-formed number, the minimum digit is always the first digit

*The maximum number of digits we can add to a given number and keep it well-formed is equal to it's (minimum digit - 1)

Given the above, the following could be used to solve the problem:
def _well_formed_numbers(current_number_str, size):
    if size == 0:
        # we don't need to add any more
        return [current_number_str]
    if(len(current_number_str) == 0):
        min_digit = 9
    else:
        min_digit = int(current_number_str[0]) - 1
    if min_digit < size:
        raise Exception("can't add " + str(size) + " more digits to " + current_number_str)
    # Return a list of all the numbers resulting from recursively applying
    # this function to the "children" of the number we already have
    # Children are the input number with one valid digit added to the beginning
    # valid digits are [size .. min_digit], inclusive
    return reduce(lambda x,y: x+y, [_well_formed_numbers(str(digit) + str(current_number_str), size-1) for digit in range(size,min_digit+1)])

def well_formed_numbers(size):
    if size <= 0 or size >= 10:
        raise "invalid size for perfect number: " + str(size)
    return _well_formed_numbers("", size)

if __name__ == '__main__':
    import unittest
    class Tests(unittest.TestCase):
        def testMaxList(self):
            self.assertEqual(["123456789"], well_formed_numbers(9))

        def testEightList(self):
            self.assertEqual(sorted(['12345678', '12345679', '12345689', '12345789', '12346789', '12356789', '12456789', '13456789', '23456789']), sorted(well_formed_numbers(8)))

        def testOneList(self):
            self.assertEqual(sorted(["1","2","3","4","5","6","7","8","9"]), sorted(well_formed_numbers(1)))

        def testTwoList(self):
            self.assertEqual(sorted(['12', '13', '23', '14', '24', '34', '15', '25', '35', '45', '16', '26', '36', '46', '56', '17', '27', '37', '47', '57', '67', '18', '28', '38', '48', '58', '68', '78', '19', '29', '39', '49', '59', '69', '79', '89']), sorted(well_formed_numbers(2)))

    unittest.main()

Admittedly, Sven Marnach's answer is shorter and cleverer... but this one shows the thought process of a reasonable algorithm.

A: I'd propose the following:
the maximal value of the i-th digit is max[i] = 10 - (len - i)

*

*start with 1..n

*on each step, find the leftmost position i where digit[i] == max[i]

*if no such i is found, increase the rightmost digit

*if i is found, and it is = 0, we're done

*if i is found, and it is > 0, increase digit[i - 1] and fill the rest so that digit[j] = digit[j - 1] + 1

in (the intentionally ugly) python
a = [1, 2, 3]
n = len(a)

while 1:
    print a
    f = 0
    for i in range(n):
        if a[i] == 10 - (n - i):
            if i == 0:
                exit()
            else:
                f = 1
                a[i - 1] += 1
                for j in range(i, n):
                    a[j] = a[j - 1] + 1
                break

    if f == 0:
        a[n - 1] += 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the closure of the set $A=\bigcup_{n\in\Bbb N} A_n,$ where $A_n=\{(x,y)\in\Bbb R^2: y=x^2/n\}$
For each $n\in\Bbb N,$ we define $$A_n=\left\{(x,y)\in\Bbb R^2: y=\frac{x^2}n\right\}.$$
Let $A=\bigcup\limits_{n\in\Bbb N}A_n.$ Find $\overline A$.

My attempt:
Each $A_n$ is closed as a graph of the continuous function $f:\Bbb R\to\Bbb R, f(x)=\frac{x^2}n$ and, therefore, all the limit points of $A_n$ are in $A_n,$ that is, in $A$.
I want to show that $\overline{A}=B:= A\cup \{(x,0):x\in\Bbb R\},$ by arguing $\{(x,0):x\in\Bbb R\}$ is  a subset of the set $A'$ of all the limit points of $A$ and $B$ is closed.
Let's take a fixed $x_0\in\Bbb R$ and define $y_n=\frac{x_0^2}n.$ Then $y_n\to 0$ and hence $(x_0,y_n)\to (x_0,0).$ We constructed a sequence converging to an arbitrary $(x_0,0)$ and it follows that the whole $x$ axis contains limit points of the set $A$.
Now, I want to show $B=A\cup\{(x,0):x\in\Bbb R\}$ is closed. For that purpose, let's observe $\Bbb R^2\setminus B$.
Let's define $C_n:=\left\{(x,y)\in\Bbb R^2:\frac{x^2}{n+1}<y<\frac{x^2}n\right\}.$ We can write $$C_n=\underbrace{\left\{(x,y)\in\Bbb R^2:y>\frac{x^2}{n+1}\right\}}_{D_1}\cap\underbrace{\left\{(x,y)\in\Bbb R^2:y<\frac{x^2}n\right\}}_{D_2}$$
Both $D_1$ and $D_2$ are open (for each point $(x',y')\in D_1$ or $(x',y')\in D_2$ we can find the shortest distance $d$ from a bounding parabola and take $r<d$ so that $B((x',y'),r)\subseteq D_1$ or $B((x',y'), r)\subseteq D_2$) and therefore, $C_n$ is open $\forall n\in\Bbb N$.
Also, there is a set $E=\{(x,y):\in\Bbb R^2:y>x^2\}$ and the lower half plane $F=\{(x,y)\in\Bbb R^2: y<0\}$ both of which are open.
Finally, we see $\Bbb R^2\setminus B=E\cup F\cup\bigcup\limits_{n\in\Bbb N} C_n.$
$\Bbb R^2\setminus B$ is open as a countable union of open sets, which implies $B$ is closed.
Is there anything wrong with my answer?

A: Your proof that the $D_i$ are open is a little hand-wavy. Otherwise it is fine.
It is easier to prove that $B$ is closed.
Let $$C_n= \{(x,y)\mid 0\leq y\leq f_n(x)\}$$ and
$$B_n=A_1\cup \cdots \cup A_n\cup C_n$$
Show $C_n$ is closed, and includes all $A_i, i\geq n.$ Then $B_n$ is also closed and we can show easily that: $$B=\bigcap_{n=1}^{\infty} B_n$$
Hence $B$ is closed.

Here's an approach essentially the same as your approach, but using a uniform language to make it clearer.

Lemma: If $f:\mathbb R\to\mathbb R$ is a continuous function, then
$$D_{f}^+=\{(x,y)\in\mathbb R^2\mid y>f(x)\}\\ D_{f}^-=\{(x,y)\in\mathbb R^2\mid y<f(x)\}$$ are both open in $\mathbb R^2.$ Proof: The function $g(x,y)=y-f(x)$ is continuous, and $$D_f^{+}=g^{-1}((0,\infty))\\ D_f^{-}=g^{-1}((-\infty,0)).$$

Define $z(x)=0.$ Then:
$$\mathbb R^2\setminus B=D_{f_1}^+\cup \bigcup_{n=1}^\infty \left(D_{f_n}^{-1}\cap D_{f_{n+1}}^+\right)\cup D_z^-\tag1$$
So $\mathbb R^2\setminus B$ is open, and $B$ is closed.
$(1)$ is true because the $f_n$ are decreasing and converging to zero. So for any $(x,y)\notin B,$ either $y>f_1(x),$ or $f_n(x)>y>f_{n+1}(x)$ for some $n,$ or $y<0.$
$(1)$ is just a restatement of your approach, but I'm just using the one result about $D_f^{\pm}.$
This works for any decreasing sequence of functions such that $f_n(x)\to 0$ as $n\to \infty.$
More generally, for a topological space $X$ and a decreasing sequence $f_n:X\to \mathbb R,$ of functions which converges to a continuous function $f$, the closure of the union of the graphs in $X\times\mathbb R$ is gotten by just adding the graph of $f.$

It's true if $f_n$ is not decreasing, if it converges uniformly to $f.$
Then for any $\epsilon>0$ there is some $N$ such that for all $n>N,x\in X,$ $|f_n(x)-f(x)|<\epsilon.$ So:
$$C_{\epsilon}=\bigcup_{i=1}^N A_i \cup \{(x,y)\mid f(x)-\epsilon\leq y\leq f(x)+\epsilon\}$$
is closed, and contains all $A_i.$ But $$\bigcap_{\epsilon>0} C_{\epsilon}$$ is then also closed, and it just the union of the $A_i$ and the graph for $f.$

A more univseral result:

Theorem: f $f_n\to f$ and there is a sequence of decreasing decreasing continuous functions $g_m\to 0$ such that for every $m$ there is an $N_m$ so that for all $x$ and $n>N_m,$ $$f(x)-g_m(x)\leq f_n(x)\leq f(x)+g_m(x)$$ then the closure of $\bigcup A_i$ is just adding the graph of $f.$

This is more universal because it covers the uniform case (with $g_{m}(x)=\frac1m,$) and the monotone decreasing or increasing case (with $g_m(x)=|f_m(x)-f(x)|.$)
Then $$B_m=\bigcup_{i=1}^{N_m} A_i \cup \{(x,y)\mid | y-f(x)|\leq g_m(x)\}$$ is a sequence of closed sets and so:
$$B=\bigcap_{m=1}^\infty B_m$$ is closed.

For any $f_n\to f,$ we can define:
$$g_{m}(x)=\sup_{n\geq m} |f_n(x)-f(x)|.\tag1$$
This is defined for any $x,$ since $\{f_n(x)\}$ is convergent, and hence bounded. The $g_m$ are also nonnegative and decreasing, converging to $0.$
In most cases, it seems like $g_m$ will be continuous, in which case the result will hold.
But there are cases where it isn't. They are strange cases. Like if $f_n(x)$ is a triangle with base $[0,1/n]$ and with height $1.$ Pointwise, this sequence converges to $0,$ but no $g_n$ will be continuous at $0.$
And, indeed, the closure of these graphs will be $$\{(x,0)\mid x\in\mathbb R\}\cup \{(0,y)\mid y\in[0,1]\}$$
I wonder if the $g_m$ defined in $(1)$ being continuous is necessary and sufficient.


text:
Q: How to create multiple lists from data frame column value df1
    Ticker          Category
0      XOM           Group 1
1      CVX           Group 1
2  RDSA-GB           Group 2
3    BP-GB  Group 1, Group 2
4  EQNR-NO           Group 3
5    FP-FR           Group 4
6   ENI-IT  Group 3, Group 4
7      COP           Group 5

The result I'm going for would create lists of 'Ticker' based on the 'Category' column and name that list the 'Category' value while replacing spaces with "_"
Secondly, if there's an instance where Category has two values, such as "US Major, Euro Major" then how could i make sure that "Ticker" ends up in both Category lists?
Group_1 = ['XOM','CVX','BP-GB']
Group_2 = ['RDSA-GB','BP-GB']
Group_3 = ['EQNR-NO','ENI-IT']
Group_4 = ['FP-FR','ENI-IT']
Group_5 = ['COP']

Thanks!

A: Well you said name the list, I think you mean in a dictionary way? If it is the case try this :
import pandas as pd

df =  pd.DataFrame([["XOM","US Major"],
["CVX","US Major"],
["RDSA-GB","Euro Major"],
["BP-GB","Euro Major"],
["EQNR-NO","Euro Major"]],columns=["Ticker","Category"])

df_to_lists = df.groupby("Category")["Ticker"].apply(list)
lists_to_dict = dict(df_to_lists)
print(lists_to_dict)

output :
{'Euro Major': ['RDSA-GB', 'BP-GB', 'EQNR-NO'], 'US Major': ['XOM', 'CVX']}

If you don't want the dictionary, the df_to_lists outputs :
Category
Euro Major    [RDSA-GB, BP-GB, EQNR-NO]
US Major                     [XOM, CVX]
Name: Ticker, dtype: object

A: You can also use the power of loops like this (I assume my df is your df1):
lists_with_unique_vals = dict()
for cat in df.Category.unique():
    lists_with_unique_vals[cat.replace(' ', '_')] = list(df[df['Category']==cat]['Ticker'].unique())

The result is following:
>> print(lists_with_unique_vals)
{'US_Major': ['XOM', 'CVX'], 'Euro_Major': ['RDSA-GB', 'BP-GB', 'EQNR-NO']}

A: Following up on @nassiam's code to handle cases where there can be multiple categories,
import pandas as pd

df =  pd.DataFrame([["XOM","US Major"],
["CVX","US Major"],
["RDSA-GB","Euro Major"],
["BP-GB","Euro Major"],
["EQNR-NO","Euro Major"],
["ABC-XYZ", "Euro Major, US Major"],
["DEF-GHI", "Euro Major, US Major"]], columns=["Ticker","Category"])

df_to_lists = df.groupby("Category")["Ticker"].apply(list)
lists_to_dict = dict(df_to_lists)
print(lists_to_dict)

# Till here it is the same code as @nassiam pointed out

# To handle multiple-valued category
keys = lists_to_dict.keys()
for key in keys:
    categories = [x.strip() for x in key.split(',')]
    if len(categories) > 1:
        for cat in categories:
            if cat in lists_to_dict:
                lists_to_dict[cat] += lists_to_dict[key]
            else:
                lists_to_dict[cat] = lists_to_dict[key]
        lists_to_dict.pop(key, None)

# To replace space with underscore
for key in lists_to_dict:
    lists_to_dict[key.replace(" ", "_")] = lists_to_dict.pop(key)

It is under the assumption that the first column Ticker has unique values. Otherwise, when appending the lists use set to make them unique.
I hope this helps.


text:
Q: Permission denied (for entry point) on container start Since a few days, I can't run any docker containers on my machine (Ubuntu 18.04). Whenever I try to run/start a container, I receive an error which says that the entrypoint file can't be executed:
$ sudo docker run --name test nginx
sh: 0: Can't open /docker-entrypoint.sh

or
$ docker run --name test2 mongo:4.0
WARNING: Error loading config file: /home/myUser/.docker/config.json: stat /home/myUser/.docker/config.json: permission denied
/bin/bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

The second error message leads me to the conclusion, that I might have access problem to the whole docker VM. So, this is the current permission setting on the .docker folder:
$ sudo ls -l /home/myUser/.docker
total 4
drwx------ 5 root root 4096 Nov 21  2019 machine

From my point of view, it should be fine (at least when the docker run/start command is executed as superuser...). Hence, it must be somewhere else. <= WRONG! (Edited: No warning should be ignored, even less one where an error is indicaed...)
What I tried/consulted so far:

*

*reinstall docker => worked fine until the next reboot...

*this post for permission issues when the entrypoint file is copied into the container from the host (which doesn't apply to my case where no pre-built image is started...)

*desperately scraping the web for other relevant posts without luck

I'm open to any suggestions and would be glad to deliver further details about my setting if necessary.

Edit: I followed the instructions on docker for the installation and used apt-get.
I don't get any results when executing env | grep DOCKER...
Below the result of docker info:
$ docker info
WARNING: Error loading config file: /home/myUser/.docker/config.json: stat /home/myUser/.docker/config.json: permission denied
Client:
 Debug Mode: false

Server:
 Containers: 9
  Running: 0
  Paused: 0
  Stopped: 9
 Images: 21
 Server Version: 19.03.11
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version:
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.3.0-53-generic
 Operating System: Ubuntu Core 16
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 15.54GiB
 Name: my-laptop
 ID: ****:****:some:code
 Docker Root Dir: /var/snap/docker/common/var-lib-docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

Edit 2 (or rather a fun fact): I can run the hello-world example from docker. So, the problem is that the permission inside the docker container aren't enough... why?
Edit 3: Thanks to @Sysadmin, I could remove the warning during the load of config.json by following the instructions of this post
Edit 4: Interesting to see, is that a simple image created by myself works fine. Below the example content I used:
FROM alpine
CMD ls -l /

A: In your sudo ls -l /home/myUser/.docker there is no config.json.
I have a relatively vanilla Ubuntu 18 with docker and there is a config.json in my ~/.docker. Try and create one to eliminate the warning and see of the error goes away as a result.

A: You need to copy the bash script file in the location where the VM can access the file, preferably globally like so:
COPY docker-entrypoint.sh /usr/local/bin/


text:
Q: FileNotFoundException was unhandled - But the file is there I'm struggling with this. My WPF app, in debug/release works fine. After I publish it, via InstallShield Express, I get a runtime exception and the program crashes.
When the program crashes, I can choose to debug the program in Visual Studio, it breaks in the RelayCommand which looks like
public class RelayCommand : ICommand
{
    public Action<object> _execute;

    public RelayCommand(Action<object> execute)
    {
        this._execute = execute;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        this._execute(parameter); // where the breakpoint is
    }
}

The error message is

FileNotFoundException was unhandled
  Could not load file or assembly 'TaskScheduler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified

I'm lost as to why this is. I have other commands on the page, and they are all set up in the following manner
   public ICommand SaveScheduledTaskCommand { get; set; }
   public ICommand OpenFileCommand { get; set; }

    #region Constructor

    public MyApp()
    {
        OpenFileCommand = new RelayCommand(new Action<object>(OpenFile)));
        ScheduledTaskCommand = new RelayCommand(new Action<object>(SaveScheduledTask));
    }

    #endregion

    private void OpenFile(object o)
    {
        MessageBox.Show("OF"); //works fine
    }

    private void SaveScheduledTask(object o)
    {
        MessageBox.Show("TS"); //never shows
        TaskScheduler ts = new TaskScheulder();
        //more code
    }

I guess the issue is with the TaskScheduler.dll (based upon the error message) but, the .dll exists in the installed folder (under c:\Program Files\Compamy\MyApp)...
I don't think it matters but, the TaskScheduler.dll is saved outside of my project (it is saved on the desktop) but I assume this is not relevant as the installer will take a copy of it and save it to the program Files folder any way?
I used InstallShield Express to create the installer and other than this, it works fine. I also another 3rd party dll, XCeed, and this work fine in my app.
I'm totally lost as to what I can do as I can't see how I can fix the code! Why can't the application "see" the dll?

A: Since TaskScheduler is included this is because you are missing to include an assembly that is referenced by the TaskScheduler.dll.
Debug Step 1
Inspect the dependencies of TaskScheduler.dll and make sure to include all dependencies in the installation package (except framework assemblies).
Debug Step 2
If you cannot inspect the dependencies of TaskScheduler.dll then follow this guide, How to enable assembly bind failure logging (Fusion) in .NET, to find out which assemblies are missing.


text:
Q: Regex PHP remove all float numbers Learning regex in PHP. Here's my code:
 header('Content-type: text/plain; charset=utf-8');
 $lines = file('datatest.txt');
 $lines = preg_grep("/word/", $lines); //finds words that I need, including numbers
 $lines = preg_replace('/\d/', '', $lines); //replaces all numbers with ''
 foreach ($lines as $name) {
    echo "$name";
}

I have a lined text, every line starts with nubmer, for example:
1.1. Name
2.0. Name2
2.3. Name3

Removed digits, but comma stays, now it looks like this:
.. Name
.. Name2
.. Name3

Thanks!

A: You can use:
$lines = preg_replace('/[\d.]+/', '', $lines); //replaces all numbers with ''

A: Try this: This will remove numbers and dot only from the starting of the string
$lines = preg_replace('/^\s*[\d\.]+/', '', $lines);


text:
Q: Retain textbox values on page refresh I have a textbox in a user control uc1. I have embedded this uc1 in a page called default.aspx. My issue is after running the application and entering some data in the textbox, when refresh the page i would like to show the values that i have entered in the textbox and not clear the textbox. I would like help with code on how to achive this. Thanks in advance for your help.

A: Create a global variable at the top of your aspx.cs page:
 public string textboxValue
    {
        get
        {
            if (ViewState["textboxValue"] != null)
                return ViewState["textboxValue"].toString();
            else
                return "";
        }

        set
        {
            ViewState["textboxValue"] = value;
        }
    }

Then, in PageLoad(), assign textboxValue a value:
protected void Page_Load(object sender, EventArgs e)
    {
if(!IsPostBack)
textboxValue = MyTextBox.Value;
else
MyTextBox.Value = textboxValue;
}

You can also use textboxValue to assign the value of MyTextBox at any time, or use it in any other way that might be useful to you.

A: The default behavior for all asp.net server side controls (runat="server") is to maintain their state. If your textbox is being cleared when your page refreshes, you are likely clearing that value yourself in code.
Are you dynamically adding the textbox or user control? If so, are you doing that during PageInit? Adding them later may cause them to lose state.

A: I was able to refresh the page without clearing the value in textbox. I did it as below:
I created a public property in the UC1.vb as below:
Public Property textbox_value() As String
    Get
        If Session("textbox1") IsNot Nothing Then
            Return Session("textbox1").ToString()
        Else
            Return ""
        End If
    End Get
    Set(value As String)
        Session("textbox1") = value
    End Set
End Property

And in the page_load event of the user control i added the code below:
        If IsPostBack Then
            textbox_value= textbox1.Text
        ElseIf Not IsPostBack Then ' First time the page is loaded or when the page is refreshed
            textbox1.Text =  textbox_value
         End If
Hope it helps.


text:
Q: Conditional statement embedded in data-bind I'm binding table rows using foreach statement. The row HTML markup is:

I would like to do something like this:

 0 {rowClick: $parent.editCost} ">

Is something like this possible?

A: Of course, you can do it :

 0) $parent.editCost($data);} ">

If rowClick is a cutom  binding, you can do that :

I hope it helps.


text:
Q: Shouldnt my Random() write random code? c# So im going through a tutorial where you call methods, and withing these methods you want to do use the Random(), in the tutorial he calls his method multiple times and get random results, but when I do it, i get the same result multiple times, all the time. Am I doing something wrong?
static void Main(string[] args)
        {
            MeetAlien();
            Console.WriteLine("---------------");
            MeetAlien();
            Console.WriteLine("---------------");
            MeetAlien();

        }

        static void MeetAlien()
        {
            Random numberGen = new Random();
            string name = "X-" + numberGen.Next(10, 9999);
            int age = numberGen.Next(10, 500);

            Console.WriteLine("Hi Im " + name);
            Console.WriteLine("Im " + age + " age old");
            Console.WriteLine("And im an alien :)");
        }

A: That's a bad piece of sample code, if it's a faithful reproduction from a tutorial.
The problem is that it's repeatedly constructing Random objects without a seed. As the docs state:

because the first two Random objects are created in close succession, they are instantiated using identical seed values based on the system clock and, therefore, they produce an identical sequence of random numbers.

(It's talking about a different example, but the explanation is the same)

Further down, it's discussed that .NET Framework acts differently to .NET Core, so that indicates that you're running this code on .NET Framework. Maybe the tutorial is meant to be for .NET Core?


text:
Q: Error in make file for device driver Hello world I have simple code with device driver hello world with a make file.it was executed well in case of 12.04 LTS but recently i have upgrade my ubuntu to 14.04 after this the same program not able to compiled.
with error message on
make

make -C /lib/modules/3.13.0-45-generic/build M= modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-45-generic'
make[2]: *** No rule to make target `/usr/src/linux-headers-3.13.0-45-generic/arch/x86/syscalls/syscall_32.tbl', needed by `arch/x86/syscalls/../include/generated/uapi/asm/unistd_32.h'.  Stop.
make[1]: *** [archheaders] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-45-generic'
make: *** [all] Error 2

Thanks in advance......

A: your make file does't work for other versions of the kernel since the kernel library modules will be in /lib/modules/kernelversion/build.
so you should use
make -C /lib/modules/"should be the current running kernel"/build
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

Which will automatically loads the current running kernel version using "shell uname -r".
Sample makefile
KERNELDIR := /lib/modules/$(shell uname -r)/build
CLEANFILE := *.dis *.o *.ko *.mod.* *.symvers *.*.old
obj-m := hello.o

    default:
            make -C $(KERNELDIR)  M=$(CURDIR) modules

    clean:
            rm -f $(CLEANFILE)

A: You are expected to post the content of your Makefile in your question.
Anyways, I think, there is some problem in your Makefile. Instead of specifying the kernel version as 3.13.0-45-generic , you should write $(shell uname -r) so that it can dynamically get the currently running kernel version. With upgrading ubuntu, your kernel version changed. So, it's not working anymore.
Create you Makefile as follows provided your device driver program file name is hello.c
obj-m += hello.o
all:
    make -C /lib/modules/$(shell uname -r)/build M=$(CURDIR) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(CURDIR) clean

The execution of 'make' command starts by changing its directory to the one provided with the -C option that is /lib/modules/$(shell uname -r)/build which is your kernel source directory and The M= option causes that makefile to move back into your module source directory as CURDIR(current directory) is always set to current working directory.
Reply if it's still not working. This pdf can help you as a quick reference if you are beginner in this field. And if you want to become an expert in linux device driver programming in future, follow This Book. It's worth reading.


text:
Q: Qt quick project - how to invoke cpp function in qml file? I' ve created quick project in Qt, selected from wizard at the begin, when Qt creator is started.
Qt creator create project. There are qmlapplicationvierwer subproject and qml files in main project. I want to add new cpp source and header files (MainMenu.cpp and MainMenu.h) to project and then invoke function from these files in main.qml file.
How I can register new type in qmlapplicationviewer and invoke function from ManiMenu ?
qmlapplicationvierwer has only few function:
QApplication app(argc, argv);
QmlApplicationViewer viewer;
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/PUTest/main.qml"));
viewer.showExpanded();

return app.exec();

and:
viewer.addImportPath(const string &path);

Better way is not create project without project wizard ?
Thanks

A: Normally, you use this wizard to create QML only projects.
The QmlApplication viewer is just a lightweight C++ wrapper around your QML file so a binary is generated and the QML file is loaded.
There's not much magic to do that on your own, see:
https://doc.qt.io/archives/qt-4.7/qtbinding.html
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>

int main(int argc, char *argv[])
{
 QApplication app(argc, argv);

 QDeclarativeView view;
 QDeclarativeContext *context = view.rootContext();
 context->setContextProperty("backgroundColor",
                             QColor(Qt::yellow));

 view.setSource(QUrl::fromLocalFile("main.qml"));
 view.show();

 return app.exec();
}

And with setContextProperty you can ad global QML types via cpp...
Of course you can also reuse the QmlApplicationViewer. The Mainclass QmlApplicationViewer is derived from QDeclarativeView, so you directly have access to the context in this class.
So like in the example above, it should be possible to use:
QDeclarativeContext *context = this.rootContext();
context->setContextProperty("backgroundColor", QColor(Qt::yellow));

somewhere in the QmlApplicationViewer costructor or afterwards (didn't try it for now, let me know if it doesn't work).


text:
Q: How to find MYSQL Logs for Drop Delete Record? I am using SQlyog Ultimate for Mysql GUI. I want to know who is deleting, Dropping table and record. I want to track the User Ip and Name.
If there is any method to track please share with me.
I found some Link but not able to understand
How to show the last queries executed on MySQL?
Thanks
Sitansu

A: You must enable query logging on server as described on the official page:
https://dev.mysql.com/doc/refman/5.7/en/server-logs.html
Here general logging is the easiest approach that can be used to resolve your objective. Link shared by you shows two different methods of achieving the same. You can use following queries as root user to get what you want
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';

select event_time,user_host,argument
from mysql.general_log
where command_type='Query' and
upper(argument) rlike '(DROP|DELETE|TRUNCATE)+';

Beware that it will fill server disk space very faster.

A: SQlyog Ultimate for Mysql GUI - is good tool, but haven't any relations with Your question.
With MySQL You are restricted with not a big list of options:

*

*You can enable general log, but in this case You can easy kill server performance, because server would log everything (absolutely) and also size of logs would be grow dramatically on a busy server

*You can use MariaDB audit plugin, it excellent, but it part of subscription edition (and it not cheap). I not fully understand license policy of MariaDB, but You could request direct, they answer good.

*You can switch to MySQL Enterprise it also contain audit plugin

*You can test McAfee audit plugin (https://github.com/mcafee/mysql-audit)


text:
Q: Rubygems blocked by Norton DNS I ran
$ gem fetch -V github-linguist
GET http://rubygems.org/latest_specs.4.8.gz
302 Moved Temporarily
GET http://production.s3.rubygems.org/latest_specs.4.8.gz
200 OK
ERROR:  While executing gem ... (Zlib::GzipFile::Error)
    not in gzip format

then to my shock I opened the link in my browser and see
this message

Norton DNS
Malicious Web Site Blocked
You attempted to access: production.s3.rubygems.org
This is a known malicious web site. It is recommended that you do NOT visit
this site. This site points to production.s3.rubygems.org.s3.amazonaws.com,
which is malicious.

On pencil's suggestion I ran
namebench and have switched to OpenDNS-2.

A: Probably someone used AWS to distribute malware and some buggy automatism now blockes *.amazonaws.com
Must be a filter anywhere between you and Amazon (Router/Firewall, Proxy, ISP, Name Server, ...). Start by using different name servers (like Google's 8.8.8.8).


text:
Q: how to rename a module in the url with mod_rewrite I'm using MVC with /<module>/<controller>/<action>/ have a module at example.com/module/whatever, and I need to 'rename' it to example.com/module-a/whatever. The whole application is already written, so I can't go through and change it everywhere in my code, so I'm hoping to do it with mod_rewrite. I've tried the following
RewriteCond %{THE_REQUEST} ^GET\ /module/
RewriteRule ^module/(.*) /module-a/$1 [L,R=301]

which did what I wanted as far as redirecting all urls like example.com/module/whatever to example.com/module-a/whatever, but now I need all requests at 'module-a' to be internally rewritten as 'module'. It also needs to work for the module root (i.e. example.com/module with no trailing slash). Is this possible? I added
RewriteRule ^module-a/(.*)$ module/$1

directly beneath the above condition and rule, but when the page is accessed, it still says the module 'module-a' is not found.

Edit:
I have a few more rules below those, I wouldn't think they would affect this, but here they are anyway:
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Solution
I ended up using
RewriteCond %{THE_REQUEST} ^GET\ /module/
RewriteRule ^module$ /module-a [L,R=301]
RewriteRule ^module/(.*) /module-a/$1 [L,R=301]

to redirect all links from module to module-a. I had to do it with 2 rules because I don't know regex well enough to combine them, handling the special case of the url example.com/module.
To rewrite internally, the original rule I had would normally work, but Zend seems to do some stuff that overrides that, so I had to handle it with routes. See rename a zend module with routes

A: If I understand correctly then you've gone about this from the wrong direction. I am also not clear on the purpose of your RewriteCond
You want all module-a/* requests to be processed internally as module/*, so all you need is a simple rewrite::
RewriteRule ^module-a/?(.*) /module/$1 [L]
I suspect the problem you are having is the internal links on the site all reference /module/ rather than /module-a/, but putting a 301 there will cause no end of problems (not least with search engines), and with the subsequent rewrite you may fall into circular references.  You are much better off changing the link code in your app (if you have a link abstraction class), or at worst using output buffering to swap all links out before rendering the page.
Note: The second rule below the above is not being processed if the first matched, as [L] causes mod_rewrite to cease processing if that rule is matched.


text:
Q: How can I allow sha1WithRSAEncryption during nginx ssl_client_verify? My nginx server is successfully verifying most (expected) client certificates, but some older client certificates are getting "400 Bad Request The SSL certificate error" and producing this log entry -- "client SSL certificate verify error: (68:CA signature digest algorithm too weak)"
Is there a way to allow older signature digest algorithms?
Running openssl list -digest-algorithms shows sha1RSA, but it isn't included in the TLSv1.2 -  Handshake Protocol - Certificate Request Message.
Versions:
 - helm chart nginx-ingress v1.1.3
 - nginx-ingress-controller v0.21.0
 - nginx v1.15.6
 - openssl 1.1.1
-- Update --
To verify client certificates that are signed with weak digest algorithms, append @SECLEVEL=0 to your ssl_ciphers list, i.e. ssl_ciphers 'HIGH:!aNULL:!MD5@SECLEVEL=0';
discussion and openssl reference.
I don't understand the full implications of @SECLEVEL, so best solution is to push for updated client certificates!


text:
Q: RIA Creates same instance twice in Silverlight class Profile { string name; Book[] books}

class Book { string name }

Two separate Profiles (A and B) both have a relation to the same book.
When I load the profiles one by one from Silverlight using WCF/RIA. I end up with two book object, with the same name. (same book!). I want RIA to detect that the book is already present in silverlight and use the existing instance instead of creating it a second time.
They are POCO (complex object-not in DB).
How do I tell RIA that the Name is unique and that there can not be two instances in Silverlight(RIA client side) with the same name?
UPDATE
Since asking I have implemented a WORKAROUND - I dont not really consider it a elegant solution though! But here it is:
The callback method on GetProfile is replaced with a method that traverses all profile.books and check if each book already exist in a local Dictionary. If the book exists locally the local book is used and the second instance is deleted. If it doesn't the book is added to the dictionary and used.
SOLUTION
I create my own Book-class clientside, then convert the RIA-created bookss to my own book-type. When I send the updated Books back to the server, I create instances of RIA Books, and before updating any properties I call OnDeserializing() and OnDesriallized() after. That allows me to edit the RIA-Book.

A: SOLUTION
The callback method on GetProfile is replaced with a method that traverses all profile.books and check if each book already exist in a local Dictionary. If the book exists locally the local book is used and the second instance is deleted. If it doesn't the book is added to the dictionary and used.
I create my own Book-class clientside, then convert the RIA-created bookss to my own book-type. When I send the updated Books back to the server, I create instances of RIA Books, and before updating any properties (like FavouriteBook) I call OnDeserializing() and OnDesriallized() after. That allows me to edit the RIA-Book.


text:
Q: How to find subgraphs of strongly connected components using networkx as nx.strongly_connected_component_subgraphs() is now removed in version 2.4, I have tried using (G.subgraph(c) for c in strongly_connected_components(G)) similar to what we do for connected component subgraphs. but this just shows strongly_connected_component_subgraphs is deprecated. What to do for strongly connected subgraphs in networkx? sorry if this question is repeated.

A: Using nx.strongly_connected_components as in your shared approach, should be fine:
(G.subgraph(c) for c in nx.strongly_connected_components(G))

This function is included in the latest version, 2.5, and does not rely on any other deprecated methods, as you can see in the source code. So make sure you aren't using the method that is actually raising the deprecation warning, nx.strongly_connected_component_subgraphs.


text:
Q: What is this String.Replace method doing? I'm trying to port this Javascript code to another language (Xojo):
Vertices.fromPath = function(path, body) {
    var pathPattern = /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/ig,
        points = [];

    path.replace(pathPattern, function(match, x, y) {
        points.push({ x: parseFloat(x), y: parseFloat(y) });
    });

    return Vertices.create(points, body);
};

I know that path should be a string containing x y pairs of numbers (in SVG format like "L 50 25 L 100 10"). Am I correct in thinking that this would split the earlier string into two objects 50,25 and 100,10 and then push them onto the points array?

A: Not sure if you know that /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/ig is a regex search string.
If I decypher that quickly, I'd say that it seeks an optional "L" at the start, then optional whitespace, then a number (i.e. anything containing a digit, period, minus or "e"), whitespace or comma, another number, and the parentheses around the numbers mean that these are the matched values passed to the function in the replace() call. The "ig" at the end are options, where "i" means to ignore case IIRC.
So, that code only seems to fetch two numbers, optionally preceded by an "L". It then reads those numbers into x and y, and appends them to the points array.
In Xojo you'd have to do that in a loop (Xojo has no support for local functions), using the RegEx class to parse the string repeatedly. To convert the scanned numbers into doubles, use the Val() function.

A: While it is true that the regular expression in your question will match two numbers that follow a single 'L' letter, it will also match many other things that cannot be parsed as valid numbers.
You are correct, this code will create two objects that have their X and Y properties populated from the matched numbers.
Using Realbasic.Points to hold the coordinates, this functionality could be achieved by the following Xojo snippet:
Dim inString As String = "L 50 25 L 100 10"
Dim outArray(-1) As Realbasic.Point

Dim rx As New RegEx()
Dim match As RegExMatch
rx.SearchPattern = "L?\s*([\-\d.e]+)[\s,]*([\-\d.e]+)*"
match = rx.Search(inString) // Get the first matching part of the string, or nil if there's no match
While match <> nil
    dim x As Integer = match.SubExpressionString(1).Val() // X coordinate is captured by the first group
    dim y As Integer = match.SubExpressionString(2).Val() // Y coordinate is captured by the second group
    dim p As new REALbasic.Point(x, y)
    outArray.Append(p)
    match = rx.Search() // Get the next matching part, or nil if there's no more
Wend

If you need to match only numbers and want to prevent errors during the String->Double conversion, you should update the regex pattern to something like this:
"L?\s+(\-?\d+(?:\.\d+)?(?:e-?\d+)?)[\s,]+(\-?\d+(?:\.\d+)?(?:e-?\d+)?)"

The original pattern would match 'Lee ...---...', this updated one would require at least one space between the 'L' and the numbers, and would not match on characters that could be parts of a number, but they do not form a valid numeric representation.


text:
Q: Rails - Sort by a condition and limit? I am trying to fetch only 5 records from a table, and I need to ensure that the sort order is in a way that a specific record will always be at position 0.
How do I achieve this? My DB is MYSql
User.order("IF(id == #{current_user.id}) DESC").take(5)

A: There might be a way to do this natively with SQL/MySQL, but I'd simply call two queries:
users = User.where.not(id: current_user.id).take(4) # perform order/etc
users.unshift(current_user)                         # or find specific record


text:
Q: How can I prevent a community user from creating an account? I am going through the community user setup and I found that the standard profile has access to read, edit and create accounts.
So I proceeded to edit the profile, but I am not able to take away the permissions. I want the user to have access to read the account, but I don't want the user to create or edit the account.
In this particular org, we have used a profile for issuing permissions to community users.
I have highlighted the license applied on this org.
This is the help documentation link I have found.

A: There are two ways to solve this.
One method is via use of Permissions Sets. These have not been implemented in this particular org.
The other method is clone the customer community plus profile and create another profile. In this newly created profile, take away the permissions for Create and Edit from the objects.
Now the community user should not be able to create an account.


text:
Q: Pandas Groupby -- efficient selection/filtering of groups based on multiple conditions? I am trying to

*

*filter dataframe groups in Pandas, based on multiple (any) conditions.

but I cannot seem to get to a fast Pandas 'native' one-liner.
Here I generate an example dataframe of 2*n*n rows and 4 columns:
import itertools
import random

n = 100
lst = range(0, n)
df = pd.DataFrame(
    {'A': list(itertools.chain.from_iterable(itertools.repeat(x, n*2) for x in lst)),
     'B': list(itertools.chain.from_iterable(itertools.repeat(x, 1*2) for x in lst)) * n,
     'C': random.choices(list(range(100)), k=2*n*n),
     'D': random.choices(list(range(100)), k=2*n*n)
    })

resulting in dataframes such as:
    A   B   C   D
0   0   0   26  49
1   0   0   29  80
2   0   1   70  92
3   0   1   7   2
4   1   0   90  11
5   1   0   19  4
6   1   1   29  4
7   1   1   31  95

I want to

*

*select groups grouped by A and B,

*filtered groups down to where any values in the group are greater than 50 in both columns C and D,

A "native" Pandas one-liner would be the following:
test.groupby([test.A, test.B]).filter(lambda x: ((x.C>50).any() & (x.D>50).any()) )

which produces
    A   B   C   D
2   0   1   70  92
3   0   1   7   2

This is all fine for small dataframes (say n < 20).
But this solution takes quite long (for example, 4.58 s when n = 100) for large dataframes.
I have an alternative, step-by-step solution which achieves the same result, but runs much faster (28.1 ms when n = 100):
test_g = test.assign(key_C = test.C>50, key_D = test.D>50).groupby([test.A, test.B])
test_C_bool = test_g.key_C.transform('any')
test_D_bool = test_g.key_D.transform('any')
test[test_C_bool & test_D_bool]

but arguably a bit more ugly. My questions are:

*Is there a better "native" Pandas solution for this task? , and

*Is there a reason for the sub-optimal performance of my version of the "native" solution?

Bonus question:
In fact I only want to extract the groups and not together with their data. I.e., I only need
    A   B
    0   1

in the above example. Is there a way to do this with Pandas without going through the intermediate step I did above?

A: This is similar to your second approach, but chained together:
mask = (df[['C','D']].gt(50)         # in the case you have different thresholds for `C`, `D` [50, 60]
         .all(axis=1)                # check for both True on the rows
         .groupby([df['A'],df['B']]) # normal groupby
         .transform('max')           # 'any' instead of 'max' also works
        )

df.loc[mask]

If you don't want the data, you can forgo the transform:
mask = df[['C','D']].min(axis=1).gt(50).groupby([df['A'],df['B']]).any()

mask[mask].index

# out
# MultiIndex([(0, 1)],
#           names=['A', 'B'])


text:
Q: UI performance with large image data Some days ago, I built a small program for some of my colleagues to analyse cell images. One minor part of the user interface was the selection of the region of interest. The images are large and need to be analysed in full-size but for the selection, you don't need to see them in full-size.
The most direct way to implement this is to use the original image and only show it in a smaller size. With this the original image dimensions are preserved and I can use the original coordinates for the selection of the region. Let me give a small function that does nothing more than showing an image and a rectangular region that can be moved:
roiSelector[img_] := DynamicModule[{
   pt = Round[ImageDimensions[img]/2],
   dim = Round[ImageDimensions[img]/6]
  },
  LocatorPane[Dynamic[pt],
   Show[
    HighlightImage[
     img,
     Dynamic@{Rectangle[pt - dim, pt + dim]}
    ], ImageSize -> 512]
  ]
]

img = Import["https://media.mehrnews.com/d/2019/09/04/3/3227015.jpg"];
roiSelector[img]

This selection box is far from being responsive although images that large are really common when working in science. Things like that are one reason why I believe that Mathematica is great for prototyping but doesn't scale well in real life applications. In this specific case, the user interface itself should be really fast, because it has nothing more to do than to display an image of size 512 and draw a frame above it. Although it almost looks the same, the responsiveness of a version that really uses a 512 pixel image is better
roiSelector[ImageResize[img, 512]]

Surprisingly, at least on my machine the effect can be observed when using too small images as well. The 100px version below shows the some sluggishness as well.
roiSelector[ImageResize[img, 100]]

Question: Is there better way to highlight something in large images dynamically beside the code shown above? (I have tested some other ideas myself without much success)
Side notes:
If you change my example slightly and put the inner Dynamic@ in front of the Show and evaluate the roiSelector[img] then the whole FE becomes slow. So if you have it arranged like I do

then even editing the code in the middle becomes horribly slow. Now imagine that we loaded and displayed only one single image which is usually not the case in a real application.
My system is Mathematica 11 on OSX.

A: Another approach is to set the red box to be a locator. Then you can display the image and use the red-box-locator to define the region of interest. This speeds it up a little. The major problem seems to be that the image resizing is done inside the dynamic environment. This can be helped by resizing the image once (and then using that smaller version for display). The box moves around almost instantaneously.
img = Import["https://media.mehrnews.com/d/2019/09/04/3/3227015.jpg"];
box = Graphics[{Opacity[0], Rectangle[{0, 0}, {1, 1}], Red,
                Opacity[0.5], Rectangle[{0.3, 0.4}, {0.6, 0.6}]}];
imgSmall = ImageResize[img, 512];
Manipulate[imgSmall, {pt, Locator, Appearance -> box}]

A: A lot can be tweaked, but it is hardly ever straightforward:
img = Import["https://media.mehrnews.com/d/2019/09/04/3/3227015.jpg"]

roiSelector[img_] := DynamicModule[
  {v,
   pt1, pt2,  dim,
   imgDim = ImageDimensions@img,
   w = 300, wI,  h = Automatic, ratio
  }
  ,
  ratio = #/#2 & @@ imgDim;
  dim = Round[w imgDim/imgDim[[1]]];
  pt1 = .3 dim; pt2 = .7 dim;
  wI = w;

  EventHandler[
    Framed @ Pane[
        Dynamic[
          Show[
            HighlightImage[
               ImageResize[img, {wI, Automatic}],
               { Dynamic @ Rectangle[pt1, pt2],
                 Locator @ Dynamic[ pt1,
                    {(v = pt2 - pt1) &, (pt1 = #; pt2 = pt1 + v) &, None}
                 ],
                 Locator @ Dynamic @ pt2
               }
            ],
            ImageSize -> {w, Automatic}
          ],
          TrackedSymbols      :> {wI},
          SynchronousUpdating -> False,
          ImageSizeCache      -> dim
        ]
     ,
     ImageSize -> Dynamic[{w, h}, ({w, h} = {1, 1/ratio} #[[1]]) &],
     AppearanceElements -> All
     ]
   ,
   {"MouseUp" :> ({pt1, pt2} = {pt1, pt2} w/wI; wI = w;)},
   PassEventsDown -> True
   ]
  ]

Grid[{{#, #}, {#, #}}] & @ roiSelector @ img


text:
Q: Error 500 al configurar .htaccess: "AH00124: Request exceeded the limit of 4 internal redirects due to probable configuration error." Estoy intentando configurar una URL amigable, cuando lo realizo, me da el error 500 del servidor.
Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^recovery/([a-zA-Z0-9-z\-]+)/?$ recovery?token=$1 [L,QSA,NC]

En el log de Apache aparece el siguiente error:

AH00124: Request exceeded the limit of 4 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

¿Alguien sabe a qué se debe este error?

A: La regla que tienes en .htaccess es que si la url empieza por recovery envía la petición a recovery con un token. Es decir a la misma dirección y esto es redirección cíclica. Soluciónalo cambiando el segundo recovery por algo otro.


text:
Q: C# WPF How to create a generic method that can create a specific Window I currently have this method in my App.Xaml.Cs project:
private void ApplicationStart(object sender, StartupEventArgs e)
{
            Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

            var NetworkConnectionView = new NetworkConnectionView();
            NetworkConnectionView.ShowDialog();

            if (NetworkConnectionView.ConnectionNetWorkServerInternetState == ConnectionStatus.NetworkConnectionSuccess)
            {
                var mainWindow = new MainWindow();
                Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
                Current.MainWindow = mainWindow;
                mainWindow.Show();
            }

            else if(NetworkConnectionView.ConnectionNetWorkServerInternetState == ConnectionStatus.NetworkConnectionFail)
            {
                NetworkErrorView networkErrorWindow = new NetworkErrorView();
                networkErrorWindow.ShowDialog();
                Current.Shutdown(-1);
            }
}

I would like to be able to outsource all its content in a static method contained in a library. Like this :
private void ApplicationStart(object sender, StartupEventArgs e)
{
    NetWorkTools.MyExternalMethod();
}

But I don't know how to do it because MainWindow only exists in my main WPF project ( and also Current). All other method/class are created from my Library, so I wouldn't have a problem referencing them.

A: As I see it you're trying to "start" the Mainwindow from another function. This works for all "Windows" by first creating an instance of them and then showing them as well.
Mainwindow mw = new Mainwindow();
mw.show();

A: If you want it to be generic, then do it like this:
private void ApplicationStart<TWindow>() where TWindow : Window, new()
{
   ...
   Application.Current.MainWindow = new TWindow();
   ...
}


text:
Q: How to convert 32-bit VBA code into 64-bit VBA code I'm trying to run a macro code that worked in 32-bit (used to work) but since I just upgrade my machine, I'm using a 64-bit Excel  and this code is not working anymore. I need to make this work in 64-bit. Please help me to fix this please:
AdoConn
     .ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &  strFileSource & ";Persist Security Info=False"
     .Open

It shows the problem in .Open
Thank you so much.

A: You may find an incompatibility with the Microsoft.Jet.OLEDB.4.0 (32 bit) driver in 64 bit OS.
You can use the Microsoft.Jet.OLEDB.4.0 (32 bit) driver on a 64 bit OS, but you must force your application to build in in 32 bit mode.
If you don't want to, or cannot do that, there is a 64 bit version of the driver available (Microsoft.ACE.OLEDB.12.0) which works on 32 & 64 bit OS.
Try changing:
.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &  strFileSource & ";Persist Security Info=False"

to
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &  strFileSource & ";Persist Security Info=False"

If the driver is not registered on your machine, it can be downloaded from the Microsoft website: https://www.microsoft.com/en-us/download/details.aspx?id=54920
Also, not it's not just the 4.0 changing to 12.0, 'Jet' changes to 'ACE' as well.


text:
Q: Using NSThread in this code piece I am working on someone else's code. I came across a line of code
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];

I have 2 questions to ask.

*

*Its just calling a method. Why is NSThread used here?

*While running the code, On some instances, this method doesn't get  called. When I put a breakpoint inside the method, it always get called. But if I remove the breakpoint, on some instances the method doesn't get called. Is this the problem of NSThread?

A: Using NSThread in this way means that the method "myMethod" is being called on a background thread, concurrently with the rest of the code. It is equivalent to this, which you may also have seen:
[self performSelectorInBackground:@selector(myMethod) withObject:nil];

If the method is not getting called (or seeming to not get called), it may be down to concurrency issues, i.e. the fact that the execution order of that method and ones you call after in on the main thread is not guaranteed, so you are expecting it to be called earlier than it actually is.
If you say:
[NSThread detachNewThreadSelector:@selector(methodA) toTarget:self withObject:nil];
[self methodB];

Then methodA and methodB will be running at the same time and there is no guarantee that methodA will finish before methodB.

A: I always use NSThread detachNewThreadSelector in combination with an auto-release pool, like so:
  -(void)myMethod {
      NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
      // .. Do stuff in this thread
      [pool release];
  };

If you want to "simply" perform a selector, do it like this:

  [self performSelector:@selector(myMethod)];


text:
Q: Problems with importing and equality Python Lets say we have two python files:
A:
class c(object):pass

def f(obj):
        if type(obj) == c:
                print("Object is of type c!")
        else:
                print("Object is not of type c.")
                print(f"Type c: {c}")
                print(f"Type of the object: {type(obj)}")

o = c()

B:
import A

o = A.c()

Now lets run A in shell or using the -i arguments in a command line, import B and call f using the object we created in B as an argument.
>>> import B
>>> f(B.o)
Object is not of type c.
Type c: <class '__main__.c'>
Type of the object: <class 'A.c'>

Can I some how fix this?
Just to clarify: I do want to execute a program like A and then import a program like B. I just want to know if I can somehow make f work in this context.

A: Ok, I think I've cracked it.
When you run
python -i A.py

this is the same as copying each line from A.py into an interactive python shell. This shell is it's own environment, you are not editing or 'extending' A.py. Incidentally the name of this environment is __main__.
In other words, python -i A.py creates a new class c different from A.c even though the two classes are identical in functionality. When you then import B, this imports from A.py, ie the 'old' class A.c.


text:
Q: How to set the pivot point for an object that is made by multiple objects in Unity? So I used a skin editor to create the bone structure for a psb file,

the character is in the centre of the canvas but when I tried to flip it by scale it changes position.

I guess the gray ball in the picture is the pivot point so I googled how to change the pivot but the tutorials are all for a single game object. And I don't know why the flip in the sprite render didn't change anything. Here is my setup

A: A gameObject's parent's position is it's pivot point. So if you want to change the pivot point of your sprite, select all the children (all the gameobjects nested under "player_side_shadow"), and change their positions. When you change the position of a child, you're changing it's relative or local position in relation to its parent: its pivot point (when you rotate the parent).

edit
As pointed out by derHugo: if the sprite(s) are already animated then you don't want to break existing frames. Instead you would apply the same process but add another parent (an empty gameobject) over everything, and rotate/flip that new parent.


text:
Q: Perl equivalent of PHP_AUTH_PW I am working with cross-domain AJAX in jquery, using a local forwarding script in the middle, and I need to pass Basic Authentication information through to the second domain.
In PHP, I know I have access to $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] variables which are simple plaintext, so my forwarding script can use this information with no difficulty.
For reasons beyond my control, though, I have to perform this task with Perl CGI.  I know there is $ENV{REMOTE_USER}, but I can not for the life of me figure out how to find the password.  I've tried $ENV{HTTP_AUTHORIZATION} but that always comes out blank.
How, in Perl, can I read the Basic Authentication password?  Or, at least, is there a way for my CGI to directly read the Authorization header so I can base64-decode and split the string myself?
Thanks!

A: Check out this article: http://www.besthostratings.com/articles/http-auth-php-cgi.html .
It uses ModReWrite to write the Http Authorization header to an environment variable. You can then access and decode this in your CGI script.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>


text:
Q: Using Python and Beautifulsoup how do I select the desired table in a div? I would like to be able to select the table containing the "Accounts Payable" text but I'm not getting anywhere with what I'm trying and I'm pretty much guessing using findall.  Can someone show me how I would do this?
For example this is what I start with:

Accounts Payable

222.82
92.54
100.34
99.95

Accrued Expenses

36.49
33.39
31.39
36.47

And this is what I would like to get as a result:

Accounts Payable

222.82
92.54
100.34
99.95

A: You can select the td elements with class lft lm and then examine the element.string to determine if you have the "Accounts Payable" td:
import sys
from BeautifulSoup import BeautifulSoup

# where so_soup.txt is your html
f = open ("so_soup.txt", "r")
data = f.readlines ()
f.close ()

soup = BeautifulSoup ("".join (data))

cells = soup.findAll('td', {"class" : "lft lm"})
for cell in cells:
    # You can compare cell.string against "Accounts Payable"
    print (cell.string)

If you would like to examine the following siblings for Accounts Payable for instance, you could use the following:
if (cell.string.strip () == "Accounts Payable"):
    sibling = cell.findNextSibling ()
    while (sibling):
        print ("\t" + sibling.string)
        sibling = sibling.findNextSibling ()

Update for Edit
If you would like to print out the original HTML, just for the siblings that follow the Accounts Payable element, this is the code for that:
lines = ["
"]
for cell in cells:
    lines.append (cell.prettify().decode('ascii'))
    if (cell.string.strip () == "Accounts Payable"):
        sibling = cell.findNextSibling ()
        while (sibling):
            lines.append (sibling.prettify().decode('ascii'))
            sibling = sibling.findNextSibling ()
lines.append ("
")

f = open ("so_soup_out.txt", "wt")
f.writelines (lines)
f.close ()


text:
Q: Lindo syntax error for division I have tried adding parenthesis to the code but lindo gives an error stating that its a variable. According to lindo documentation "(" should be accepted as a parenthesis but this does not occur. Removing the parenthesis causes the code to terminate as soon as it encounters the division symbol. Does anybody know what I'm missing in my code? (error occurs on the 4th, 5th and 6th line of code).
min     Y1 + Y2 + Y3 + Y4 + Y5 + Y6
ST
        Y1 + Y2 + Y3 + Y4 + Y5 + Y6 >= 1

5X11 + 10X12 + 2X13 + 5X14 + 4X15 + 4X16 / Y1 <= 10
5X21 + 10X22 + 2X23 + 5X24 + 4X25 + 4X26 / Y2 <= 10
5X31 + 10X32 + 2X33 + 5X34 + 4X35 + 4X36 / Y3 <= 10


text:
Q: How to make items draw at the same time in python using turtle? I have a homework assignment, and I have to make four different turtles move like they are planets around the sun. I have it all written, its just a matter of making the turtles draw at the same time. I was wondering if there was a relatively easy way to make them start around the same time (within reason)? Anyway, here's the code:
def planets():
    """simulates motion of Mercury, Venus, Earth, and Mars"""
    import turtle

    mercury = turtle.Turtle()
    venus = turtle.Turtle()
    earth = turtle.Turtle()
    mars = turtle.Turtle()
    mercury.shape('circle')
    venus.shape('circle')
    earth.shape('circle')
    mars.shape('circle')
    mercury.pu()
    venus.pu()
    earth.pu()
    mars.pu()
    mercury.sety(-58)
    venus.sety(-108)
    earth.sety(-150)
    mars.sety(-228)
    mercury.pd()
    venus.pd()
    earth.pd()
    mars.pd()
    mars.speed(7.5)
    venus.speed(3)
    earth.speed(2)
    mars.speed(1)
    mercury.circle(58)
    venus.circle(108)
    earth.circle(150)
    mars.circle(228)

Thanks in advance!

A: In general, if you want to do multiple things at the same time, there are two options:

*

*Preemptive multithreading, where you just create a thread for each thing and they all try to work at full speed and the computer figures out how to interleave that work.

*Cooperative scheduling: you do a small piece of work for one thing, then a small piece for the next, and so on, then come back to the first one.

In this case, it's the second one that you want. (Well, you might want the first, but you can't have it; tkinter, and therefore turtle, can only run on the main thread.) Draw, say, the first 1° of each circle, then the next 1° of each circle, and so on.
So, how do you do that? The circle method has an optional extent parameter, which is an angle (in degrees) to draw. So, you can do this:
for i in range(360):
    mercury.circle(58, 1)
    venus.circle(108, 1)
    earth.circle(150, 1)
    mars.circle(228, 1)

Of course the smaller you make that extent value, the more "steps" each turtle is taking, so the slower they will take to orbit.
Also, I'm not sure you really want to use speed the way you're using it. That causes each move to animate more slowly. It doesn't affect how quickly they orbit around the sun, it just affects how long each step takes to draw. So I think what you really want to do here is leave all the speeds at 0 (no animation delay), but move the faster planets by a larger extent each step:
mercury.speed(0)
venus.speed(0)
earth.speed(0)
mars.speed(0)
for i in range(360):
    mercury.circle(58, 7.5)
    venus.circle(108, 3)
    earth.circle(150, 2)
    mars.circle(228, 1)

Of course this means Mercury will end up orbiting the sun 7.5 times, while Mars will only orbit once… but that's exactly what you want, right?

A: In my other answer, I said that you have to do some kind of cooperative scheduling, because tkinter isn't thread-safe. But that isn't quite true. tkinter is thread-safe, it just doesn't have any kind of dispatching mechanism to post events on the main loop from a background thread, so you have to add a queue or some other way to do it.
I'd definitely not recommend using threads here, but it's worth seeing how it would work.
Allen B. Taylor's clever mtTkinter library wraps all of the magic up for you. It doesn't work with Python 3, but I've ported it, and you can get it as mttkinter on GitHub. The module have any installer; you'll have to copy it into the same directory as planets.py. But then you can do this:
import threading
import turtle
import mttkinter

def planets():
    """simulates motion of Mercury, Venus, Earth, and Mars"""
    # Use your existing code, up to...
    mars.speed(1)

    # Now create a thread for each planet and start them
    mercury_thread = threading.Thread(target=lambda: mercury.circle(58))
    venus_thread = threading.Thread(target=lambda: venus.circle(108))
    earth_thread = threading.Thread(target=lambda: earth.circle(150))
    mars_thread = threading.Thread(target=lambda: mars.circle(228))
    mercury_thread.start()
    venus_thread.start()
    earth_thread.start()
    mars_thread.start()

    # Unfortunately, if we just exit the function here, the main thread
    # will try to exit, which means it'll wait on all the background threads.
    # But since they're all posting events and waiting on the main thread to
    # reply, they'll deadlock. So, we need to do something tkinter-related
    # here, like:
    turtle.Screen().exitonclick()

planets()

A: Since none of the previous answers mention turtle's own ontimer() for running the simulation, I decided to do an implementation that uses it and makes the whole problem more data-oriented:
from turtle import Turtle, Screen

""" Simulate motion of Mercury, Venus, Earth, and Mars """

planets = {
    'mercury': {'diameter': 0.383, 'orbit': 58, 'speed': 7.5, 'color': 'gray'},
    'venus': {'diameter': 0.949, 'orbit': 108, 'speed': 3, 'color': 'yellow'},
    'earth': {'diameter': 1.0, 'orbit': 150, 'speed': 2, 'color': 'blue'},
    'mars': {'diameter': 0.532, 'orbit': 228, 'speed': 1, 'color': 'red'},
}

def setup_planets(planets):
    for planet in planets:
        dictionary = planets[planet]
        turtle = Turtle(shape='circle')

        turtle.speed("fastest")  # speed controlled elsewhere, disable here
        turtle.shapesize(dictionary['diameter'])
        turtle.color(dictionary['color'])
        turtle.pu()
        turtle.sety(-dictionary['orbit'])
        turtle.pd()

        dictionary['turtle'] = turtle

    screen.ontimer(revolve, 50)

def revolve():
    for planet in planets:
        dictionary = planets[planet]
        dictionary['turtle'].circle(dictionary['orbit'], dictionary['speed'])

    screen.ontimer(revolve, 50)

screen = Screen()

setup_planets(planets)

screen.exitonclick()

OUTPUT SNAPSHOT IN TIME

A: turtle.py ends with two test demos. The second one ends with one turtle 'tri' chasing another 'turtle'. It does what abarnet suggests in the first post -- increments within a loop.
while tri.distance(turtle) > 4:
    turtle.fd(3.5)
    turtle.lt(0.6)
    tri.setheading(tri.towards(turtle))
    tri.fd(4)

The turtledemo package has multiple examples to learn from. python -m turtledemo is the easy way to start the viewer.  There are a couple of bugs that have been fixed for future releases.

A: Methods posted by other users work well. However, I did a similar model of a solar system with object oriented design and what I did was create a class called System where I create a system with a desired height and width and created a stepAll function which has a list of agents and advances all agents in that list one 'step':
class System:
"""A two-dimensional world class."""

    def __init__(self, width, height):
        """Construct a new flat world with the given dimensions."""

        self._width = width
        self._height = height
        self._agents = { }
        self.message = None

    def getWidth(self):
        """Return the width of self."""

        return self._width

    def getHeight(self):
        """Return the height of self."""

        return self._height

    def stepAll(self):
        """All agents advance one step in the simulation."""

        agents = list(self._agents.values())
        for agent in agents:
            agent.step()

Then, I created a Planet class, and made the planets agents, and defined what their step would be in a Step function.
class Planet:
"""A planet object"""

    def __init__(self, mySystem, distance, size, color, velocity, real_size, real_mass, name):
        self = self
        self._system = mySystem
        mySystem._agents[self] = self #make planet an agent
        self._velocity = velocity
        self._color = color
        self._distance = distance
        self._size = size
        self._position = [distance, distance - distance]
        self._angle = 90
        self._real_size = real_size
        self._real_mass = real_mass
        self._name = name

        #MAKE PLANET
        self._turtle = turtle.Turtle(shape = 'circle')
        self._turtle.hideturtle()

        #INITIALIZE PLANET
        self._turtle.speed('fastest')
        self._turtle.fillcolor(color)
        self._turtle.penup()
        self._turtle.goto(self._position)
        self._turtle.turtlesize(size,size,size)
        self._turtle.showturtle()

    def getmySystem(self):
        """Returns the system the planet is in"""
        return self._mySystem

    def getdistance(self):
        """Returns the distance the planet is from the sun"""
        return self._distance

    def getposition(self):
        """Returns the position of the planet"""
        return self._position

    def getvelocity(self):
        """Returns the velocity of the planet"""
        return self._velocity

    def step(self):
        """Moves the planet one step on its orbit according to its velocity and previous position"""
        xvar = self._position[0]
        yvar = self._position[1]

        newx = int(self._distance*math.cos(math.radians(90-self._angle)))
        newy = int(self._distance*math.sin(math.radians(90-self._angle)))

        self._turtle.goto(newx, newy)

        self._angle = self._angle - self._velocity

Then in my main() function I initialized all the planets with their respective values and said:
while True:
    space.stepAll()

This accomplishes your goal and also makes it easier to add another planet later with the specific parameters you want it to contain by just calling the Planet Class, instead of drawing a completely new planet and trying to individually move it along with the others.
Hope this helps someone!


text:
Q: Iframe fullscreen problem on android devices I have created a cordova hybrid app and in it, I want to display a yt video using iframe, so I have something like this in my code:
<iframe src="https://www.youtube.com/embed/tgbNymZ7vqY"
        frameborder="0"
        allow="encrypted-media; fullscreen"
        allowfullscreen="allowfullscreen">
</iframe>

This works in diplaying the video in fullscreen on browsers and on iOS but for some reason on android devices it throws this error in the console:
Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.
Does anyone have any idea to what could be the cause, and potential solution to this problem?


text:
Q: How can I avoid read errors when two python scripts access a single pickle file? I need to pass data between two Python scripts that are initiated from two different sources. I have seen my logger with a read errors. Is there a better way?
Program A: Regularly writes to a pickle file about every minute.
def cacheData(filepath, data):
    #create a cPickle file to cache the current data
    try:
        outFile = open(filepath,'wb')
        #cPickle the current data to a file
        cPickle.dump(data, outFile)
        outFile.close()
    except Exception, e:
        logger.warn("Error creating cache file")

Program B: Is a compiled executable initiated by the user. It reads the pickle file to initiate some code.
def readCachedObj(filepath):
    #read cPickle file and return data as object
    try:
        inFile = open(filepath,'rb')
        cache = cPickle.load(inFile)
        inFile.close()
        return cache
    except Exception, e:
        logger.warn("Error reading cached data cPickle")

UPDATE 1
def replace(src, dst):
    win32api.MoveFileEx(src, dst, win32con.MOVEFILE_REPLACE_EXISTING)

def cacheData(filepath, data):
    #create a cPickle file to cache the current data
    try:
        tmpfile = str(uuid.uuid4()) + '.tmp'
        outFile = open(tmpfile,'wb')
        #cPickle the current data to a temp file
        cPickle.dump(data, outFile)
        outFile.close()
        #replace the pickle file with the new temp file
        replace(tmpfile, filepath)
        #remove any extraneous temp files
        for f in glob.glob("*.tmp"):
            os.remove(f)
    except Exception, e:
        logger.warn("Error creating cache file")

def readCachedObj(filepath):
    #read cPickle file and return data as object
    try:
        inFile = open(filepath,'rb')
        cache = cPickle.load(inFile)
        inFile.close()
        return cache
    except Exception, e:
        logger.warn("Error reading cached data cPickle")

A: Never overwrite an existing file. Instead, write to a new file, and then perform an (atomic) rename after you successfully close it.

A: This seems to do it for me. By creating the new temp file and then using file overwrite, the cacheData function is alot snappier when dealing with the final pickle file.
def replace(src, dst):
    win32api.MoveFileEx(src, dst, win32con.MOVEFILE_REPLACE_EXISTING)

def cacheData(filepath, data):
    #create a cPickle file to cache the current data
    try:
        tmpfile = str(uuid.uuid4()) + '.tmp'
        outFile = open(tmpfile,'wb')
        #cPickle the current data to a temp file
        cPickle.dump(data, outFile)
        outFile.close()
        #replace the pickle file with the new temp file
        replace(tmpfile, filepath)
        #remove any extraneous temp files
        for f in glob.glob("*.tmp"):
            os.remove(f)
    except Exception, e:
        logger.warn("Error creating cache file")

def readCachedObj(filepath):
    #read cPickle file and return data as object
    try:
        inFile = open(filepath,'rb')
        cache = cPickle.load(inFile)
        inFile.close()
        return cache
    except Exception, e:
        logger.warn("Error reading cached data cPickle")


text:
Q: Sharepoint CPU usage Is is standard that CPU usage to spike from about 20% to 100% when retrieving a list (just navigating the view in Sharepoint)? List has about 1500 items but it is set to display 30 items at a time. The spike is just for 2 seconds. It goes back to 20% immediately. But if several users are accessing the site, then it ends up at a continuous 100% usage.
Thanks.


text:
Q: problem add library recyclerView in android studio i have problem to add library at android studio . i need help to fix this problem . Thankful
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //noinspection GradleCompatible
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

Error building project:
ERROR: Failed to resolve: recyclerview
Affected Modules: app

A: You don't need to add recycleview lib in gradle for androidx . just add this below lib. this package contains  recycleView inside it.
implementation 'com.google.android.material:material:1.0.0'

A: Change recyclerview library with :
    implementation 'androidx.recyclerview:recyclerview:1.0.0'

A: You're using all the dependencies from AndroidX. That means your project is in AndroidX. But the RecyclerView dependency you're trying to add is from support library that won't work with AndroidX.
Use this AndroidX dependecy instead:
implementation 'androidx.recyclerview:recyclerview:1.0.0'


text:
Q: Signature verification failed when installing MySQL 5.7.29 on Suse Linux Leap 15.1 I want to install MySQL community edition 5.7.29 on OpenSuse Linux leap 15.1 as following:

*

*Download the file: mysql-5.7.29-1.sles12.x86_64.rpm-bundle.tar;

*untar the file then get 8 files
>mysql-community-client-5.7.29-1.sles12.x86_64.rpm

>mysql-community-common-5.7.29-1.sles12.x86_64.rpm

>mysql-community-devel-5.7.29-1.sles12.x86_64.rpm

>mysql-community-embedded-5.7.29-1.sles12.x86_64.rpm

>mysql-community-embedded-devel-5.7.29-1.sles12.x86_64.rpm

>mysql-community-libs-5.7.29-1.sles12.x86_64.rpm

>mysql-community-server-5.7.29-1.sles12.x86_64.rpm

>mysql-community-test-5.7.29-1.sles12.x86_64.rpm

*install the 4 files rpm using the command:
>sudo zypper install mysql-community-{server,client,common,libs}-*

*Then the error message shows as below:
>mysql-community-common-5.7.29-1.sles12.x86_64.rpm:
Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY

>Looking for gpg key ID 5072E1F5 in cache /var/cache/zypp/pubkeys.
Repository Plain RPM files cache does not define additional
'gpgkey=' URLs.
mysql-community-common-5.7.29-1.sles12.x86_64 (Plain RPM files
cache): Signature verification failed [4-Signatures public key is
not available]

>Abort, retry, ignore? [a/r/i] (a):

Any response will be appreciated.

A: Just write i to bypass this issue and successfully complete installation.

A: The issue because by default OpenSUSE use downloads.opensuse.org repository that seems to use proxy to nearest server mirror, but the problem is that it seems some mirrors does not update something on his servers so you found messages like "Signature verification failed".
You can try several solutions:

*

*Use some VPN service to change your IP location to find a chance that download.opensuse.org will redirect you on some good mirror.

*Change "download.opensuse.org" domain in the repo configuration in the /etc/repo.d (or /etc/zypp/repo.d) to some other server from the list: https://mirrors.opensuse.org/list/15.0.html and put it into the repository files (/etc/repo.d/* or /etc/zypp/*), e.g. http://nrt.edge.kernel.org/opensuse (instead of http://download.opensuse.org).
Also you can change source server even in the OpenSUSE installation mode while use graphical install. For that you should cancel graphical install and when text mode menu opened, in the "Expert mode" you can edit configuration from the console. In the console you can't use "vi" so use "sed" command to change the file contents.
Scan configs:
grep "downloads.opensuse.org" -r /etc

Change content for every file:
sed -i s/downloads.opensuse.org/nrt.edge.kernel.org\/opensuse/g /etc/products.d/openSUSE.prod
...


text:
Q: Cache a set of strings with LRU eviction policy in Java I am trying to create a cache for a set of Strings with LRU eviction policy in this way.
private static final Boolean PLACEHOLDER = true;
LoadingCache<String, Boolean> scannedIDsCache = CacheBuilder.newBuilder()
        .build(new CacheLoader<String, Boolean>() {
            @Override
            public Boolean load(String key) throws Exception {
                return PLACEHOLDER;
            }
        });

I think I am saving space using only one object as the value for all the elements, am I correct? Do you know any other space efficient way of doing this? Thanks.

A: No, you are not saving space.
When a JVM* autoboxes a boolean it calls Boolean.valueOf(boolean) which returns either Boolean.TRUE or Boolean.FALSE which are static final Boolean fields. It does not create a new Boolean instance. As such, the PLACEHOLDER you've defined is in fact a reference to Boolean.TRUE and is redundant.
Furthermore, I would not use Guava's Cache for an LRU unless I am willing to accept the fact that "the cache may evict an entry because it hasn't been used recently or very often" (CacheBuilder.maximumSize(long), emphasis added).
If you want a straight-up LRU you can use Collections.newSetFromMap(Map) with LinkedHashMap:
Set<String> cache = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>() {
    @Override
    protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
        return size() > MAX_ENTRIES;
    }
});

Where you define MAX_ENTRIES.

*Note: Theoretically there could be some JVM implementation(s) out there that don't call Boolean.valueOf(boolean) (or something similar) at runtime when autoboxing boolean primitives but if such an implementation exists I am fairly confident you are not using it and that very few if any individuals are. From Boolean(boolean):

Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance.


text:
Q: Symfony forms: Save form containing checkboxes and/or choice widgets? I have a Doctrine table that contains the following fields:
Article:
  columns:
    title:
      type: string(40)
    content:
      type: string(255)
    publish:
      type: boolean

I am creating a custom form for creating Articles on my site. In my custom form I have a checkbox for the publish field. When submitting the form, if the checkbox is checked, the form value for it comes back as "on". If the checkbox is NOT checked, the form value is non-existent.
Because I'm working with a form that extends Doctrine's Model Forms, I'd like to be able to simply do a $this->form->save(); when it passes validity.
But if the checkbox for publish only gives the value of on or nothing, then neither value is valid for the database. The form saves properly but the database value for publish is always just default no matter if the checkbox is checked or not.
What is the correct approach to this problem?
Also, how do you deal with choice sfWidgets? The passed values is an array of values. $this->form-save() seems to ignore those arrays.
Do you manually have to get the values from the form and create a Doctrine Collection from the values and save it that way? Or is there a better method that Symfony expects you to use?

A: Is your validator for publish an instance of sfValidatorBoolean? If it is, it should return false.
Your question about choice widgets requires more elaboration. Please paste your form's configure method, the values you are receiving from $form->getValues(), and what you expect to be receiving.


text:
Q: @Controller causing java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest Why do I get java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest when I add @Controller to DummyController class?
it.cspnet.firstspringmvc.controller.Main
   public static void main(String args[]) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("jpaContext.xml");
        Servizi servizi = ctx.getBean(Servizi.class);
        Utente utente = new Utente();
        utente.setUserName("test");
        utente.setPassword("test");
        Utente utenteInDb = servizi.login(utente);

        for (Ordine ordine : utenteInDb.getOrdini()) {
            System.out.println("ordine: " + ordine);
        }
    }

it.cspnet.firstspringmvc.controller.DummyController
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;

@Controller
public class DummyController {

    @RequestMapping(value = "/dummy", method = {RequestMethod.GET})
    public String get(Model model, HttpServletRequest request) {
        return "dummy";
    }
}

When I remove the @Controller annotation from DummyController then main prints out the example's fine but if I put it back in then it throws:

Exception in thread "main" java.lang.NoClassDefFoundError:
  javax/servlet/http/HttpServletRequest     at
  java.lang.Class.getDeclaredMethods0(Native Method)

I'm using this project:
https://github.com/ivansaracino/spring-mvc-jparepository-example.git
All I've done is add Main and DummyController

A: You are probably missing right dependencies, like:
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>provided</scope>
        <version>3.1.0</version>
    </dependency>

Please note that your version could be 2.5, 3.0 or 3.1 - it depends on application server you are using. Also when you want to create executable war you should probably not use provided scope (depending on your servlet container).

A: Your dependency scope is 'provided', so when you build the war this dependency won't be added to the class path! Make sure the dependency exists on App Server lib path.

A:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <!--<scope>provided</scope>-->
    <version>3.1.0</version>
</dependency>


text:
Q: ESP8266 cannot read flash after programming I have written the flash on an ESP-12E, using a custom build with the base modules + OneWire and mDNS.
The build is from a website i've used before and the build have always worked.
The flash write was apparently successful, yet after the write the ESP started to send garbage data and it hasn't stopped yet.
The ESP8266 download tool from Espressif fails to program the flash, and so does esptool.
The fun part is: I can actually read the MAC for both the AP and the STATION.
GPIO0/2 changes have no effect whatsoever, garbage data still comes in.
Tried to read the data with ESPlorer, PuTTY (Serial) and Teraterm and the problem is the same.
Also tried all standard Baudrates from 9600 to 230400...
And now i'm completely out of ideas.
Here's an image about the error on the Espressif downloader:

A: You need to familiarize yourself with the upgrading section in the NodeMCU docs. More specifically you need to flash the esp_init_data_default.bin of the Espressif SDK your firmware builds upon to the correct memory address.
I don't know how to do that with the NodeMCU Flasher (project seems to have stalled btw) but with esptool.py the command is as follows:
esptool.py --port <serial-port-of-ESP8266> write_flash -fm dio -fs 32m 0x00000 <nodemcu-firmware>.bin 0x3fc000 esp_init_data_default.bin


text:
Q: how to find $\lim_{\large x \to \frac{\pi}{3}}\frac{\tan^{3}\left(x\right)-3\tan\left(x\right)}{\cos\left(x+\frac{\pi}{6}\right)}$ how to find

$$\lim_{\large x \to \frac{\pi}{3}}\frac{\tan^{3}\left(x\right)-3\tan\left(x\right)}{\cos\left(x+\frac{\pi}{6}\right)}$$ without L'hopital or taylor/Laurent series

I tried but did not get any answer:
$$\frac{\tan^{2}\left(x\right)\tan\left(x\right)-3\tan\left(x\right)}{\cos\left(x+\frac{\pi}{6}\right)}=\frac{2\left(\sin^{3}\left(x\right)-3\sin\left(x\right)\cos^{2}\left(x\right)\right)}{\cos^{3}\left(x\right)\left(\sqrt{3}\cos\left(x\right)-\sin\left(x\right)\right)}=\frac{2\left(\sin^{3}\left(x\right)-3\left(\sin\left(x\right)\left(1-\sin^{2}\left(x\right)\right)\right)\right)}{\cos^{3}\left(x\right)\left(\sqrt{3}\cos\left(x\right)-\sin\left(x\right)\right)}=\frac{2}{1}\frac{-3\left(\sin(x)-\sin^{2}\left(x\right)\right)+\sin^{3}\left(x\right)}{\left(1-\sin^{2}\left(x\right)\right)(\cos(x))\left(\sqrt{3}\cos\left(x\right)-\sin\left(x\right)\right)}$$

A: $$\lim_{\large x \to \frac{\pi}{3}}\frac{\tan^{3}\left(x\right)-3\tan\left(x\right)}{\cos\left(x+\frac{\pi}{6}\right)}=$$
$$\lim_{\large x \to \frac{\pi}{3}}\frac{\tan x (\tan x - \sqrt 3)(\tan x +\sqrt 3)}{\cos x \cos (\pi /6)-\sin x \sin (\pi /6)}=$$
$$\lim_{\large x \to \frac{\pi}{3}}\frac{(2\sec x)\tan x (\tan x - \sqrt 3)(\tan x +\sqrt 3)}{\sqrt 3 - \tan x}=-24$$

A: $$\begin{aligned}\frac{\tan^3 x-3\tan x}{\cos\left(x+\frac{\pi}{6}\right)}
&=\tan(x)\cdot\frac{\tan^2 x-3}{\cos x\cos\left(\frac{\pi}{6}\right)-\sin x\sin\left(\frac {\pi}{6}\right)},\quad\quad x\neq \frac{\pi}{3}
\\
&=\frac{2\sin x}{\cos^{3} x}\cdot\frac{\sin x^{2}-3\cos x^{2}}{\sqrt{3}\cos x-\sin x}\quad\quad\text{(1)}
\\
&=\frac{2\sin x}{\cos^{3} x}\cdot\frac{\left(\sin x^{2}-3\cos x^{2}\right)\left(\sqrt{3}\cos x+\sin x\right)}{\left(\sqrt{3}\cos x-\sin x\right)\left(\sqrt{3}\cos x+\sin x\right)}
\\
&=-\frac{2\sin x}{\cos^{3} x}\cdot\frac{4\cos^{2} x-1}{4\cos^{2} x-1}\cdot\left(\sqrt{3}\cos x+\sin x\right)\quad\quad\text{(2)}
\end{aligned}$$
Equation $(1)$ uses $\tan x=\frac{\sin x}{\cos x}$ and $(2)$ uses $\sin^2 x=1-\cos^2 x$. Hence, by substitution, the limit is $-24$.

A: Let $y=x-\pi/3$, so we are to compute
\begin{align*}
\lim_{y\rightarrow 0}\dfrac{\tan^{3}(y+\pi/3)-3\tan(y+\pi/3)}{\cos(y+\pi/2)}.
\end{align*}
Note that
\begin{align*}
\tan^{3}(y+\pi/3)-3\tan(y+\pi/3)&=\tan(3(y+\pi/3))(3\tan^{2}(y+\pi/3)-1)\\
&=(\tan(3y))(3\tan^{2}(y+\pi/3)-1),
\end{align*}
and the term reduces to
\begin{align*}
\dfrac{(\tan(3y))(3\tan^{2}(y+\pi/3)-1)}{-\sin y}.
\end{align*}
But
\begin{align*}
\lim_{y\rightarrow 0}\dfrac{\tan 3y}{\sin y}=3\lim_{y\rightarrow 0}\dfrac{\sin 3y}{3y}\dfrac{1}{\cos 3y}\dfrac{y}{\sin y}=3.
\end{align*}


text:
Q: how to add cookies to tornado httpclient Here is my code
class MainHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_client.fetch("http://www.example.com",
                          callback=self.on_fetch)

    def on_fetch(self, response):
        self.write('hello')
        self.finish()

I want to use asynchronous HTTP client. When I fetch the request, I want to send it with the cookies.
The Document has nothing about httpclient cookies. http://tornado.readthedocs.org/en/latest/httpclient.html

A: You can put the cookie in the headers keyword argument that fetch takes.
client:
import tornado.httpclient

http_client = tornado.httpclient.HTTPClient()
cookie = {"Cookie" : 'my_cookie=heyhey'}
http_client.fetch("http://localhost:8888/cook",
                  headers=cookie)

server:
from tornado.ioloop import IOLoop
import tornado.web

class CookHandler(tornado.web.RequestHandler):
    def get(self):
        cookie = self.get_cookie("my_cookie")
        print "got cookie %s" % (cookie,)

if __name__ == "__main__":
    app = tornado.web.Application([
        (r"/cook", CookHandler),
    ])

    app.listen(8888)
    IOLoop.instance().start()

If you run the server, followed by the client, the server will output this:
got cookie heyhey

A: https://pypi.python.org/pypi/tornado-httpclient-session
Is a library just for that:
from tornado.httpclient import HTTPClient

from httpclient_session import Session

s = Session(HTTPClient) # AsyncHTTPClient default

r = s.fetch('https://github.com')
print(r.headers['set-cookie']) # Inspect cookies returnd from Github

r = s.fetch('https://github.com') # Fetching carrys cookies
print(r.request.headers['cookie']) # Inspect cookies attached