text:
Q: "java.lang.SecurityException: Attempt to remove non-test admin" while trying to remove device admin i can't remove device owner from my Android 12.1 device.
When i use dpm list-owners while in adb shell, i get this output: 1 owner:\n User  0: admin=package.name/app.receivers.DeviceAdminReceiver,DeviceOwner,Affiliated
and when i use dpm remove-active-admin package.name/app.receivers.DeviceAdminReceiver in adb shell, i get this output:
Exception occurred while executing 'remove-active-admin':
java.lang.SecurityException: Attempt to remove non-test admin ComponentInfo{package.name/app.receivers.DeviceAdminReceiver} 0
        at com.android.server.devicepolicy.DevicePolicyManagerService.lambda$forceRemoveActiveAdmin$9$DevicePolicyManagerService(DevicePolicyManagerService.java:3712)
        at com.android.server.devicepolicy.DevicePolicyManagerService$$ExternalSyntheticLambda20.runOrThrow(Unknown Source:6)
        at android.os.Binder.withCleanCallingIdentity(Binder.java:390)
        at com.android.server.devicepolicy.DevicePolicyManagerService$Injector.binderWithCleanCallingIdentity(DevicePolicyManagerService.java:1554)
        at com.android.server.devicepolicy.DevicePolicyManagerService.forceRemoveActiveAdmin(DevicePolicyManagerService.java:3708)
        at com.android.server.devicepolicy.DevicePolicyManagerServiceShellCommand.runRemoveActiveAdmin(DevicePolicyManagerServiceShellCommand.java:280)
        at com.android.server.devicepolicy.DevicePolicyManagerServiceShellCommand.onCommand(DevicePolicyManagerServiceShellCommand.java:93)
        at com.android.modules.utils.BasicShellCommandHandler.exec(BasicShellCommandHandler.java:97)
        at android.os.ShellCommand.exec(ShellCommand.java:38)
        at com.android.server.devicepolicy.DevicePolicyManagerService.onShellCommand(DevicePolicyManagerService.java:9818)
        at android.os.Binder.shellCommand(Binder.java:950)
        at android.os.Binder.onTransact(Binder.java:834)
        at android.app.admin.IDevicePolicyManager$Stub.onTransact(IDevicePolicyManager.java:6980)
        at android.os.Binder.execTransactInternal(Binder.java:1184)
        at android.os.Binder.execTransact(Binder.java:1143)

I also tried disabling device management apps from security in settings, but disabling text is also greyed out.
What should i do?


text:
Q: How to get the size (Kb or Mb ) of Bitmap in android java I have a Bitmap and I want to get the size of the bitmap in KB, MB or etc
TRID NUMBER 1 - so I tried this but it is returning the wrong output because I have an image whose size is 42.57 KB
but in the result, it is returning 128 B
    // originalBitmap is global var

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    originalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] imageInByte = stream.toByteArray();
    long bitmap_size = imageInByte.length / 1024;
    Log.d(TAG, "size of bitmap - "+Formatter.formatShortFileSize(this,bitmap_size));

TRID NUMBER 2 - so In this tried is simply done this thing but it is also showing wrong output it showing 1.2 MB of that same image whose size is 42.57 KB
Log.d(TAG, "Image size : "+Formatter.formatShortFileSize(this, originalBitmap.getByteCount()));

NOTE: I have no real device so tested this in the emulator. may this cause or what do you think
any help will be appreciated! thank you.

A: Don't divide by 1024
long bitmap_size = imageInByte.length / 1024;

If you are using Formatter.formatShortFileSize then just use the original length of the byte array.
This code is compressing the image with this:
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

How do you know the size of the image after this compression?  You might write the compressed image out to a file, however the imageInByte.length has to be the number of bytes in the byte array.  Are you sure it is NOT this size?

A: You said "I have an image whose size is 42.57 KB" and I suppose it isn't a real Bitmap but some JPEG, PNG, WEBP or other image format.
If you import this image in Java using BitmapFactory the decoder "expands" compressed image bytes in a real Bitmap made by Width x Height x 3 (or "4" if apha is supported from original image format). So a simple 1Kb image of 100x100 PNG file could became 100x100*3 = 30000 = 30Kb in Java when "Bitmap.getByteCount()" is executed.
Compressing (again) this 30Kb Bitmap in a different or similar format could generate a different output so a different final length.
Maybe you need some explanation:

*

*a Bitmap, in Java, is just an array of bytes. A Bitmap, as a file, is made by an Header and same array of bytes.

*if you Compress a Java Bitmap into a JPEG Stream you will get the final JPEG with exactly same content you need to write in a file (aka: this output could not be directly displayed in Java)

So you're Compressing a Bitmap to get a compressed JPEG and then you're getting JPEG length (header included). Obliviously a compressed file is normally smaller than original one.

*

*If you don't want JPEG length but Bitmap length you were near right by doing "Formatter.formatShortFileSize(this, BITMAP.getByteCount())".

*If you want JPEG length (the one after Compression) then don't divide by 1024 because Formatter needs Bytes and not Kilobytes.

Comparing a Compressed or not-Compressed Java output with original Image File is 99% of times "wrong" because re-compressing a decompressed image file usually results in a different result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can I calculate $a_{n+3}=a_n+a_{n+1}+a_{n+2}$? recently I need to calculate this: $a(n+1)=((a(n-2)+a(n-1)+a(n)) \bmod 10000)$
and get $a(20000000)$ (for example).
I know RecurrenceTable,but
RecurrenceTable[{a[n + 1] == Mod[a[n] + a[n - 1] + a[n - 2], 10000],
a[1] == 1, a[2] == 1, a[3] == 1}, a, {n, 1, 20000000}] // Last

require a bit of long time.(and extra space)
using RSolve is also useless.
Nest seems only support $a_{n+1}=f(a_n)$
this is also not so useful.
a[1] == 1;
a[2] == 1;
a[3] == 1;
a[n_] := a[n] = Mod[a[n - 3] + a[n - 1] + a[n - 2], 100000];
a[20000000]

So is there a way which can Space Complexity be $O(1)$ as well as fast? (I know matrix exponentiating by squaring,but it seems hard to write.)

A: Nest[] is in fact usable here, if you are ingenious enough and willing to wait a little:
Last[Nest[Append[Rest[#], Mod[{1, 1, 1}.#, 100000]] &, {1, 1, 1}, 20000000 - 3]]
   16287

An alternative is to use an undocumented function for modular matrix exponentiation:
Mod[First[Algebra`MatrixPowerMod[{{1, 1, 1}, {1, 0, 0}, {0, 1, 0}},
                                 20000000 - 3, 100000].{1, 1, 1}], 100000]
   16287

A: You need to use Set rather than Equal for the initial conditions.
Clear[a, n]

a[1] = 1;
a[2] = 1;
a[3] = 1;
a[n_] := a[n] = Mod[a[n - 3] + a[n - 1] + a[n - 2], 100000];
Last[a /@ Range[4, 20000000]] // AbsoluteTiming

(* {107.222, 16287} *)

A: Similar approach to JM...
mat = {{1, 1, 1},
       {1, 0, 0},
       {0, 1, 0}};

init = {1,1,1};

next[vec_] := Mod[mat.vec, 100000];

First@Nest[next, {1, 1, 1}, 20000000-3] // Timing

(*  {42.0625, 16287}  *)

Inspired by JM's second approach, but using what is documented...still pretty fast. I thought it might overflow, but no problem.
First@Mod[Mod[MatrixPower[mat, 20000000 - 3], 100000].{1, 1, 1}, 100000] // Timing

(* {0.03125, 16287} *)


text:
Q: where is the MIB real value in snmp Objects in the MIB are defined using a subset of A ASN.1. following as
nsMemory                    OBJECT IDENTIFIER ::= {netSnmpObjects 31}
nsSwap                      OBJECT IDENTIFIER ::= {netSnmpObjects 32}
nsCPU                       OBJECT IDENTIFIER ::= {netSnmpObjects 33}
nsLoad                      OBJECT IDENTIFIER ::= {netSnmpObjects 34}
nsDiskIO                    OBJECT IDENTIFIER ::= {netSnmpObjects 35}

then, there is only format of OBJECT. where is the real value such as "2048"??
will snmpd process and calculate them immediately?

A: MIBs do not contain values. They only define names and types of values that SNMP agent (a hardware device or an application) reports back to SNMP manager.
In your snippet you referred to OBJECT IDENTIFIER that serves as a "name" for a value-less node in OID tree. Typically, one or more OBJECT TYPE clauses are logically linked beneath OBJECT IDENTIFIER where OBJECT TYPE define both "name" and "value type" for SNMP data coming from SNMP agent.
In the following example sysUpTime is linked under the value-less system (1.3.6.1.2.1.1) node in the OID tree. Here sysUpTime serves as a name (corresponding to the 1.3.6.1.2.1.1.3 node) for addressing values of type TimeTicks:
system   OBJECT IDENTIFIER ::= { mib-2 1 }

sysUpTime OBJECT-TYPE
    SYNTAX      TimeTicks
    MAX-ACCESS  read-only
    STATUS      current
    DESCRIPTION
            "The time (in hundredths of a second) since
            the network management portion of the system
            was last re-initialized."
    ::= { system 3 }

MIBs are mostly useful for humans (operating SNMP managers) to read, interpret and navigate SNMP data provided by SNMP agent. It is entirely possible to operate SNMP without any MIB files. At the protocol level only OIDs are used for referring to values.
You may find this explanation relevant to your question.


text:
Q: Cómo puedo graficar un conjunto de tendencias en R? Buen día, estoy tratando de graficar varias graficas por cada año en R, algo asi:

Quisiera en vez de esto, hacerlo con las tendencias, es decir, que cada grafico, sea una tendencia de ese año, esta tendencia es del año 2000

Para el primer grafico use un barplot con una tabla en excel y para la segunda grafica use un ggplot. Agradeceria una ayuda para este fin, muchas gracias


text:
Q: Limit of the decimal part of $\sqrt{4n^2+38n}$
Let $x_n=4n^2+38n$. Find the limit of the decimal part of $\sqrt{x_n}$ as $n$ goes to infinity.

I have tried completing the square for $x_n$, which yields $\sqrt{x_n}<2n+\frac{19}{2}$, but that's all I got. The decimal part really makes the problem harder.

A: Using binomial expansion for square root,
$\sqrt{4n^2+38n}=2n\sqrt{1+\dfrac{19}{2n}}=2n\left(1+\dfrac{19}{4n}+O\left(\dfrac1{n^2}\right)\right)\to2n+\dfrac{19}2=2n+9+\dfrac12$,
so the decimal part goes to $\dfrac12$.

A: We have $$\lim_{n\to\infty}\sqrt{4n^2+38n+\frac{361}4}-\sqrt{4n^2+38n}=\lim_{n\to\infty}\frac{\frac{361}4}{\sqrt{4n^2+38n+\frac{361}4}+\sqrt{4n^2+38n}}=0.$$ We also have $$\left\{\sqrt{4n^2+38n+\frac{361}4}\right\}=\left\{2n+\frac{19}2\right\}=\frac12,$$ where $\{\cdot\}$ denotes the fractional part. Can you take it from here?


text:
Q: Is there any way to hide the Airdrop option in the UIDocumentInteractionController sheet I am using the UIDocumentInteractionController for sharing the files between apps. It works fine. But whenever I am opening the sheet , that sheet contains myapp + airdrop option.
Is there any way to hide the Airdrop option in the UIDocumentInteractionController sheet ?
THanks.

A: Not in a way that is Apple Approved. Anything that hides/removes that button is going to be using private APIs or manipulating private views, both activities that will get your app rejected.


text:
Q: How to set current date to jDateChooser from pc? I have a situation that I need to fill the jDateChooser box by the current date automatically (without clicking the pop up calender).
How can I do that?
Thanks in advance.

A: Date date = new Date();
dateChooser.setDate(date);

A: Here, the Date class belongs to the java.util package. So, either import java.util.Date or use:
java.util.Date date = new java.util.Date();
dateChooser.setDate(date);

A: To pick up the current date with desired format (format is necessary when you work with database) -
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();

Then just set it to the jdatechooser field
jDateChooser.setDate(date);


text:
Q: How can I count the instances of a custom taxonomy term in the scope of a custom post type? I have a custom taxonomy called "tasks" shared between two custom post types of "roles" and "products".
Expected results:
I need to count how many times a given "task" term is used for each "role" post type minus the count shared by a "product" post type using the same "task" term.
Actual results:
None to report as I don't know how to tackle this
Error messages:
None
What I've tried:
Google keeps coming back with how to count the post type, not the terms :(
The code below is my plan B. Here I am just doing some micro loops on each post-type (only one shown below for brevity), getting the tasks and turning them into an associative array via array_count_values
    $taskList = [];

    $queryRoles = new WP_Query( array(
        "post_type" => "roles"
    ));

    while ( $queryRoles->have_posts() ) : $queryRoles->the_post();
        $tasks = get_the_terms( get_the_ID(), "tasks" );
        foreach ( $tasks as $task ) :
            $taskList[] = $task->name;
        endforeach;
    endwhile;

    $overlappingRoleTasks = $taskList;

    print_r(array_count_values($taskList));

A: you could do a loop restricted to only posts with tasks assigned and one restricted to only products with assigned tasks.
Then using sizeof(); which return the number of elements in an array, count each number of posts and products and then do some basic php maths.
More about sizeof(); @ https://www.w3schools.com/php/func_array_sizeof.asp


text:
Q: Img_to_array returns blank value I have a image augmentation script which i use to perform some operations on images. But the img_to_array function of Keras returns Blank value on calling.
I have made the script for augmentation but it has been facing some issues.
from numpy import expand_dims
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot
from glob import glob
import glob
import cv2
import os

def get_images(m):
    count = 0
    img_list = []
    images_path = glob.glob(m)

    out = "C:\\Python35\\augmented_images\\horizontal_shift\\"

    if not os.path.exists(out):
        os.makedirs(out, exist_ok=True)

    for folder in images_path:
        for f in glob.glob(folder+"/*.jpg"):
            img_list.append(f)
            print(img_list)

        for i in range(len(img_list)):
            img_base = os.path.basename(img_list[i])
            img_name = os.path.splitext(img_base)[0]
            img = load_img(img_list[i])
            print(img)
            data = img_to_array(img)
            samples = expand_dims(data, 0)
            datagen = ImageDataGenerator(width_shift_range=[-200, 200])
            it = datagen.flow(samples, batch_size=1)
            for i in range(9):
                batch = it.next()
                cv2.imwrite(out + img_name+"_%d.jpg" % count, batch)
                count += 1

folders = ("C:\\Python35\\augment_img_data\\*")
get_images(folders)

Why is the img_to_array reutrn blank. What needs to be chnged so that the augmentation operation can be performed

A: Try this. I dont think you will have to expand the dimensions.
img = image.load_img(file, target_size=(224, 224))
img = image.img_to_array(img)
#x = resnet50.preprocess_input(img)
x = np.array([img])
feature = model.predict(x)

or this
img = load_img(img_list[i])
print(img)
data = img_to_array(img)
samples = expand_dims(data, axis= 1)


text:
Q: How can I print the error message into a txt or json file in my directory? I have a function that save all the error in a errormessage list
public class Util {
    private List<String> errorMessages = new ArrayList<>();

    public void outputResult(String content) {
        logger.error(content);
        errorMessages.add(content);
    }
}

and my compare function add all the error message to the list,
public void compare(Config source, Config target) {
    if (source.getId() != target.getId()) {
        util.outputResult("id not equal");
    }
    // ...
}

And in my main function, I call this compare function and want to save all the error message in a txt or some other file in my current directory
public class MyClass {
    public void main() {
        compare();

        // writeToFile
    }
}

This is what I'm doing right now, I convert ByteArrayOutputStream to a string and print it, there a txt file generated but is empty, and I don't want to a string, I want each error message in the list be printed, how can I do that?
ByteArrayOutputStream errorMessages = new ByteArrayOutputStream();

try (FileWriter w = new FileWriter(pathToReport)) {
    w.write(errorMessages.toString());
}
File errorMessagesFile = new File(pathToReport);

errorMessagesFile.writeText(errorMessages.toString());

A: What logger library that you are using? If you use sl4j, you can couple it with log4j by configuring properly to just log the error messages into the file that you have specified in the configuration. I've done some lookup and I find this stackoverflow: where-does-the-slf4j-log-file-get-saved answer provided a template for you to follow on with this setup.


text:
Q: How long a Promise can remain in pending state? I'm using Promises in Angular (4) project and I have a question about them that I couldn't find a response to it in the docs.
When I create a Promise, I basically wait for an async answer from a service/party. But how long should I expect this Promise to stay in pending state?
Is there any mechanism that will terminate it after a while?
How reliable is this concept of waiting/pending?
Let's suppose that I need to get some data from a busy service that can answer even after few minutes of waiting, maybe more, no matter if the computing of the response is a resource intensive process or that service is linked with another one that is responding very slow.
Is there anything on the client side that will somehow terminate my Promise and determine/force to create another one to ask again for my data?
Someone suggested to upgrade to Observables, and I will do that, but for now I want to keep using Promises, at least for some areas of the code.
Tks a lot

A: A Promise can be in pending state as long as the page is loaded.
You can wrap the call in another Promise where you introduce a timeout like shown in
let wrappingPromise = new Promise((resolve, reject) => {
  var error = false;
  setTimeout(function(){
    reject("some error");
  }, 3000);
  this.http.get(...).toPromise().then(res => {
    if(!error) {
      resolve(res.json);
    }
  });
});

This will cause an error when the timeout is reached.
It will still wait to receive the full response.
An Observable might be able to forward a cancellation and close the connection, so that the result isn't even received anymore when the timeout is reached. This might depend on whether the concrete implementation and the browser used browser API supports that.

A: new Promise(() => {}) will never settle, like a callback never called.
A promise is a return object you attach callbacks to, instead of passing callbacks into the function. That's all. It is not a control surface of the asynchronous operation that was just started.
Instead, look to the asynchronous API you called for such controls, if it has them.
Creating promises
Most people are consumers of promises returned from asynchronous APIs. There's no reason to create a Promise other than to wrap a legacy callback API. In an ideal world there'd be no need.


text:
Q: Shell script with comment, command not found when creating variable I have the following script which works:
x=10
echo $x
now=$(date +'%Y-%m-%d')
echo $now

However, when I add a comment line at the beginning:
# comment
x=10
echo $x
now=$(date +'%Y-%m-%d')
echo $now

I get the following:
x=10: command not found
x: undefined variable

Why is the addition of the comment causing the script to fail?
if I do the following it works:
x=10
echo $x
now=$(date +'%Y-%m-%d')
# comment here
echo $now

A: This is a quirk of csh.  (Stop using csh!)  csh will process a script that does not begin with a '#' using a "standard shell" (quoting from the csh manpage.)  When the script begins with '#', csh parses it. Your script is not valid csh.
You should probably add a shebang line to avoid this type of issue.  That is, make the first line:

#!/bin/sh

A: try something like this
#!/bin/sh
#
x=10
echo $x
now=$(date +'%Y-%m-%d')
echo $now

This works on my system (Ubuntu 11.04, 64bit). If that doesn't work then you may have some hidden special character in your file.


text:
Q: Using email to link two graphs If I have two following two graphs:
<http://example.com/graph1>

:A foaf:mbox "A@example.com"

and
<http://example.com/graph2>

:B foaf:mbox "a@EXAMPLE.com";
foaf:phone "123456878" .

How can I get:
----------------------
| person | phone     |
======================
| A      |"123456878"|
----------------------

A: How about something like the following?  Since the email addresses don't use the same case, I've normalized them using lcase.
select ?person ?phone {
  graph ?g { ?person foaf:mbox ?email1 }
  graph ?h { ?person_ foaf:mbox ?email2 ; foaf:phone ?phone }
  filter (lcase(?email1) = lcase(?email2))
}


text:
Q: package amt: unnest tracks produces a list-like object of class NULL I am not sure whether this is an amt or a tidyr issue, but there is no amt tag yet, so here we are.
When working with nested tracks, any calculation (e.g. step_lengths) done in the nested tracks creates a new "list-like" column outside the "data" column, with the same number of rows. I am not sure that is the desired outcome, I'd rather have it added to the nested dataset inside the "data" column, but that's fine, it can be easily solved by unnesting and nesting again (in theory). However, unnest produces this weird list-like object of class NULL, and although I have managed to find a workaround to turn it back into a dataframe, then I need to use make_tracks and nest again to go back to the starting point, which is annoying. Code below with a reprex
First make the dataset
library(random)
test_df <- data.frame(id = rep(c("A", "B", "C"), each = 100),
                  lon = runif(min = -9, max = -6, n = 300),
                  lat = runif(min = 51, max = 55, n = 300),
                  covar1 = runif(min = 0, max = 100, n = 300),
                  covar2 = c(randomStrings(n=300, len=3, unique = F,
                                         upperalpha = T, loweralpha = F,
                                         digits = F)))

Now make it a nested track
test_tracks <- test_df %>%
  make_track(lon, lat,
             all_cols = T,
             crs = 4326,
             check_duplicates = FALSE,
             verbose = TRUE) %>%
  nest(data = c(-id))

Calculate step lengths
test_tracks2 <- test_tracks %>%
  mutate(sl = map(data, step_lengths))

This produces a nested df that has an additional "list" column, sl
> str(test_tracks2, 2)
nested_track [3 × 3] (S3: nested_track/tbl_df/tbl/data.frame)
 $ id  : chr [1:3] "A" "B" "C"
 $ data:List of 3
 $ sl  :List of 3

Unnest
test_tracks3 <- test_tracks2 %>%
  unnest(cols = c(data, sl))

This produces a list, but of class NULL
> class(test_tracks3)
[1] "NULL"
> str(test_tracks3)
List of 6
 $ id    : chr [1:300] "A" "A" "A" "A" ...
 $ x_    : num [1:300] -7.67 -7.96 -8.39 -7.26 -8.49 ...
 $ y_    : num [1:300] 54.3 53.6 54.8 51.9 52.2 ...
 $ covar1: num [1:300] 55.028 0.772 76.037 64.362 34.512 ...
 $ covar2: chr [1:300] "KRU" "RJL" "RVG" "BUW" ...
 $ sl    : num [1:300] 0.718 1.28 3.087 1.261 0.648 ...
 - attr(*, "class")= chr "NULL"
 - attr(*, "row.names")= int [1:300] 1 2 3 4 5 6 7 8 9 10 ...

I can turn this list back to a normal df with do.call, but other dplyr or tibble methods won't work
x <- as.data.frame(do.call(cbind, test_tracks3))
> str(x)
'data.frame':   300 obs. of  6 variables:
 $ id    : chr  "A" "A" "A" "A" ...
 $ x_    : chr  "-7.67035690904595" "-7.96027435711585" "-8.38539077946916" "-7.25699410191737" ...
 $ y_    : chr  "54.2703927513212" "53.6132442755625" "54.8205336350948" "51.9466292150319" ...
 $ covar1: chr  "55.0277820788324" "0.772069441154599" "76.0366528760642" "64.3617564812303" ...
 $ covar2: chr  "KRU" "RJL" "RVG" "BUW" ...
 $ sl    : chr  "0.718259177377767" "1.27994983112401" "3.08749181012144" "1.26120128657495" ...

However it is a plain df now, and all the variables have lost their format (they are all chr) which is not ideal.
Any idea why this is happening and how to fix it?

A: I do not know why this is happening, but another workaround is to nest 'id' prior to  making the track itself.
test_df <- data.frame(id = rep(c("A", "B", "C"), each = 100),
                      lon = runif(min = -9, max = -6, n = 300),
                      lat = runif(min = 51, max = 55, n = 300),
                      covar1 = runif(min = 0, max = 100, n = 300),
                      covar2 = c(randomStrings(n=300, len=3, unique = F,
                                               upperalpha = T, loweralpha = F,
                                               digits = F)))

test_tracks <- test_df %>%
  nest(data = -id) %>%
  mutate(trk = map(data, function(d) {
    make_track(d, lon, lat,
    all_cols = T,
    crs = 4326,
    check_duplicates = FALSE,
    verbose = TRUE)}))

test_tracks2 = test_tracks %>%
  mutate(sl = map(trk, amt::step_lengths))

test_tracks3 <- test_tracks2 %>%
  select(-c(data)) %>%
  tidyr::unnest(cols=c(trk, sl))

A: I always approach this kind of calculations like this:
library(random)
library(amt)
test_df <- data.frame(id = rep(c("A", "B", "C"), each = 100),
                      lon = runif(min = -9, max = -6, n = 300),
                      lat = runif(min = 51, max = 55, n = 300),
                      covar1 = runif(min = 0, max = 100, n = 300),
                      covar2 = c(randomStrings(n=300, len=3, unique = F,
                                               upperalpha = T, loweralpha = F,
                                               digits = F)))

trk <- test_df %>%
  nest(data = -id) %>%
  mutate(data = map(data, ~ {
    make_track(
      .x, lon, lat,
      all_cols = TRUE,
      crs = 4326,
      check_duplicates = FALSE,
      verbose = TRUE)}))

And apply whichever function needed on each element of the list-column.

trk1 <- trk %>%
  mutate(data = map(data, ~ mutate(.x, sl = step_lengths(.x)))) %>%
  unnest(cols = data)

Unfortunately, trk1 loses the track_xy classes. I file an issue for this.


text:
Q: Safari cannot open the page because it could not connect to the server When I tried to use Fb and Twitter authentication with firebase it shows below error. Same error shows both on the iOS device and simulator. Could you tell me how to sort out this issue? I'm using Ionic 3 app.
Note: This is working fine on Android device though.
I have used this article: Ionic Social Login using Firebase

Safari cannot open the page because it could not connect to the server

This is the error:

.ts
 async loginWithFacebook(): Promise<string> {
    try {
      const response = await this.afAuth.auth.signInWithRedirect(new firebase.auth.FacebookAuthProvider());
      const result = await this.afAuth.auth.getRedirectResult();
      return result.additionalUserInfo.profile.email;
      }
    catch (err) {
      console.log(err);
    }


text:
Q: Find the browsers default value for a CSS property with JavaScript Is it possible to retrieve the browsers default value for a CSS property, ignoring any inline/imported styles, using JS?
Some context: I'm using JS to in-line all styles on a specific SVG element and its children (which allows me to turn it into a PNG using canvg). At the moment my output is hugely bloated with every single available style, I would like to be able to discard any properties which are using the browser default values from the array of styles that are include in-line.
Demo of what's happening:

$.extend($.fn, {
  makeCssInline: function() {
    this.each(function(idx, el) {
      var style = el.style;
      var properties = [];
      for (var property in style) {
        if ($(this).css(property)) {
          // TODO: Only in-line this style if it's not browser default
          properties.push(property + ':' + $(this).css(property));
        }
      }
      this.style.cssText = properties.join(';');
      $(this).children().makeCssInline();
    });
  }
});

$(document).ready(function() {
  $("#before").text($("svg")[0].outerHTML.length);
  $("svg").makeCssInline();
  $("#after").text($("svg")[0].outerHTML.length);
});
svg circle {
  fill: #080;
}

svg text {
  fill: #FFF;
}

<svg version="1.1" baseProfile="full" width="300" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="150" cy="50" r="50" />
  <text x="150" y="65" font-size="40" text-anchor="middle">SVG</text>
</svg>

Total characters before in-lining styles:

Total characters after in-lining styles:

As you can see, even for a simple SVG this process adds a huge amount of unnecessary data.

A: You can compute the default style value of a newly created element by using getComputedStyle(). But the new element must be inserted in the DOM for this to work:
function getDefaultStyleOf(tagName, name)
{
    var element = document.createElement(tagName);

    document.body.appendChild(element);
    var value = getComputedStyle(element)[name];
    document.body.removeChild(element);

    return value;
}

console.log(getDefaultStyleOf('code', 'font-size'));


text:
Q: include failed to open stream Senhoras e senhores, por favor, me ajudem.
Tenho um arquivo clientes.php, que possui uma tabela de clientes a ser preenchida.
Os dados que irão preencher essa tabela está na classe Cliente.php.
Estou, portanto utilizando um include 'Cliente.php' no início do arquivo, da seguinte forma:
<?php

include 'Classes/Modelo/Cliente.php';
?>

<title>Clientes | </title>
mais algum código html...

O arquivo Cliente.php também possui um include, da seguinte forma:
<?php

include 'Persistencia/ClienteCRUD.php';

class Cliente {

    private $cpf;
    private $nome;
    private $crud;

    public function __construct() {
        $this->crud = new ClienteCrud();
    }

    public function getCpf() {
        return $this->cpf;
    }

    public function getNome() {
        return $this->nome;
    }

    public function setCpf($cpf) {
        $this->cpf = $cpf;
    }

    public function setNome($nome) {
        $this->nome = $nome;
    }

    public function inserir() {
        return $this->crud->create($this);
    }

    public function alterar() {
        $this->crud->update($this);
    }

    public function excluir() {
        $this->crud->delete($this);
    }

    public function listar() {
        $result = $this->crud->read();
        return $result;
    }

}

?>
Pois bem, está dando o seguinte erro:

Warning: include(Persistencia/ClienteCRUD.php): failed to open stream: No such file or directory in C:\xampp\htdocs\inove\gentelella-master\production\Classes\Modelo\Cliente.php on line 3

Bom, sinceramente, eu não sei o que está ocorrendo.
O arquivo 'clientes.php' está localizado no diretório production.
O arquivo 'Cliente.php' está em production/Classes/Modelo/
O arquivo 'ClienteCRUD.php' está em production/Classes/Persistencia.
Gente, já pesquisei bastante, mas sinceramente não sei o que tem de errado.
Por favor, se puderem me ajudar, serei muito grato, pois estou parado neste projeto apenas por causa disso.
OBS: Tenho que usar PHP sem ajuda de nenhum framework.
Obrigado

A: Você pode utilizar a constante magica:
require __DIR__ . '/../Persistencia/ClienteCRUD.php';

Ela contém o diretório do arquivo, e o nome do diretório não possui uma barra / no final, a não ser que seja o diretório raiz /, então lembre-se de colocar a barra caso não esteja na raiz.


text:
Q: C# programming for a label link? Ok here is my problem[or you can sat awkward question), I have a label I have created a link for it, working example below:
string strLinkBegin = "";
            string strLinkMid = "' target='_blank'>";
            string strLinkEnd = "";
            string strQuerystring = "";
 strQuerystring = "somePage.aspx" + "?AMode=" + "Update" + "&someID=" + hdnsomeLink.Value;
 lblFromDesc.Text = strLinkBegin + strQuerystring + strLinkMid + hdnFromDescText.Value + strLinkEnd;

Real question:  can I write something similar to code you see below in a label and when user clicks it it executes? I know I can program through link button but was interested if its possible to do the same thing in a label.
someclass WTRadWindow = new someclass();
WTRadWindow.OpenUpdateForm(Page, hdnToDescLinkURL.Value, 350, 263);

A: To start with you could take a look here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink.aspx
It does, to me at least, seem as if you are using the wrong control to achieve what you are after, in that putting a html link into a Label seems to be a slight misuse of the control. The HyperLink control is what first came to mind when reading your question. That is why I gave you the link.
Whether or not it is a misuse, I think it is not of great importance, but the HyperLink control should provide what you are wanting.

A: The Label control cannot contain HTML text, it is designed to display plain text.
As discussed in another answer, the most appropriate solution would be to use the Hyperlink Control.
If it's really important for you to generate the HTML as a string and then add it to the page you would need to use the LiteralControl.  If you just used that instead of a label your existing code should work just fine.  I want to mention though that literal controls should be used sparingly, and that it really isn't appropriate in this situation.  So much of what makes ASP great is that you don't need to create HTML as a string.


text:
Q: react/axios -- not able to get data by API call I am working on React first time, I am doing a API call in my react code. I am following an example from net. The example working perfectly. And I am following same way and implemented my API call. API call is successful. but I am assigning the response to an object and printing it in the console, but my object printing as unknown.
My code:
export const getXFlowdata = async () => {
    try{
        const {data} = axios.get(xurl, { headers: headers });

        console.log('Data: ', data)
        console.log('Data Type: ',typeof data)

        return data;

    }catch(error) {
        throw error;
    }
}

Output:

Data:  undefined
Data Type:  undefined

Example I fallowing:
export const getPieData = async () => {
    try{
        const {data} = await axios.get(baseUrl);
        console.log('Data: ', data)
        console.log('Data Type: ',typeof data)
        return data;
    }catch(error){
        throw error;
    }
}

Output:

Data:  {confirmed: {…}, recovered: {…}, deaths: {…}, dailySummary:
Data Type:  object

A: You are getting a promise rather the data itself because you have not written await inside an async function and the promise
does not have any property data because it is not resolved yet.
  export const getXFlowdata = async () => {
    try{
        const {data} = await axios.get(xurl, { headers: headers });

        console.log('Data: ', data)
        console.log('Data Type: ',typeof data)

        return data;

    }catch(error) {
        throw error;
    }
}


text:
Q: Android's BreakIterator considers line breaks as sentence delimiters I have a unix text file that I want to read in my Android app and split it into sentences. However I noticed that BreakIterator considers some line break characters as sentence delimiters.
I use the following code to read the file and split it into senteces (only the first sentence is output for presentation purpose):
        File file = new File...
        String text = "";
        BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(Locale.US);

    try {
        FileInputStream inputStream = new FileInputStream(file);

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        StringBuilder stringBuilder = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append('\n');
        }

        inputStream.close();
        text = stringBuilder.toString();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    sentenceIterator.setText(text);
    int end = sentenceIterator.next();
    System.out.println(end);
    System.out.println(text.substring(0, end));

But if I compile and run the code from Eclipse as a Desktop app the text is split correctly. I don't understand why it doesn't do the same on Android app.
I tried to convert the text file to dos format, I even tried to read the file and preserve original line breaks:
    Pattern pat = Pattern.compile(".*\\R|.+\\z");
    StringBuilder stringBuilder = new StringBuilder();
    try (Scanner in = new Scanner(file, "UTF-8")) {
        String line;
        while ((line = in.findWithinHorizon(pat, 0)) != null) {
            stringBuilder.append(line);
        }
        text = stringBuilder.toString();
        sentenceIterator.setText(text);
        int end = sentenceIterator.next();
        System.out.println(end);
        System.out.println(text.substring(0, end));
    }

but without success. Any ideas?
You can download an excerpt from the file (unix format) here: http://dropmefiles.com/TZgBp
I've just noticed that it can be reproduced without download of this file. Just create a string that has line breaks inside sentences (e.g. "Hello, \nworld!") and run an instrumented test. If BreakIterator is used in a usual test then it splits correctly.
I expect 2 sentences:
sentence 1:

Foreword
IF a colleague were to say to you, Spouse of me this night today
  manufactures the unusual meal in a home.

sentence 2:

You will join?

Yes, they don't look great but at least you know why it is so (sentence delimiters are ?. etc.). But if the code runs on Android it creates a sentence even from

Foreword

for some reason...
I'm not sure whether it is a bug, or whether there is a workaround for this. But in my eyes it makes Android version of BreakIterator as sentence splitter useless as it is normal for sentences in books to spread over multiple lines.
In all the experiments I've used the same import java.text.BreakIterator;

A: This is not really an answer but it might give you some insights.
It is not a file encoding issue, I tried it it his way and have the same faulty behaviour.
BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(Locale.US);
String text = "Foreword\nIf a colleague were to say to you, Spouse of me this night today manufactures the unusual meal in a home. You will join?";
sentenceIterator.setText(text);

Android does not use the same Java version as your computer
I noticed that when I printout the class of the sentenceIterator object
sentenceIterator.getClass()

I have different classes when running with IntelliJ and when running on Android:
Running with IntelliJ:
sun.util.locale.provider.RuleBasedBreakIterator

Running on Android:
java.text.RuleBasedBreakIterator

sun.util.locale.provider.RuleBasedBreakIterator has the behaviour you want.
I don't know how to get Android to use the good RuleBasedBreakIterator class. I don't even know if it is possible.


text:
Q: Variable substitution error in Pi-calculus I am learning the language K, so I started a little implementation of the Pi-Calculus with K.
I can't figure out why my substitution Q[Z/Y] doesn't work in my program below.
My program is: (m(z) . m ! z) | (m ! 4 . m(x)) (a ping/pong between two thread),  and with my K semantic below I get this output:
</thread> <thread>
    <k>
      m ! z ~> .
    </k>
  </thread> <thread>
    <k>
      m ( x ) ~> .
    </k>

But z is not substituted. I would expect this output:
</thread> <thread>
    <k>
      m ! 4 ~> .      <---The 2nd z take the value of 4
    </k>
  </thread> <thread>
    <k>
      m ( x ) ~> .
    </k>

Here is my K semantic for the Pi-calculus.
Notice that I use x!y instead of x<y> for the send construction.
require "substitution.md"

module PI-SYNTAX
    imports DOMAINS-SYNTAX
    imports KVAR-SYNTAX

    syntax Val ::= KVar  [binder]
                | Int

    syntax Proc ::= "(" Proc ")"        [bracket]
                | Send
                | Receive
                | None
                | Replication
                > Proc "." Proc         [left]
                > Par

    syntax None ::= "None"

    syntax Par ::= Proc "|" Proc        [left]

    syntax Receive ::= Id "(" Val ")"

    syntax Send ::= Id "!" Val

    syntax Replication ::= "!" Proc

endmodule

module PI
    imports PI-SYNTAX
    imports DOMAINS
    imports SUBSTITUTION

    syntax KResult ::= Int | Bool

      configuration <T color="yellow">
                        <thread multiplicity="*" type="Set" color="blue">
                            <k color="green"> $PGM:Proc </k>
                        </thread>
                    </T>

    // Parallel composition:
    rule <thread> <k> P1:Proc | P2:Proc => . ... </k> </thread>
        (.Bag => <thread> <k> P1 </k> </thread>)
        (.Bag => <thread> <k> P2 </k> </thread>)

    // Communicate reduction: x ! y . P | x(y) . Q => P | Q[z/y]
    rule
        <thread> ... <k> X:Id ! Y:Val . P:Proc => P </k> ... </thread>
        <thread> ... <k> X:Id ( Z:Val ) . Q:Proc => Q[Z/Y] </k> ... </thread>
endmodule

Thank you in advance.


text:
Q: I want to to charge a capacitor with rectified mains voltage BUT But when I make the connections the house fuse just blows.Capacitor values is 3000uF 450v. When I measure the voltages of the rectified (bridge) mains, I get a reading of 207VDC and 80VAC
(ı think its the unfiltered bumps, but not sure)
But then I tried 1000uf 450v and fuse didnt blow. How can I charge a cap with mains? Can anyone help? Thx

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Series mains lamp.

But when I make the connections the house fuse just blows.

This probably means that you did this without a circuit fuse. This is foolish. You should include a fuse rated to limit the current to a safe value.
While we're on the subject, fuse discrimination is a topic you can read up on to learn how to size fuses properly so that the fuse closest to the load blows without blowing or tripping upstream protection devices which would affect other devices on that circuit.

Capacitor values is 3000 uF 450 V.

A discharged capacitor will act as a short circuit when initially connected to the supply. Apart from tripping your fuse / circuit breaker it could also destroy the bridge rectifier.

How can I charge a cap with mains?

Add a mains rated bulb in series. You may see an initial flash and fade out as the capacitor charges up. You can also use it to discharge the capacitor safely.

Safety: there is enough energy in this circuit to kill. All should be enclosed in an insulated case or in an earthed metal case.


text:
Q: MySQL Query To Produce Amount Per Month I have a table that contains:
id           date                   user_id   duration  amount
1            2014-01-01 00:00:00    1         1         £10
2            2014-01-02 00:00:00    2         2         £10
3            2014-01-03 00:00:00    3         3         £10

I'm trying to display the amount per month. Any ideas how to do this in a query?

A: Working on the assumptions that you can extract the month from you datetime easily, so the real question is about the aggregation logic, and that you can create a numbers table.
Here is a simple example that shows the pattern.
sqlfiddle
CREATE TABLE Num (num int);
INSERT INTO Num VALUES (0),(1),(2),(3),(4);

CREATE TABLE Tbl (start int, run int);
INSERT INTO Tbl VALUES (1,2),(2,3);

SELECT start + num active_month
      ,count(*) * 10 income
  FROM Tbl
       INNER JOIN
       Num ON num < run
GROUP BY start + num

A: What about :
SELECT a.my_date, a.income, IFNULL(SUM(DISTINCT(a.income)) + sum( b.income ), a.income) as roll_up
FROM (
SELECT purchase_id, DATE_FORMAT( date_purchased, '%y-%m') AS my_date, SUM( amount_income / duration ) AS "income"
FROM incomes
GROUP BY my_date
) AS a
LEFT OUTER JOIN (
SELECT purchase_id, DATE_FORMAT( date_purchased, '%y-%m') AS my_date, SUM(amount_income / duration ) AS "income"
FROM incomes
GROUP BY my_date
) AS b ON ( a.purchase_id > b.purchase_id )

GROUP BY a.purchase_id
It's a bit tricky to do that in one shot - and it might be improved - but that gives the following results :
my_date  income     roll_up
13-12    8.5000     8.5000
14-01   10.0000     18.5000
14-02   16.6667     35.1667

My data set is :
1   2013-12-28 00:00:00     1   2   15
2   2014-01-04 00:00:00     2   1   10
3   2014-02-04 00:00:00     3   6   40
4   2013-12-29 00:00:00     4   1   1
5   2014-02-28 00:00:00     5   2   20

A: Like Karl, I'm pretty sure some kind of numbers table is necessary here. Personally I like the approach given here, which defines a view (well, several of them) to generate numbers, instead of having to actually store a table full of numbers. Whether you use a table or a view, when you SELECT from it, it just looks like this:
 n
---
 0
 1
 2
 3
 …

With that you can construct a query like this:
SELECT
  purchases.purchase_id,
  purchases.date_purchased,
  purchases.duration,
  -- generator_16 is our numbers table
  generator_16.n,
  -- Below we calculate the year and month (year_mon) in the following way:
  -- (1) Get the first day of the year, e.g. if date_purchased is 2012-12-28,
  --     this gives us 2012-01-01.
  -- (2) Get the month number, e.g. 12 for 2012-12-28) and add that many months
  --     to the first day of the year, which gives us the first day of the
  --     month, 2012-12-01.
  -- (3) Add "n" months, where "n" is the number we get from the numbers table,
  --     starting at 0.
  DATE_ADD(                                              -- (3)
    DATE_ADD(                                            -- (2)
      MAKEDATE( YEAR(purchases.date_purchased), 1 ),     -- (1)
      INTERVAL MONTH(purchases.date_purchased) - 1 MONTH -- (2)
    ),
    INTERVAL generator_16.n MONTH                        -- (3)
  ) AS year_mon,
  purchases.amount_income / purchases.duration AS amount
FROM purchases
-- The below JOIN means that if `purchases.duration` is 3, we get three rows
-- that have 0, 1, and 2 in the `n` column, which we use as the number of dates
-- to add in (3) above.
JOIN generator_16
ON generator_16.n BETWEEN 0 AND purchases.duration - 1
ORDER BY purchases.purchase_id, year_mon;

This gives us a result like this (SQL Fiddle):
purchase_id  date_purchased  duration  n      year_mon  amount
-----------  --------------  --------  -  ------------  ------
          1    2013-12-28 …         2  0  2013-12-01 …     7.5
          1    2013-12-28 …         2  1  2014-01-01 …     7.5

          2    2014-01-04 …         1  0  2014-01-01 …      10

          3    2014-02-04 …         6  0  2014-02-01 …  6.6667
          3    2014-02-04 …         6  1  2014-03-01 …  6.6667
          3    2014-02-04 …         6  2  2014-04-01 …  6.6667
          3    2014-02-04 …         6  3  2014-05-01 …  6.6667
          3    2014-02-04 …         6  4  2014-06-01 …  6.6667
          3    2014-02-04 …         6  5  2014-07-01 …  6.6667

I inserted blank lines to separate the purchase_id groups so you can see how n increases from 0 to duration - 1 with each item in the group. As you can see, year_mon is equal to n months after the first day of the date_purchased month plus n months, and amount is equal to amount_income / duration.
We're almost done, but as you can see year_mon has repetition: 2014-01-01 is shown twice. This is great news, because we can then use GROUP BY to group by that column and SUM(amount) to get the total for that month:
SELECT
  DATE_ADD(
    DATE_ADD(
      MAKEDATE( YEAR(purchases.date_purchased), 1 ),
      INTERVAL MONTH(purchases.date_purchased) - 1 MONTH
    ),
    INTERVAL generator_16.n MONTH
  ) AS year_mon,
  SUM(purchases.amount_income / purchases.duration) AS total
FROM purchases
JOIN generator_16
ON generator_16.n BETWEEN 0 AND purchases.duration - 1
GROUP BY year_mon
ORDER BY year_mon;

The only difference between this query and the previous month is that we do GROUP BY year_mon and then SUM(amount_income / duration) to get total for the month, yielding this result (SQL Fiddle):
    year_mon   total
------------  ------
2013-12-01 …     7.5
2014-01-01 …    17.5
2014-02-01 …  6.6667
2014-03-01 …  6.6667
2014-04-01 …  6.6667
2014-05-01 …  6.6667
2014-06-01 …  6.6667
2014-07-01 …  6.6667

...and of course you can use DATE_FORMAT and CAST or ROUND to get nicely-formatted dates and amounts, or you can do that in your front-end code.


text:
Q: Othello Alpha-Beta Pruning playing badly python I am currently trying to make a good AI for Othello, and have done so using the Minimax algorithm. However, when I tried to make a deeper search using alpha-beta pruning, it seemed like the algorithm was playing terribly. I checked it with other sources like Wiki and Berkely.edu , and I think I have implemented it correctly, but I still can't find the problem.
def alphabeta(board, player, a, b, lev):
        h = heur(board, player)
        if lev == 0:
                return h, None
        poss = get_legal_moves(board, player)
        if len(poss) == 0:
                return h, None
        move = 0
        for x in poss:
                cpboard = board[:]
                cpboard[x] = player
                bracket(cpboard, player, x)
                a1, q = alphabeta(cpboard, opponent_color(player), a, b, lev-1)
                if player is me:
                        if a1 > a:
                                a, move = a1, x
                else:
                        if a1 < b:
                                b, move = a1, x
                if b <= a:
                        break
        if player is me:
                return a, move
        else:
                return b, move

A: Your alpha-beta code is probably wrong. Be aware of what happens when a player 'pass the turn' (i.e. has no available moves), i had a tricky bug in my code, due to this.
Did you call the recursion with the alpha and beta values switched?
Mine works like this (Java code):
private float minimax(OthelloBoard board, OthelloMove best, float alpha, float beta, int depth)
{
    float bestResult = -Float.MAX_VALUE;
    OthelloMove garbage = new OthelloMove();

    int state = board.getState();
    int currentPlayer = board.getCurrentPlayer();

    if (state == OthelloBoard.STATE_DRAW)
        return 0.0f;
    if ((state == OthelloBoard.STATE_BLACK_WINS) && (currentPlayer == OthelloBoard.BLACK))
        return INFINITY;
    if ((state == OthelloBoard.STATE_WHITE_WINS) && (currentPlayer == OthelloBoard.WHITE))
        return INFINITY;
    if ((state == OthelloBoard.STATE_BLACK_WINS) && (currentPlayer == OthelloBoard.WHITE))
        return -INFINITY;
    if ((state == OthelloBoard.STATE_WHITE_WINS) && (currentPlayer == OthelloBoard.BLACK))
        return -INFINITY;

    if (depth == maxDepth)
        return OthelloHeuristics.eval(currentPlayer, board);

    ArrayList<OthelloMove> moves = board.getAllMoves(currentPlayer);

    for (OthelloMove mv : moves)
    {
        board.makeMove(mv);
        alpha = - minimax(board, garbage, -beta, -alpha, depth + 1);
        board.undoMove(mv);

        if (beta <= alpha)
            return alpha;
        if (alpha > bestResult)
        {
            best.setFlipSquares(mv.getFlipSquares());
            best.setIdx(mv.getIdx());
            best.setPlayer(mv.getPlayer());
            bestResult = alpha;
        }
    }

     return bestResult;
}

The call is like:
 OthelloMove bestFound = new OthelloMove();
 int maxDepth = 8;
 minimax(board, bestFound, -Float.MAX_VALUE, Float.MAX_VALUE, maxDepth);
//Wait for Thread to finish
 board.makeMove(bestFound);

Edit: In case a player has no available moves, getAllMoves() return a 'dummy move', that
doesn't change the board at all, just pass the turn.
Hope it helps!

A: Your alphabeta implementation looks sound to me.  Since minimax and alphabeta produce the same results when implemented correctly, you should be able to use your old minimax code as a check against alphabeta, at least for modest search depths.  If their results differ when searching the same game tree, then you know you've done something wrong.
But most likely, the poor play is the result of something in your "heur" evaluation function.


text:
Q: Strange behavior for loop in python I am writing this code to read a text file and then print the line number after each line here is my code
with open("newfile.txt") as f:
 for line in f:
  x=1
  y=str(x)
  print(line)
  print(x)
  x=x+1
f.close()

I should expect some thing like that
Line one
1
Line two
2
Line three
3
but instead I am getting
Line one
1
Line two
1
Line three
1
Why is that !?

A: You can just use enumerate() :
with open("newfile.txt") as f:
 for num,line in enumerate(f,1):
      print line,'\n',num

Also note that you don't need to close the file when you use the with statement. It will automatically does it for you.
And about the x variable in your code, you shouldn't initialized it in your loop, you need to put x=1 out of the loop.

A: The problem is that you are initializing x to 1 inside the loop and before the print statement.
try:
x = 1
with open("newfile.txt") as f:
  for line in f:
    y = str(x)
    print(line)
    print(x)
    x += 1

A: Adding comments to your code will help you see why you always print out  1.
with open("newfile.txt") as f:
  for line in f:
   x=1            # x is now equal to 1
   y=str(x)       # x is still 1, y is now equal to '1'
   print(line)    # prints out the line
   print(x)       # 1 is printed
   x=x+1          # you now add 1 to x, but don't do anything with this
                  # updated value, because in the next loop x is again
                  # initialised to 1
 f.close()

A: The issue with the code would be the x=1 inside of the loop. By moving that outside and initializing that before you should get the result you want. For example:
 x=1
 with open("newfile.txt") as f:
 for line in f:
 y=str(x)
 print(line)
 print(x)
 x=x+1

This should work


text:
Q: Slim 4 - Registering and Accessing Routes I have just created slim 4 project using "composer create-project slim\slim-skeleton appdb". I have a routes.php as
<?php
declare(strict_types=1);

use App\Application\Actions\User\ListUsersAction;
use App\Application\Actions\User\ViewUserAction;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;

return function (App $app) {

    $app->post('/hello', function (Request $request, Response $response) {
        $response->getBody()->write('Hello world!');
        return $response;
    });

};

and the index.php as
<?php
declare(strict_types=1);

use App\Application\Handlers\HttpErrorHandler;
use App\Application\Handlers\ShutdownHandler;
use App\Application\ResponseEmitter\ResponseEmitter;
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;

require __DIR__ . '/../vendor/autoload.php';

// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();

if (false) { // Should be set to true in production
    $containerBuilder->enableCompilation(__DIR__ . '/../var/cache');
}

// Set up settings
$settings = require __DIR__ . '/../app/settings.php';
$settings($containerBuilder);

// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);

// Set up repositories
$repositories = require __DIR__ . '/../app/repositories.php';
$repositories($containerBuilder);

// Build PHP-DI Container instance
$container = $containerBuilder->build();

// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
$callableResolver = $app->getCallableResolver();

// Register middleware
$middleware = require __DIR__ . '/../app/middleware.php';
$middleware($app);

// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);

/** @var bool $displayErrorDetails */
$displayErrorDetails = $container->get('settings')['displayErrorDetails'];

// Create Request object from globals
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();

// Create Error Handler
$responseFactory = $app->getResponseFactory();
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);

// Create Shutdown Handler
$shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
register_shutdown_function($shutdownHandler);

// Add Routing Middleware
$app->addRoutingMiddleware();

// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);

// Run App & Emit Response
$response = $app->handle($request);
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);

Attempts to access post route as 127.0.0.1/appdb/public/hello/Peter, gives an error
{ "statusCode": 404, "error": { "type": "RESOURCE_NOT_FOUND", "description": "Not found." } }
What am I doing wrong?
Thanks in advance


text:
Q: Why is error message not showing when applied on RadioButtons or Checkboxes So I have this form. I am applying errors on the widgets with the following method
editText.setError("Please write at least 5 characters");
checkBox.setError("Please, choose");
radioButton.setError("Please, choose");

But the text for the RadioButtons and for the Checkboxes does not seem to show. Any ideas?

A: it is showing red mark your code is working perfectly fine because setError() method is only available for widgets that extend TextView. But gladly all relevant Widgets for error messages do inherit from TextView: EditText, AutoCompleteTextView, CheckBox and RadioButton (well, the hierarchy is weird, but never mind).But there is one problem with using this approach. The message text is only visible when the view has the focus. Otherwise Android only displays the red marker. Try setting the focus on a touch screen with a radio button or a check box


text:
Q: ASP.net MVC 5 Session is not clearing after calling Abandon() MVC noob here.
I currently have this code that fires off my HomeController when a page loads via AJAX:
namespace ETTData.Controllers
{
  public class HomeController : Controller
  {
    [HttpPost]
    public ContentResult clearSessions()
    {
        var currentSession = System.Web.HttpContext.Current.Session;

        System.Diagnostics.Debug.WriteLine("BEFORE: " + currentSession.Timeout);

        currentSession.Abandon();
        //currentSession.RemoveAll();
        //currentSession.Clear();

        System.Diagnostics.Debug.WriteLine("AFTER : " + currentSession.Timeout);

        return new ContentResult { Content = "OK", ContentType = "text/plain" };
    }
  }
}

The output of the debug.WriteLine is:

BEFORE: 35
AFTER : 35

So as you can see it has 35 on the BEFORE but also has 35 for the AFTER when it shouldnt equal anything since I used currentSession.Abandon(); prior to calling that output.
I am setting the session timeout via the Global.asax.cs file:
namespace ETTData
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Session_Start(Object sender, EventArgs e)
        {
            HttpContext.Current.Session.Timeout = 35;
        }
    }
}

So saying all that - I'm at a loss as to why its not clearing the session...

A: Yea that's a good one that got me too in WebForms a long time ago.
The issue is, that your session is bound to a session cookie.
The cookie is transmitted in the request and response headers, which means via the HTTP protocol. The HTTP protocol is stateless, and therefore, it can't remove a cookie until after a response has been sent.
When you call session.Abandon, the session data will be abandoned at the same time as the cookie is abandoned at the client. Which means the frameworks marks the session data as "to be cleared after the response has been sent", which is after response.end. At response.end (which will be called after ContentResult.ExecuteResult), the framework will then clear the session. Subsequently it will call the Session_End event.
Session.Clear removes items immediately, but it will not remove the session cookie - therefore it also doesn't end the session, and it will not call the Session_End event - which is because it doesn't expire the session cookie.
Think of it as async-function.
You called abandon, but it's not yet executed.
As the others told you, if you need the session cleared immediately, call session.clear after session.abandon.
But if you start another session after you called session.abandon, you'll run into a very sharp knife.
Basically, you should never use sessions.
If you want to access "session" data without a detour into the database, you should store the information in an encrypted and asymmetrically-signed cookie, which you can bind to a session-lifetime, if you want to, but you don't have to. Google JWT for more information. I would bind such data into your auth-cookie. That way, there's no need for >1 cookies. The default timeout of 20 minutes in ASP.NET is a pretty bad thing. Your session data shouldn't expire until your authentication has.
Also, be careful what you write into your session.
If you just store user information there, that's fine.
But if you store state information there, you'll have a problem, because I can open multiple tabs of your site at once, and then the state from tab2 will overwrite the state of tab1. You have ONE session per domain, not one per tab.

A: Have a look at this question to find your answer.
In Short: Session.Abandon destroys the session but doesn't clear it's values. This happens when the request ends. Session.Clear clears everything from the session but doesn't destroy it.


text:
Q: PostgreSQL "date at time zone" unexpected behaviour The behavior of the at time zone operator on the date type is not as expected in PostgreSQL.
set time zone 'UTC';
select
  '2021-01-03'::date at time zone 'America/Chicago' as "value",
  pg_typeof('2021-01-03'::date at time zone 'America/Chicago') as "type";

x
value
type

Expected
2021-01-03 06:00:00+00
timestamp with time zone

Actual
2021-01-02 18:00:00
timestamp without time zone

DB Fiddle
Tested on PostgreSQL server versions 10, 11, 12, and 13.
This behavior is very strange to me, and I have not been able to find anywhere it is described or discussed. It seems PSQL is implicitly casting date to timestamptz (using the system time zone) and then applying the at time zone operator. I know that the at time zone operator is only defined (in the docs) for the timestamp(tz) and time(tz) types. However, I would have assumed PSQL would implicitly cast date to timestamp and not timestamptz because:

*

*It is a "safe" conversion (no need to assume a time zone). Simply append 00:00:00.

*It results in a timestamptz which one would expect when using the at time zone operator on a type that does not have a time zone.

The current behavior simply doesn't make sense to me and I can't think of a use case that would benefit from it. You are asking for the timestamp with time zone for a date at a particular time zone and instead you get a timestamp of the date at the system time zone localized to the given time zone.
Of course, a simple workaround is to cast to timestamp first:
set time zone 'UTC';
select '2021-01-03'::date::timestamp at time zone 'America/Chicago';

I was hoping someone could shed some light on this. What am I missing? Perhaps some overarching rule about how date is implicitly cast to timestamp(tz)? Is this behavior documented somewhere?
Thanks!

*

*Mike

A: You ask "why". The reason is that AT TIME ZONE does not operate on date, so PostgreSQL invokes an implicit type cast to convert it to a different data type. Lacking an explicit directive, PostgreSQL opts for the preferred data type for datetime, which happens to be timestamp with time zone.
The data type resolution rules for operators are documented here, and the preferred type for a type category can be found in the typispreferred and typcategory columns of the pg_type system catalog.

A: As per the Postgresql documentation:
The AT TIME ZONE converts time stamp without time zone to/from time stamp with time zone, and time values to different time zones
Here in first query, you are trying to apply at time zone to date type, not to time stamp
set time zone 'UTC';
select
  '2021-01-03'::date at time zone 'America/Chicago' as "value",
  pg_typeof('2021-01-03'::date at time zone 'America/Chicago') as "type";

which is eventually gets ignored, and you will get a timestamp without timezone
But in second query,
set time zone 'UTC';
select '2021-01-03'::date::timestamp at time zone 'America/Chicago';

You are casting the date to time stamp first and then converting it to desired  time zone,
which gives you the expected result of time stamp with time zone.
Hope this clears your doubt.


text:
Q: Chrome displaying Failed to load resource I have a simple webpage structure:
-index.html
-css
  -style.css

The contents of the html are:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>test</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>

</body>
</html>

When I open the html in Chrome I get the error:

Failed to load resource file:///C:/css/style.css

My directory is in Mydocuments in Windows. Why can't the .css file be found?

A: As the console shows, your path
/css/style.css

means "the 'css' directory in the root path":
C:/css/style.css

which is not what you want*.
Use css/style.css - this will mean "the 'css' sub-directory in the directory the current page's located in."
* But even if it had been what you want, access to local file:// URLs is limited in that any resources you request (images, style sheets) need to be in a sub-directory of the current page. Modern browsers impose this limitation for security reasons.

A: Forward slash first means an absolute path (from the root). Since you are running your page from the file system, the root is the drive.
No forward slash first means a relative path (from the current folder).
You may also want to make a shortcut to your chrome browser that has the "--allow-file-access-from-files" flag, so you can better test your site locally as you add more advanced features.


text:
Q: stdClass Object foreach PHP Been searching for a solution for my problem. Seams meny has the same q as me, but still haven't got a solution for my problem.
I have a stdClass Object that needs to be printed out in a foreach or somlike like that.
Here is a cut of the result i get with a "print_r($result)".
stdClass Object
(
    [ServiceGroup] => Array
        (
            [0] => stdClass Object
                (
                    [Service] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [_] => 3D-modulering
                                    [count] => 71
                                )

                            [1] => stdClass Object
                                (
                                    [_] => CAD
                                    [count] => 81
                                )

                            [2] => stdClass Object
                                (
                                    [_] => Databasutveckling
                                    [count] => 118
                                )

                            [3] => stdClass Object
                                (
                                    [_] => Datainmatare
                                    [count] => 6
                                )

                            [4] => stdClass Object
                                (
                                    [_] => Driftsteknik
                                    [count] => 87
                                )

                            [5] => stdClass Object
                                (
                                    [_] => IT-konsult
                                    [count] => 39
                                )

                            [6] => stdClass Object
                                (
                                    [_] => IT-tekniker
                                    [count] => 223
                                )

                            [7] => stdClass Object
                                (
                                    [_] => Mjuk- och hårdvarutestning
                                    [count] => 150
                                )

                            [8] => stdClass Object
                                (
                                    [_] => Nätverksteknik
                                    [count] => 142
                                )

                            [9] => stdClass Object
                                (
                                    [_] => Produkttestare
                                    [count] => 171
                                )

                            [10] => stdClass Object
                                (
                                    [_] => Programmerare
                                    [count] => 146
                                )

                            [11] => stdClass Object
                                (
                                    [_] => Projektledning
                                    [count] => 156
                                )

                            [12] => stdClass Object
                                (
                                    [_] => Serviceteknik
                                    [count] => 157
                                )

                            [13] => stdClass Object
                                (
                                    [_] => Support
                                    [count] => 360
                                )

                            [14] => stdClass Object
                                (
                                    [_] => Systemadministration
                                    [count] => 145
                                )

                            [15] => stdClass Object
                                (
                                    [_] => Systemutveckling
                                    [count] => 110
                                )

                            [16] => stdClass Object
                                (
                                    [_] => Webbdesign
                                    [count] => 246
                                )

                            [17] => stdClass Object
                                (
                                    [_] => Webbutveckling
                                    [count] => 135
                                )

                            [18] => stdClass Object
                                (
                                    [_] => webmaster
                                    [count] => 103
                                )

                        )

                    [name] => Data/IT
                )

            [1] => stdClass Object
                (
                    [Service] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [_] => Affärsanalys
                                    [count] => 192
                                )

                            [1] => stdClass Object
                                (
                                    [_] => Aktuarie
                                    [count] => 20
                                )

A: I don't know exactly what you want, but can easily foreach through objects just like arrays.  This example shows that.
foreach($result->ServiceGroup as $value){
    foreach($value->Service as $obj){
        echo $obj->_;
        echo $obj->count;
    }
    echo $value->name;
}


text:
Q: how to make buttons same width and float near the center? I created a div row because I need them to be also the same width. I've google and there is not much help. I've tried changing the css using .btn-row.btngroup{ width: some width;} and still does not work!
Here is my code part :

      <button type="button" class="btn btn-default ">Edit</button>
      </button>

    <button type="button" class="btn btn-default ">Delete</button>
    </button>

    <button type="button" class="btn btn-default ">Add Service</button>
    </button>

This is what it needs to look like

This is what mine looks like

Also, how do I make the last button blue? The examples from twitter don't really show much
Thanks and really appreciate it!

A: To make the button blue, add the 'btn-primary' class.
To make them the same width, add a new class to each button (not the group) and define the 'width' of that class to whatever you want.
.my-btn { width: 150px; }

A: To make buttons float near the center just add
margin: 0px 0px 0px 100px;

or
margin-left:100px;

in class btn-row

A: Try something like this:
HTML

         <button type="button" class="btn btn-default ">Edit</button>

         <button type="button" class="btn btn-default ">Delete</button>

         <button type="button" class="btn active btn-default ">Add Service</button>

CSS
.btn-row{
    width:100%;
    text-align: center;
}

.btn{
    border-radius:5px;
    width: 35px; /* You desired width*/
    height: 30px;
    border: 1px solid grey;
    background: #fff;
}

.btn.active
{
    background:#488FE1;
    color: #fff;
    border: 1px solid #488FE1;
}

Here is the jsfiddle


text:
Q: Understanding geometric realisation of a simplicial set I am trying to understand what is geometric realisation of a simplicial set is.
I am not able to understand what exactly do they mean in notes I found online.
Sometimes, starting something fresh gives better clarity so I am not writing what I have seen in online notes.

A simplicial set $X$ is a collection of sets $X_n$ indexed by integers $n\geq0$ along with maps $$d_i:X_n\rightarrow X_{n-1}, s_:X_n\rightarrow X_{n+1}$$ called face maps and degeneracy maps respectively satisfying compatibility conditions.

I did not see anywhere explicitly but I guess they are not allowing $X_n$ to be empty sets. Is that correct?
Please help me to build up the notion of geometry realisation from scratch.

A: There are no maps $S \to \varnothing$ if $S$ is nonempty, but there is a unique map $\varnothing \to \varnothing$, so if $X$ is a simplicial set with $X_n = \varnothing$ for some $n$, then in fact $X_n = \varnothing$ for all $n$, and the faces/degeneracies are all $1_\varnothing$. In fact, this "empty simplicial set" is the initial object in the category of simplicial sets.
To motivate geometric realization, you need a very general statement in category theory. For simplicial sets, it says that the natural map $colim_{\Delta^n \to X} \Delta^n \to X$ is an isomorphism for $X$ any simplicial set. This basically says that if you take all the simplices in a simplicial set and glue them together, you get the original simplicial set back.
The geometric realization takes this as motivation. But now you want a topological space, so instead of gluing simplicial simplices together (i.e. the $\Delta^n$ for $n \geq 0$), you're now gluing their toplogical incarnations, which are the standard topological simplices, denoted $|\Delta^n|$ for $n \geq 0$. Thus the geometric realization is $colim_{\Delta^n \to X} |\Delta^n|$.


text:
Q: Height of the div is not resizing according to the content inside My div of class .list-holder in the header is not resizing according to the content in the div. If I increase the padding of list items, the content is overflowing outside the div.
I have imported bootstrap CDN

.list-holder {
    background-color: rgba(0,0,0,0.8);
    margin: 0px 40px;
    margin-top: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.list-holder > ul > li{
    display: inline;
    padding: 10px;
    border: solid 1px;
}

.list-holder > ul > li > a{
    display: inline;
    color: white;
    text-decoration: none;
}

.list-holder > ul{
    margin: 0px;
    padding: 0px;
}

Blogging

            <button >Get started</button>

                <input type="search" placeholder="Google Search ">

Total Views: 0

Total Users: 0

 Home

 Nation

 Sports

 Politics

 Entertainment

 Search

 Contact Us

also :
Plz anyone say what's my mistake......!

A: Your li elements should have display: inline-block instead of display: inline in order to trigger height modifications in the parent element.
If you want to use bootstrap, though, you could do something like this to achieve what you wanted (expand the snippet to see the centered menu items):

nav.navbar-dark.bg-dark {
  background-color: rgba(0,0,0,0.8)!important;
}
@media (min-width: 1200px) {
  h1.navbar-brand {
    position: absolute;
  }
  nav .form-inline {
    position: absolute;
    right: 15px;
  }
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

Blogging

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

Home(current)

Nation

Sports

Politics

Entertainment

Search

Contact Us

        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Google Search" aria-label="Google Search">
          <button class="btn btn-dark my-2 my-sm-0" type="submit">Get Started</button>
        </form>

Total Views: 0

Total Users: 0

A:

.list-holder {
    background-color: rgba(0,0,0,0.8);
    margin: 0px 40px;
    margin-top: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.list-holder > ul > li{
    display: inline-block;
    padding: 10px;
    border: solid 1px;
}

.list-holder > ul > li > a{
    display: inline;
    color: white;
    text-decoration: none;
}

.list-holder > ul{
    margin: 0px;
    padding: 0px;
}

Blogging

            <button >Get started</button>

                <input type="search" placeholder="Google Search ">

Total Views: 0

Total Users: 0

 Home

 Nation

 Sports

 Politics

 Entertainment

 Search

 Contact Us

You can use display: inline-block to .list-holder > ul > li instead of display: inline


text:
Q: Android Development. webview doesn't disappear ontouchevent This is my code
  public boolean onTouchEvent(MotionEvent event) {
    wv.setVisibility(View.GONE);
    return true; // Required for receiving subsequent events (ACTION_MOVE, ACTION_UP)
}

It doesn't do anything
I want the webview to disappear when the screen is touched. The webview is being used to host a ad.
My activity_main.xml code is:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.catching.apples.MainActivity"
tools:ignore="MergeRootFrame">

<WebView
android:id="@+id/activity_main_webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     />
<WebView
    android:id="@+id/webbanner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal|bottom" />

</FrameLayout>

A: In past, i've got problem with Visibility using FrameLayout, so i suggest you to switch to LinearLayout to solve this problem.
Changing your layout to:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.catching.apples.MainActivity"
    tools:ignore="MergeRootFrame">

    <WebView
        android:id="@+id/activity_main_webview"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <WebView
        android:id="@+id/webbanner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

Using wv.setVisibility(View.GONE);, now i'll work.
And using layout_height="0dip" and layout_weight="1", the activity_main_webview will fit all screen except by the webbanner.


text:
Q: Initialized repo on the wrong folder After selecting Initialize Repo on a particular folder and letting VSCode do its thing, I realized I had a number of items in the folder that I didn't want Repo'd. Rather than move those items out of the folder, however, what I want to do is create a new folder for the stuff I do want repo'd and initialize that.
How do I go about 'uninitializing' the current folder so that it isn't tracked anymore?

A: When you create a git repository, a hidden ".git" folder is created in the repository folder. If you want to "uninitialize" it, you just have to delete it.


text:
Q: Refactoring: Isn't it just a fancy word for clean up your code? Before Martin Fowler's book "Refactoring: Improving the Design of Existing Code" came out, we used to call major changes to code "rearchitecture" and minor changes "cleanup". IMO, refactoring techniques are all common sense / obvious things we've been doing forever.
Do you think refactoring was ever anything new? Perhaps just a way to trick management into allocating time for code cleanup?

A: It's just tidying code up.  Essentially, programmers (especially Martin Fowler) noticed that they tended to perform the same tasks each time they tidied up their code.  They defined and labelled the tidying methods and associated code problems and presto!  Refactoring was born.
It's the same with design patterns - people noticed that they tended to use the same approaches to particular problems over and over again.  They labelled and defined the approaches and now it seems that you're not a real programmer unless you only ever use the same dozen or so patterns in your code.
There's no magic to refactoring; it's just a new set of jargon to describe an old practice.

A: We do three separate things in our company, with allocated time for the three:

*

*Refactoring: consists in changing the code structure, thus keeping the behavior.

Example: splitting an ugly and unreadable 100 lines method which does four things into four reusable methods, 25 lines each.

*

*Cleanup: consists in doing minor modifications to make code more readable without modifying neither its behavior, nor its structure.

Example: removing commented code after ensuring that this code is not needed anymore.

*

*Enforcing StyleCop/FxCop rules: consists in checking if the code matches the default set of StyleCop or FxCop rules, and if not, modify it to match those rules.

Example: adding Culture.Invariant in string.Format (or another culture which is more appropriate).
So in my case, refactoring is something very different from cleanup. When doing cleanup, I don't have to run unit tests again: if the code worked before, it will work after cleanup. In other words, it's not because I removed an empty line or added a comment that the code will stop working. On the other hand, when I refactor complicated parts of an old code, I can do some mistakes, so I must run unit tests after refactoring.

A: Refactoring's older than the hills, so no, it's not anything new.
And refactoring's not cleaning up. Well, it can be, but it's not limited to cleaning up.
It's adjusting the architecture of your application (whether at large or small scales) while preserving behaviour.
That means that while some part of your application might have been perfectly clean and fine yesterday, today's new feature requires adjusting that part to accomodate the new feature.
You don't want to break existing functionality, so you adjust the structure of your application while preserving behaviour - which is refactoring.
This said no matter what changes are made to the code one should always run his tests... just in case.

A: Refactoring adds knowledge to your code.  If you know something is incorrectly named, you give it a better name.  If you know something can be done better, you change it into something better.
It is a lot of steps - small and big - that hopefully result in a better program.

A: I agree with "refactoring is a fancy word for clean up your code" but not with "just". People use fancy words for a reason: sometimes because they want to look clever, and sometimes because they're conveying a greater or more precise meaning, and IMHO refactoring (even if occasionally misused) is generally referring to the latter.
"Clean up" could mean anything from "reformatting a bit" to "rewriting large chunks".
"Refactoring" means specifically something like "small incremental changes to the code, designed to maintain the same functionality, while transforming it into a better design". And there's a body of best practice on the sort of things you do: some is ad-hoc, but there are general principles, like using unit tests, extracting part of functions into new functions or classes, etc, which people can and should learn.
You say "just trick management into allocating time for code clean up". But if saying "refactoring" correctly conveys the concept that a steady investment in clarity now will pay dividends in efficiency in the future, then that's not a "trick", that's clear and effective communication.

A: Refactoring is to code as Normalisation is to relational data. It's a process of abstracting concepts into cleaner, clearer and more efficient representations of their role in the application.

A: It depends how you understand term refactoring. For most of people this is a process of improving structure without changing behaviour. If you agree, then yes it was done long before this book came out. I know, because I was (among many other things) renaming classes, extracting classes and extracting methods before the book was written. I wasn't calling it refactoring, but in essence I was doing exactly the same thing.
For me personally refactoring is what people now call "automated code refactoring" ie: support for various refactoring techniques inside an IDE. This is a real improvement to what I was doing before (which indeed was very painfull). I can carry out a change in one class and not worry how this is going to affect the rest of the software. I think that Martin formalized refactoring techniquest up to the point where it could be represented as algorithm and thus implemented in various IDEs out there.
So if you understand refactoring as a process, then it is nothing new. If you see it as automation, then yes it is huge improvement. Try renaming few core classes (literally, not through refactoring options of your IDE) in a reasonably large project to see why :)

A: Refactoring is indeed code "cleanup", but also restructuring the code. In my team refactoring is usually the latter. When we have a "refactor" case we allocate time to restructure our code, e.g. to make it aligned with a new architecture, or information model, or to make it more efficient.
Code "cleanup" is something that we do continously without specially allocated time for it. For me "cleanup" is usually renaming, cleaning out comments, etc.

A: I'd say No.
There may be cleanup in the refactoring process but it is not the essence.
Cleanup comes with the assumption that the previous code is not clean. In reality, developers refactor their code even the original code is already clean.
DRY is a key drive behind refactoring.
When adding new codes to an existing code base, refactoring is done naturally due to DRY principle.
Just my 0.02

A: Cleaning your code is like tidying up your house, refactoring is like tearing down a wall and possibly putting it up somewhere else

A: When someone else cleans up your house, you can't find anything because the goal is getting things clean and out of the way. Refactoring would build and label rooms, closets, cabinets, shelves, bins, etc. It still holds most of the same stuff (you can still make a grilled cheese sandwich in the kitchen and eat it in the living room), but should make it easier to find and possibly have efficient places to put new things.

A: The term 'refactoring' is elegantly borrowed from algebra.  It means simplifying the terms to produce the same result.  Not only elegant, it was revolutionary -- it required a hard finite approach to your code, at a level that surprised many.  And so the term itself was significant and helpful.

A: "Refactoring" is really the same thing as "rearchitecture", but with a stronger connotation of "no functionality changes". It's also clearer in terms of the goal of re-architecture, which is often to "factor out" common code into reusable chunks.

A: The two overlap a bit at the edges, but to me it's the difference between cleaning the house and remodeling the house.  Cleanup, to me, does not imply structural changes, while refactoring does.


text:
Q: Database in Mysql does not show the result for a radiobutton in html and php I am trying to work on a contact form with PHP, HTML and MYSQL. Everything works except for the radiobuttons. When i select the button 'male' it doesnt show that in the database.
I tried to specify the radiobuttons with an ID, unfortunately that did not worked out for me. Could you guys help me with this? Thanks!
HTML

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact formulier</title>

<fieldset>
<legend>Contact Form</legend>
<form name="frmContact" method="post" action="contact.php">

Name
<input type="text" name="txtName" id="txtName">

    <input type="radio" name="gender" value="Male">Male

    <input type="radio" name="gender" value="Female">Female

Phone
<input type="text" name="txtPhone" id="txtPhone">

Message
<textarea name="txtMessage" id="txtMessage"></textarea>

<input type="submit" name="Submit" id="Submit" value="Submit">

</form>
</fieldset>

 ```

PHP
// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');

$con = mysqli_connect('localhost', 'root', '','db_connect');

// get the post records
$txtName = $_POST['txtName'];
$gender = $_POST['gender'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];

// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`Id`, `fldName`, 'gender', `fldPhone`, `fldMessage`) VALUES ('0', '$txtName', '$gender', '$txtPhone', '$txtMessage')";

// insert in database
$rs = mysqli_query($con, $sql);

if($rs)
{
    echo "Contact Records Inserted";
}else{
  echo "Contact records failed";
}

?> ```

A: Your should change the quotation mark from ' to `
// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`Id`, `fldName`, `gender`, `fldPhone`, `fldMessage`) VALUES ('0', '$txtName', '$gender', '$txtPhone', '$txtMessage')";

Or you can completely leave them:
// database insert SQL code
$sql = "INSERT INTO tbl_contact (Id, fldName, gender, fldPhone, fldMessage) VALUES ('0', '$txtName', '$gender', '$txtPhone', '$txtMessage')";


text:
Q: Winapi Shell_NotifyIcon - Duplicated icons in Notification Area Icons window I´m working on a C++ application that creates an icon in notification area, with a baloon tip. When user clicks the baloon, the icon is being removed using Shell_NotifyIcon(NIM_DELETE, &nid), just as MSDN instructs to do.
The problem is that the notification icon leaves the tray, but it remains in the Notification Area Icons window (that window which opens when you click the Customize option in windows 7/8´s tray). Then, if the user restart the program, the icon will be duplicated many times as the program can be restarted, even if the computer is being restarted.
I googled about and I found out that removig some registry keys, the cache can be cleaned, but explorer.exe needs to be restarted... but this is not an option I want to put in pratice, for many reasons.
My questions are:
- Have any of you guys seen this before?
- Is there some alternative to Shell_NotifyIcon (assuming the possibility that the usage of this being the problem, once I´m not too much experienced in Winapi);
- Is there any way to force "cache cleanup" in notification area window without restarting explorer.exe?
For those who can help, my gratitude in advance.

A: Indeed, IUserNotification2 worked great and the problem is solved.
I wrote a new notification class based on Notifu´s examples, using IUserNotification2, IQueryContinue and IUserNotificationCallback.
Thanks to all for helping.


text:
Q: "Top 20% of the people earn 80% of the money" ... this type of result using R Let me give you an example:
person | salary
----------------
1      | 30'000
2      | 10'000
3      | 15'000
4      | 25'000
5      | 80'000
6      | 56'000
...    | ...

The steps to take to get to this result would be to order the salaries and then create a new table giving the share of rows/people from start until the respective row and the share of the sum of the salaries from start until the respective row (of the total salaries).
Then one just has to take the row closest to 20% for the people and we know how much they earn.
This is a pretty standard question - but as I don't know how to refer to it verbally I cannot google it.
So I would appreciate if somebody could tell me what to "call this" and how to compute and plot this in R the most easiest - so no loops and stuff. My intuition tells me there are at least 5 packages and 10 functions addressing this scenario. Maybe something similar to summary() with fixed quantiles.
So let's assume the above table to be available as a data frame:
salaries <- data.frame(person = c(1,2,3,...), salary = c(30000,...))

A: Use the SLID income dataset from the car-package:
library(car)

dat <- SLID[!is.na(SLID$wage),]       # Remove missing values
dat$income <- dat$wage*40*50          # "translate" the wages to their full time annual earnings equivalent.
dat$id <- seq(1,nrow(dat))

# Create a data.frame with a person ID and their annual income:
keep <- data.frame(id = seq(1, nrow(dat)),
                   income = dat$income)
keep <- keep[order(keep$income, decreasing = TRUE),]  # Descending ordering according to income
keep$accum <- cumsum(keep$income)                     # Cumulative sum of the descending incomes
keep$pct <- keep$accum/sum(keep$income)*100           # % of the total income

keep$check <- keep$pct<80                      # Check where the % is smaller than 80%
threshold <- min(which(keep$check == FALSE))   # First line where % is larger than 80%
border <- threshold/nrow(keep)*100             # Check which percentile that was
border <- round(border, digits = 2)
paste0(border, "% of the people earn 80% of the income")

#[1] "62.41% of the people earn 80% of the income"

The classical 80-20 rule as we would expect it, would show "20% of the people earn 80% of the income". This rule does not apply here, as you can see..
The reversed argument:
# The 20% of the people earn X % of total income:

linenr <- ceiling(1/5*nrow(keep))
outcome2 <- round(keep$pct[linenr], digits = 2)
paste0(outcome2, "% of total income is earned by the top 20% of the people")

# [1] "36.07% of total income is earned by the top 20% of the people"

Note that the numbers presented here are not representative for the real world :)
Also, Wikipedia has some more information on the Pareto principle, which is also known as the 80-20 rule. It seems that this rule appears in multiple settings, such as business, economics and mathematics.


text:
Q: MySQL5.6 stuck on the process " attempting to start service " I got a community server version of MySQL5.6 for windows7 32 bit.
and also downloaded windows installer for the same windows version.
Everything was prepared correctly.
I saw on a blog giving me a step-by-step manual for installing MySQL 5.6 on winodws7 32bit.
I did the instruction accordingly and it always stops processing in the phrase of starting service. I completely don't know what the problem is.
I googled it for like three hours and got nothing relevant to this problem.

It never processes any further without any kind of alerts, no matter how much I wait.
Please help me out.
My OS
Windows7 Ultimate K 32bit, Service Pack1

A: Have you installed other version of MySQL before? I have experienced this case ,but I installed MySQL5.5 and uninstalled it. I solved it by clearing regedit and deleting the folder of MySQL in the directory(C:\ProgramData.This directory is hidden by default in Windows.),then reinstalled it.

A: TURN OFF WINDOWS FIREWALL COMPLETELY BEFORE INSTALLING

This was one of the only threads I could find on this issue and the current answers did not cut the mustard for me.
MySQL 5.6.21, both x86 and x64, did not want to get past "Starting Server" and would give me the "MySQL install taking longer than expected" message.
I tried all of the registry cleaner, folder deletions, etc to no avail.
I am running Windows 7 x64 and I finally decided to check the event viewer to find this:

0x80070422 turns out to be some unspecified firewall error and boom, it struck me like lightning.
I hope this post helps future visitors!

A: Follow this link http://tadeparti.com/pages/?page_id=808.
And do remember to delete everything under the C:\program files\mysql folder, including the odbc stuff if you have.