text:
Q: Failing initial response when updating test via Zephyr api I am having some issues regarding updating an execution status in a zephyr test cycle, this implementation has been present for a year and the failure has only just started occurring, when we run our set of selenium tests, the first test will fail to update the test execution status with the following error:
java.lang.AssertionError: 1 expectation failed.

Expected status code <200> but was <404>.
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:72)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:105)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:59)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:263)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:277)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:499)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:684)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.codehaus.groovy.runtime.callsite.PlainObjectMetaMethodSite.doInvoke(PlainObjectMetaMethodSite.java:43)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:193)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:61)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:185)
at io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:127)
at io.restassured.specification.ResponseSpecification$statusCode$0.callCurrent(Unknown Source)

After the first test has failed, all other tests successfully update the status, If I put the code into debug and step through the updateTestResult method then it is able to update the status, so it looks like a timing issue in my opinion, however I am not sure how I can handle that delay with our current implementation, Method is below:
public void updateTestResult(boolean isTestFailed) {
    String body;
    if (isTestFailed) {
        body = "{\n" +
                "    \"status\": \"2\"\n" +
                "}";
    } else {
        body = "{\n" +
                "    \"status\": \"1\"\n" +
                "}";
    }
    request = given()
            .auth()
            .preemptive()
            .basic(System.getenv("USER_NAME"), System.getenv("ZAPI_PASSWORD"))
            .header("Accept", "application/json")
            .header("Content-Type", "application/json")
            .body(body);
    response = request.when().put(readPropertiesFile("ZEPHYR_API_URL") + "/execution/" + executionId + "/execute");
    response.then().log().ifError().statusCode(200);
}

Any help would be really appreciated.


text:
Q: BC - no "\\n" at the end + start with zeros? This is a bc output, e.g.:
Input:
echo "scale=10; BLA-BLA-HERE-NOT-IMPORTANT" | bc

Output:
.3708446283953709207058828124021300754352578903651372655882743141882\
77124645102027246581819139527644919407424570060822470537797066353573\
96635.8038454068 days

Two Questions:

*

*can the output be rounded to something like "0.3708..."?

*can I remove the "\n"-s from the end?

I can't find any max width option in bc.

A: With the GNU implementation of bc, there is an environment variable you can set called BC_LINE_LENGTH that will either disable the backslash + newline feature or will extend it. Newer versions allow you to disable it with a value of 0 like this:
BC_LINE_LENGTH=0 bc <<<"2^4096"

Older versions don't have the "0 turn off" feature and require you to set the value to a large enough value so that it doesn't affect you:
BC_LINE_LENGTH=10000 bc <<<"2^4096"

Seems like this would be a good environment variable to set in your shell if you use bc a lot and don't like the line wrapping. If you're using bash, just place this in your .bashrc:
export BC_LINE_LENGTH=0

A: You can try something like this code:
echo "scale = 4;  3.5678/3" | bc | tr '\n' ' '

Setting scale for bc is supposed to do the rounding job. You can substitute the division part with your desired command. The output of bc is again piped to tr, which converts the newline (\n) to white space. For the above command I get the following output:
1.1892 user@localhost:~/codes$

A: $ OUT=$(bc <<< "2 ^ 256")
$ echo "$OUT"
11579208923731619542357098500868790785326998466564056403945758400791\
3129639936

$ OUT=${OUT//$'\\\n'/}
$ echo "$OUT"
115792089237316195423570985008687907853269984665640564039457584007913129639936

A: So maybe answer just for myself, but combination of everything would be
BC_LINE_LENGTH=10000 bc -l <<< "scale=200;1/3" | tr "\n" " "

For example calculation of energy consumption
BC_LINE_LENGTH=10000 bc -l <<< "scale=2;`cat /sys/class/power_supply/BAT1/energy_now`/1000000"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert this String to JSON object in Javascript, when the string has single quote within the double quote If the string contains only double quotes, it can be solved like below-
var str=`{"name":"javascript"}`;
var jsonObj=JSON.parse(str) //Works

And if string contains only single quotes , it can be solved like below-
var str = "{'result': ['def', 'abc', 'xyz']}";
str = str.replace(/'/g, '"');
var res = JSON.parse(str);
console.log(res.result);

But how do we convert the below string, where there's single quote inside the double quote-
var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} `

A: This doesn't look like a valid stringified JSON.
var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} `

error should be wrapped in double quotes instead.
var s=`{"error": "No such file or directory: '../FileSystem/3434-5433-124/'"} `

You can verify it using JSON.stringify
JSON.stringify({
  error: "No such file or directory: '../FileSystem/3434-5433-124/'"
})

Assuming that you're using a valid JSON. You can now escape the single quotes with a backslash.

var s = `{"error": "No such file or directory: '../FileSystem/3434-5433-124/'"}`
const parsed  = JSON.parse(s.replace(/\'/g, "\'"));
console.log(parsed)

A: If you know that the only issue is that the property names are single quoted rather than the JSON required double quotes you could use regex to replace the single quotes on property names with doubles.
var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} `
const regex = /(')(\S*)('):/g
s = s.replace(regex, '"$2":')
const workingJson = JSON.parse(s);

Should do the trick. This will replace single quotes with doubles for any part of your string that has the format of (single quote)(text)(single quote)(colon), this will most likely only be property names but keep in mind that if another part of your string follows this exact format it will also get it's single quotes replaced by doubles.


text:
Q: TTPhotoViewController thumbnails rotate but images don't I have PhotoTest1Controller very similiar to the one in Three20 samples. I implemented necessary shouldRotate methods in necessary places in UITabBarController and UINavController derived classes as well as the table that contains PhotoTest1Controller.
A funny thing is happening, when in thumbnail mode, the view rotates properly, but when showing a picture it does not respond to rotation. Moreover, If I rotate in thumbnail view and then switch to single image view in that rotation, I find that the image is properly rotated in the background. It only ignores rotation when it is the topmost view!
So, my understanding is that shouldRotate events are properly propagated, but for some reason single image view does not rotate when in top view, unlike the example code which is %98 equal to my code...

A: I found the answer to my own problem and answered it here: TTThumbView/TTPhotoView no autorotation
Briefly: I don't know why but TTScrollView deviceOrientationDidChange method in three20 codebase is commented out! If you uncomment it, it will work.
See the code here: http://github.com/facebook/three20/blob/master/src/TTScrollView.m


text:
Q: Android to WCF: Streaming multi part image and Json string Android to WCF: Streaming multi part image and Json string
I want to create a WCF-RESTful web service method,in which i need to upload an image(multipart-form data) along with some other information (in JSON format). This web service will be accessed by android and iPhone application to send Image and json information as
I want WCF Server Side and Android Code, Help me
I'm trying to upload an image and a text to a wcf service. I create a service to save upload images:
Rest Client Code
protected void Button2_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {

                MemoryStream mStream = new MemoryStream();

                Bitmap bmpPostedImage = new Bitmap(FileUpload1.PostedFile.InputStream);

                bmpPostedImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] imageArray = mStream.ToArray();
                mStream.Close();

                VehicleCheckListTransaction objAttachmentRequestDto = new VehicleCheckListTransaction();
                objAttachmentRequestDto.VehicleCheckListTransactionID = 0;
                objAttachmentRequestDto.VehicleCheckListID = 2;
                objAttachmentRequestDto.TTID = 10;
                objAttachmentRequestDto.UserID = 226;
                objAttachmentRequestDto.UserTypeID = 4;
                objAttachmentRequestDto.ValidTill = "215-05-10";
                objAttachmentRequestDto.CurrentDate = "215-07-22";
                objAttachmentRequestDto.CurrentStatus = "Yes";
                objAttachmentRequestDto.CreatedBy= 226;
                objAttachmentRequestDto.ModifiedBy = 226;
                objAttachmentRequestDto.CreatedDate = string.Empty;
                objAttachmentRequestDto.ModifiedDate = string.Empty;
                objAttachmentRequestDto.Notes = "Some Text";
                objAttachmentRequestDto.IsActive = true;
                objAttachmentRequestDto.FileName = "";
                objAttachmentRequestDto.FilePath = "";
                objAttachmentRequestDto.VerifiedBy = 226;

                var serializer = new DataContractJsonSerializer(typeof(VehicleCheckListTransaction));
                var ms = new MemoryStream();
                serializer.WriteObject(ms, objAttachmentRequestDto);
                ms.Position = 0;
                var reader = new StreamReader(ms);
                string requestBody = reader.ReadToEnd();

                var client = new RestClient();
                client.BaseUrl = new Uri("http://localhost:49188/WDS_SERVICE.svc/");
                var request = new RestRequest(Method.POST) { DateFormat = DataFormat.Json.ToString(), Resource = "vehiclechecklisttransaction/Add" };
                if (requestBody != null)
                    request.AddParameter("VehicleCheckListTransaction", requestBody);
                request.AddFile("file1", imageArray, "NEVER.jpg");
                var response = client.Execute(request);
            }
        }

WCF Service Code
public string UploadPhoto(Stream request)
        {
            //Read in our Stream into a string...
            StreamReader reader = new StreamReader(request);
            string JSONdata = reader.ReadToEnd();

            // ..then convert the string into a single "wsCustomer" record.
            JavaScriptSerializer jss = new JavaScriptSerializer();
            Checklist Checklist = jss.Deserialize<Checklist>(JSONdata);

            try
            {
                FileStream targetStream = null;
                Stream sourceStream = Checklist.fileContents;

                String guid = Guid.NewGuid().ToString();

                //get photofolder path
                string photofolderName = "Trip\\Android";
                string filename = guid + ".JPEG";
                string uriPath = "file:\\C:\\inetpub\\wwwroot\\WDS\\Media\\" + photofolderName + "\\" + filename;
                string photopath = new Uri(uriPath).LocalPath;

                using (targetStream = new FileStream(photopath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //read from the input stream in 6K chunks
                    //and save to output stream
                    const int bufferLen = 65000;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }

                db.Checklists.Add(Checklist);
                db.SaveChanges();
                return filename + "_" + Checklist.ChecklistID;
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }


text:
Q: Can I use std::vector::swap to modify a shared vector? I'm working on software where multiple threads read-access a single std::vector with a lot (and large) data.
I have some basic understanding of the complexities of multiple theads accessing a single object and things can be greatly simplified by using a mutex.
In my case, modifying an existing object is a lot more expensive that copying it. So I was thinking about creating a copy, modifing the copy (while not holding the mutex) and
then swapping it back into the shared object.
I cannot use C++11, so I don't have access to move operations, but it is my understanding that gcc uses a very efficient std::vector::swap() that is comparable with move operations (in terms of speed).
I was thinking about something like this:
pthread_mutex_t mtx;

class bigdata_t { ... };
std::vector<bigdata_t> shared_vec; // accessed by multiple threads

void modify_bigdata()
{
    pthread_mutex_lock(&mtx);
    std::vector<bigdata_t> tmp_vec = shared_vec; // create copy
    pthread_mutex_unlock(&mtx);

    /*
     * Here, apply expensive modifications to tmp_vec
     */

    pthread_mutex_lock(&mtx);
    shared_vec.swap(tmp_vec); // this is very fast and does not copy data
    pthread_mutex_unlock(&mtx);
}

modify_bigdata() is only called by a single thread, so this is basically a single writer/multiple reader approach.
It runs very fast, but swapping data back into the shared vector kind of feels like cheating.
My question is:
Is this approach correct and thread-safe ?

A: Assuming that you swap the whole vector, it is very dangerous if any reader thread has reference inside that vector as when swapping, it is very possible that the other vector get destroyed in which case any reference from reader threads can become invalide.
So every time your reader thread would access the vector, they would need a lock. So using swap won't help here. The only way it could works is that by ensuring that no reader are active by using some kind of multiple reader - single writer lock.
What might works for you is
std::vector<std::shared_ptr<bigdata_t>> shared_vec;

That way, you only need to properly synchronize the exchange of pointers and ensure that either:

*

*the size of the vector does not change once you have started reader threads or

*that you never keep iterator around and access to vector is properly synchronized.


text:
Q: How to restrict a user or a group of users to access an asset in fatwire How to restrict a user or a group of users to access an asset in fatwire
I wanted to obtain standard mvc functionality using fatwire.

A: You can add an attribute to the flexasset definition to establish wich users (groups much better) have access to the asset. In your template, before rendering, check if the user (group) have access and, if so, render the asset.

A: Do you mean how to restrict users/groups from accessing assets in Fatwire authoring screen? We can achieve this through multiple ways such as site as the secure scope and assign users/groups to the sites. Users can only see assets available in the logged in site.
If you need users to collaborate within the same site, you can create a one-step workflow and add all sites to the workflow and assign certain users/groups to the workflow.


text:
Q: Alinear pirámide de asteriscos Javascript Buenas noches y como siempre, gracias de antemano. Hice un ejercicio para escribir con asteriscos en forma piramidal (lo explico mejor en este fragmento de código )

function pyramid(numPisos) {
  for (let i = 0; i < numPisos; i++) {
    let piso = '';
    for (let j = 0; j < i + 1; j++) {
      piso = piso + '*';
    }
    console.log(piso)
  }
}

pyramid(5);

y lo siguiente que quiero hacer es que esta misma pirámide se alinee a la derecha, en vez de a la izquierda como está ahora. Sé que necesito otro bucle for* entre los dos existentes, pero tras probar más de 100 formas lo único que consigo es que la pirámide tenga en cada línea 5 espacios antes de escribir el asterisco.Es decir, solo consigo desplazarla hacia la derecha pero no cambio su alineación.
Por si doy lugar a muchas dudas, mi objetivo sería dejarla así:
    *
   **
  ***
 ****
*****

Muchas gracias.

A: Siguiendo tu ejemplo, puedes realizarlo como mencionas, agregando otro for.
El código quedaría de la siguiente manera:

    function pyramid(numPisos) {
      for (let i = 0; i < numPisos; i++) {
        let piso = '';
        for (let j = 1; j < numPisos - i; j++) {
          piso = piso + ' ';
        }

        for (let j = 0; j < i + 1; j++) {
          piso = piso + '*';
        }
        console.log(piso);
      }
    }

    pyramid(5);

A: ciertamente una de las soluciones es agregar un tercer bucle para determinar el número de espacios en blanco que deben existir para desplazar el asterisco a la derecha y por ende, conseguir que la pirámide esté alineada a la derecha, cabe mencionar que el resultado se verá bien siempre y cuando se imprima usando fuente monoespaciada (como la consola del navegador). Anexo el código con la solución a tu pregunta. Saludos

function pyramid(numPisos) {
  /* Espacios que se debe empujar el asterisco*/
  let spaces = numPisos - 1;

  /* Recorrer cada piso */
  for (let i = 0; i < numPisos; i++) {
    let piso = '';

    /* Agregar el número de espacios*/
    for (let j = 0; j < spaces; j++) {
      piso += ' ';
    }

    /* Agregar el número de asteriscos */
    for (let k = 0; k <= i; k++) {
      piso += '*';
    }

    /* Mostrar espacios y asteriscos por piso*/
    console.log(piso)

    /* El siguiente piso tendrá un espacio menos */
    spaces--;
  }
}

pyramid(5);

A: Puedes hacerlo con un for, un metodo de javascript que se encarga de repetir la cadena vacia con padStart luego concatenas la otra codena con la cantidad de *

function pyramid(numPisos) {

  for (let i = 1; i <= numPisos; i++) {
    let piso = ''.padStart(numPisos - i, " ").concat("".padStart(i, "*"))
    console.log(piso)
  }
}

pyramid(5);

cambiamos el orden de la cadena para generar el arbol, te invito a jugar con este metodo

function pyramid(numPisos) {

      for (let i = 1; i <= numPisos; i++) {
        let piso = ''.padStart(i, "*").concat("".padStart(numPisos - i, " "))
        console.log(piso)
      }
    }

    pyramid(5);

A: Un for() y repeat

function pyramid(numPisos) {
  for(let x = 1; x <= numPisos; x++){
    console.log(' '.repeat(6 - x) + '*'.repeat(x))
  }
}
pyramid(5);


text:
Q: PHP - Turn a timestamp (2012-07-12 20:26:00) Into two seperate variables that refelct the month and day values? I would like to separately strip the day and month values out of this  timestamp "2012-07-12 17:50:00".
So essentially I could have two variables like:
$month = 7
$day = 12

As I am not very proficient with php, specifically regex coding, I thought I would post this question to ask for advice as to how I would go about accomplishing something like this.
Any assistance, insight or input in this regard would be greatly appreciated. Thank you!
AS A NOTE: Futhermore, I would like to turn the two variables into an output like "12th July". This can be coded quite easily so I have not made this a part of the question but if there is a simple function that deals with this information would be much appreciated too!

A: As said in the comments, DateTime would be a good choice.
First, if your php config dosen't already set it up for you, set your default timezone by:
date_default_timezone_set('XXXX');

XXXX stand for a value out of the List of supported timezones
initialize your date by:
$DateTime = new DateTime();

depending on where you get the timestamp, lets assume you will create it out of PHP:
$timestamp = $DateTime->getTimestamp();

Now format the output
echo $month = $DateTime->format( 'm' );
echo $day = $DateTime->format( 'd' );

or to get you desired output:
echo $output = $DateTime->format( 'dS F' );

A: <?php
list($month,$day) = explode(':',date('n:j',strtotime('2012-07-12 17:50:00')),2);
echo 'Month: '.$month.'
'."\n";//Month: 7
echo 'Day: '.$day.'
'."\n";//Day: 12
?>

And...
<?php
echo date('jS F',strtotime('2012-07-12 17:50:00'));//Outputs: 12th July
?>

A: Assuming the timestamp is a string, something like this should work if you're looking for a regex solution...
<?php
$string = '2012-07-12 17:50:00';
preg_match_all('/\d{4}-(\d{2})-(\d{2})/', $string, $matches);
$month =$matches[1][0];
$day = $matches[2][0];
?>


text:
Q: php mysql infinite loop I have the following code which stays in a constant loop unless I comment *$conn->query($insert_statement.$values);*.  With that line commented I get exactly the correct printed output as it will finish the loop at the last insert statement.
for($count =0; $count < $rs->num_rows; $count++){
        $values = "";
        foreach($keys as $key){
            $values = $values . "'".$row->$key."', ";
        }
        $values = substr($values, 0, strlen($values)-2) . ");\n";
        echo $insert_statement.$values."\n";
        $conn->query($insert_statement.$values);
}

Here's the entire code.  I am trying to make a script the backs up a table.
<?

$date = getdate();

$date = $date['month']."_".$date['mday']."_".$date['year'];

$conn = new mysqli("localhost", "root", "ranger", "customers");

$conn->query("drop table if exists backup_$date");
$rs = $conn->query("DESCRIBE customers");

$create_statment = "create table backup_$date (";

$primary_key = "";
$keys = array();
$insert_statement = "insert into backup_$date (";

$count = 0;
while($row = $rs->fetch_object()) {
    if($count > 0){
        $keys[] =  "".$row->Field."";
        $insert_statement = $insert_statement . "`".$row->Field."` ,";
    }
    if($row->Null == "NO"){
        $create_statment = $create_statment . "`".$row->Field."` ".$row->Type." not null";
        if($row->Extra == "auto_increment"){
            $create_statment = $create_statment ." not null auto_increment, ";
        }else{
            $create_statment = $create_statment . ",";
        }
    }else{
        $create_statment = $create_statment . " `".$row->Field."` ".$row->Type.", ";
    }
    if($row->Key == 'PRI'){
        $primary_key = "primary key(".$row->Field.")";
    }
    $count++;
}
$create_statment = $create_statment . " $primary_key);";

$conn->query($create_statment);

$rs = $conn->query("select * from customers;");

$insert_statement = substr($insert_statement, 0, strlen($insert_statement)-1).") values (";
$row = $rs->fetch_object();
for($count =0; $count < $rs->num_rows; $count++){
        $values = "";
        foreach($keys as $key){
            $values = $values . "'".$row->$key."', ";
        }
        $values = substr($values, 0, strlen($values)-2) . ");\n";
        echo $insert_statement.$values."\n";
        $conn->query($insert_statement.$values);
}

?>

A: I create backup using INSERT ... SELECT. Maybe this helps you.


text:
Q: UA String failed,prompt Invalid Device type We set it "TPV_linux", but we found UA String failed.
We checked the underscore "" and found that it was half-width "" rather than full-size "_", so it should not fail.
We do not understand what caused this, can you help to check?

A: Underscore and some other characters are replaced in function Sanitize() when the User Agent string is created in UserAgentStringFactory::CreateUserAgentString().
Please, check file cobalt/network/user_agent_string_factory.cc for more details, but comments in the source code suggest that these chars are reserved:
struct SanitizeReplacements {
  const char* replace_chars;
  const char* replace_with;
} kSanitizeReplacements[] = {
  { ",", u8"\uFF0C" },  // fullwidth comma
  { "_", u8"\u2E0F" },  // paragraphos
  { "/", u8"\u2215" },  // division slash
  { "(", u8"\uFF08" },  // fullwidth left paren
  { ")", u8"\uFF09" },  // fullwidth right paren
};


text:
Q: Using CASE WHEN with an unknown number of categories Let's say I have a table like this
Col1  Col2

A     0.1

B     2.4

B     2.1

C     5.0

...   ...

and that I want to obtain this other table
ColA  ColB  ColC

0.1   0     0

0     2.4   0

0     2.1   0

0     0     5.0

...   ...   ...

To create one single column I can use a CASE WHEN as
SELECT CASE WHEN Col1 = 'A' THEN Col2 ELSE 0 END AS ColA FROM TABLE
But I don't know a priori how many different categories I have in Col1 and there can be many of them. How could I obtain this result with BigQuery?


text:
Q: COUNTIF cell description matches and within date range Hi I am after some help with a COUNTIF formula, I want to add 1 to cell
if the 3 criteria are met (see image) =COUNTIF(K4:K20,D2 AND L4:L20,C6 AND M4:M20,B7) i can get the 2 count from =COUNTIF(K4:K20,D2) but the formula does not work with the AND L4:L20,C6 AND M4:M20,B7

Any help would be great

A: for first, I'd split your B column in two columns FROM and TO. This helps countifs to evaluate if time is after ( >= ) FROM and before (<) TO.
If you are asking what should you write in your C7 formula, this could be something like (according to columns in my screenshot):
=COUNTIFS(G:G,$C$5,H:H,">="&A6,H:H,"<"&B6,F:F,$B$2)

so use ">=" & cell to evaluate if time if after FROM columns; and "<" & cell to evaluate if is before TO column.
I paste this screenshot of I'd solve this problem:
screeshot
and here you have a working example


text:
Q: "TypeError: undefined is not a function" when calling a function from the factory I'm trying to call a function defined in the factory via controller, but getting an error:

TypeError: undefined is not a function.

Could someone help please help me?
//service
angular.module('Blog').factory('postData', function($http) {
  var postData = {}
  postData.data.posts = [{
    title: 'first title',
    contents: 'first contents'
  }]
  postData.loadPosts = function() {
    postData.data.posts = $http.get('./posts.json')
      .success(function(data) {
        postData.data.posts = data;
      })
      .error(function() {
        console.error('Failed loading data');
      })
  }
  postData.createPost = function(newPost) {
    var data;
    if (newPost.newPostTitle === '' || newPost.newPostContents === '') {
      alert('Neither the Title nor the Body are allowed to be left blank.');
      return false;
    }
    data = {
      new_post: {
        title: newPost.newPostTitle,
        contents: newPost.newPostContents
      }
    };
    $http.post('./posts.json', data).success(function(data) {
      postData.data.posts.push(data);
      console.log('Successfully created post.');
    }).error(function() {
      console.error('Failed to create new post.');
    });
    return true;
  };

  console.log("initialized postdata");
  return postData;
})

//controller
var createPostCtrl = function($scope, $location, postData) {
  postData = postData;
  $scope.data = postData.data;
  postData.loadPosts();
  $scope.formData = {
    newPostTitle: '',
    newPostContents: ''
  };

  $scope.createPost = function() {
    // This one is throwing an error TypeError: undefined is not a function
    postData.createPost($scope.formData)
  };
};

A: module function need dependency as second argument. If no dependency you can write:
angular.module('Blog', [])


text:
Q: Best algebraic geometry textbook? (other than Hartshorne) I think (almost) everyone agrees that Hartshorne's Algebraic Geometry is still the best.
Then what might be the 2nd best?
It can be a book, preprint, online lecture note, webpage, etc.
One suggestion per answer please. Also, please include an explanation of why you like the book, or what makes it unique or useful.

A: If you know french, you might enjoy David Harari's course notes. These are the notes for a basic course in schemes and cohomology of sheaves. He combines the best parts of Hartshorne with the best parts of Liu's book. Hartshorne doesn't always do things in the nicest possible way, and the same is of course true for Liu.
I agree that Vakil's notes are great, since they also contain a lot of motivation, ideas and examples. But does anyone know where to get the files with this year's notes? I only found the notes of previous years on the web.

A: Also lots of things on jmilne.org

A: Biased by my personal taste maybe, I think, Harder's two-volume book(with the third one not completed yet) Lectures on Algebraic Geometry is wonderful. The author develops the algebraic side of our subject carefully and always strikes a good balance between abstract and concrete. If you can torlerate the English written by a German, perhaps some parts of Harder's are more appealing than those of Shafarevich and Hartshorne!

A: A friendly introduction to Arithmetic Algebraic Geometry is Lorenzini's book "An invitation to Arithmetic Geometry". Aimed at beginning graduate students, it treats Number Fields and Algebraic curves simultaneously.

A: Next to the classics, I enjoy Introduction to schemes by Ellingsrud-Ottem very much (available here).
The best part about this book is that many insightful examples are explicitly computed accompanied with nice, colorful pictures. E.g. already chapter 5 (just after introducing schemes!) spans 18 pages of examples about gluing (from $\mathbb{P}^n$ to hyperelliptic curves to Hirzebruch surfaces $\mathbb{F}_r$). Prof. Ottem himself has mentioned that writing out these examples are important to him, and it really shows!

A: Macdonald "Algebraic geometry: Introduction to schemes" (not only about noetherian schemes), Dieudonné's two booklets with focus on the motivation and history, the first chapter in Demazure, Gabriel "Groupes algebraique I", Mumford's "red book".
Mumford suggested in a letter to Grothendieck to publish a suitable edited selection of letters from Grothendieck to his friends, because the letters he received from him were "by far the most important things which explained your ideas and insights ... vivid and unencumbered by the customary style of formal french publications ... express(ing) succintly the essential ideas and motivations and often giv(ing) quite complete ideas about how to overcome the main technical problems ... a clear alternative (to the existing texts) for students who wish to gain access rapidly to the core of your ideas". (Found in the very beautifull 2nd collection - when I got it from the library I could not stop reading in it, which happens to me rarely with such collections, despite the associated saga)

A: The red book by Mumford is nice, better than Hartshorne in my opinion (which is nice as well).
At a far more abstract level, EGA's are excellent, proofs are well detailed but intuition is completly absent.
For a down to earth introduction, Milne's notes are nice (but they don't go to the scheme level, they give the taste of it).

A: Hodge, Pedoe, Methods of Algebraic Geometry.

A: Perhaps this is cliché, but I recommend EGA (links to full texts: I, II, III(1), III(2), IV(1), IV(2), IV(3), IV(4)).
I know it's a scary 1800 pages of French, but

*

*It's really easy French. I would describe myself as not knowing any French, but I can read EGA without too much trouble.

*It's extremely clear. The proofs are usually very short because the results are very well organized.

*It's the canonical reference for algebraic geometry. I assure you it is not 1800 pages of fluff.

I've found it quite rewarding to to familiarize myself with the contents of EGA. Many algebraic geometry students are able to say with confidence "that's one of the exercises in Hartshorne, chapter II, section 4." It's even more empowering to have that kind of command over a text like EGA, which covers much more material with fewer unnecessary hypotheses and with greater clarity. I've found this combined table of contents to be useful in this quest. [Edit: The combined table of contents unfortunately seems to be defunct. Here is a web version of Mark Haiman's EGA contents handout.]

A: Mukai's Introduction to Invariants and Moduli surely deserves to be on this list.

A: I'm a fan of The Geometry of Schemes by Eisenbud and Harris.  Its great for a conceptual introduction that won't turn people off as fast as Hartshorne.  However, it barely even mentions the concept of a module of a scheme, and I believe it ignores sheaf cohomology entirely.

A: Liu wrote a nice book, which is a bit more oriented to arithmetic geometry. (The last few chapters contain some material which is very pretty but unusual for a basic text, such as reduction of algebraic curves.)

A: I've found something extraordinary and of equally extraordinary pedigree online recently. I mentioned it briefly in response to R. Vakil's question about the best way to introduce schemes to students. But this question is really where it belongs and I hope word of it spreads far and wide from here.
Last fall at MIT, Michael Artin taught an introductory course in algebraic geometry that required only a year of basic algebra at the level of his textbook. The official text was William Fulton's Algebraic Curves, but Artin also wrote an extensive set of lecture notes and exercise sets. I found them quite wonderful and very much in the spirit of his classic textbook. (By the way, simply can't wait for the second edition.)
Not only has he posted these notes for download, he's asked anyone working through them to email him any errors found and suggestions for improvements. All the course materials can be found at the MIT webpage. I've also posted the link at MathOnline, of course.
I don't know if most of the hardcore algebraic geometers here would recommend these materials for a beginning course. But for any student not looking to specialize in AG, I can't think of a better source to begin with. That's just my opinion. But it certainly belongs as a possible response to this question. Then again, it may be too softball for the experts, particularly those of the Grothendieck school.
Here's keeping our fingers crossed that this is the beginning of the gestation of a full blown text on the subject by Artin.

A: Read Math Overflow.
Whereas it is actually not quite a textbook, it is becoming a very popular reference. In recent talks it was even used as the almost exclusively!
And indeed, there are a lot of high quality 'articles', and often you can find alternative approaches to a theory or a problem, which are more suitable for you. In addition, you can actually ask questions (a feature thoroughly missed in e.g. Hartshorne's book).

A: Shafarevich wrote a very basic introduction, it's used in undergraduate classes in algebraic geometry sometimes
Basic Algebraic Geometry 1: Varieties in Projective Space
also, for a more computational point of view
Ideals, Varieties, and Algorithms: An Introduction to Computational Algebraic Geometry and Commutative Algebra
And the followup by the same authors
Using Algebraic Geometry

A: Manin's lectures on algebraic geometry that were recently translated into English could be helpful too.

A: I think it's hard to say which one is the best, but for my own experience, I got into this area pretty much by reading most of this "3264 & all that" book, and completing almost all exercises (this is crucial!). It is said to be on intersection theory, but when I worked through it, I learned many other perspectives and came up with lots of concrete questions as well. I strongly recommend this book (again, the crucial point is doing exercises).
But of course I think it would be good to not just stick on one book. For example, Hartshorne definitely has a very quick and useful intro in cohomology, but for the part "higher direct images" I think 3264 is better. Also Beauville's surface book is of course good intro to surfaces, but for discussion of ruled surfaces, I think Hartshorne is actuallty better...

A: At a lower level then Hartshorne is the fantastic "Algebraic Curves" by Fulton. It's available on his website.

A: I think Algebraic Geometry is too broad a subject to choose only one book. Maybe if one is a beginner then a clear introductory book is enough or if algebraic geometry is not ones major field of study then a self-contained reference dealing with the important topics thoroughly is enough. But Algebraic Geometry nowadays has grown into such a deep and ample field of study that a graduate student has to focus heavily on one or two topics whereas at the same time must be able to use the fundamental results of other close subfields. Therefore I find the attempt to reduce his/her study to just one book (besides Hartshorne's) too hard and unpractical. That is why I have collected what in my humble opinion are the best books for each stage and topic of study, my personal choices for the best books are then:

*

*CLASSICAL:
Beltrametti-Carletti-Gallarati-Monti. "Lectures on Curves, Surfaces and Projective Varieties" which starts from the very beginning with a classical geometric style. Very complete (proves Riemann-Roch for curves in an easy language) and concrete in classic constructions needed to understand the reasons about why things are done the way they are in advanced purely algebraic books. There are very few books like this and they should be a must to start learning the subject. (Check out Dolgachev's review.)

*HALF-WAY/UNDERGRADUATE:
Shafarevich - "Basic Algebraic Geometry" vol. 1 and 2. They may be the most complete on foundations for varieties up to introducing schemes and complex geometry, so they are very useful before more abstract studies. But the problems are hard for many beginners. They do not prove Riemann-Roch (which is done classically without cohomology in the previous recommendation) so a modern more orthodox course would be Perrin's "Algebraic Geometry, An Introduction", which in fact introduce cohomology and prove RR.

*ADVANCED UNDERGRADUATE:
Holme - "A Royal Road to Algebraic Geometry". This new title is wonderful: it starts by introducing algebraic affine and projective curves and varieties and builds the theory up in the first half of the book as the perfect introduction to Hartshorne's chapter I. The second half then jumps into a categorical introduction to schemes, bits of cohomology and even glimpses of intersection theory.

*FREE ONLINE NOTES:
Gathmann - "Algebraic Geometry" (All versions are found here. The latest is of 2019.) Just amazing notes; short but very complete, dealing even with schemes and cohomology and proving Riemann-Roch and even hinting Hirzebruch-R-R. It is the best free course in my opinion, to get enough algebraic geometry background to understand the other more advanced and abstract titles. For an abstract algebraic approach, the nice, long notes by Ravi Vakil is found here. (A link to all versions; the latest is of 2017.)

*GRADUATE FOR ALGEBRISTS AND NUMBER THEORISTS:
Liu Qing - "Algebraic Geometry and Arithmetic Curves". It is a very complete book even introducing some needed commutative algebra and preparing the reader to learn arithmetic geometry like Mordell's conjecture, Faltings' or even Fermat-Wiles Theorem.

*GRADUATE FOR GEOMETERS:
Griffiths; Harris - "Principles of Algebraic Geometry". By far the best for a complex-geometry-oriented mind. Also useful coming from studies on several complex variables or differential geometry. It develops a lot of algebraic geometry without so much advanced commutative and homological algebra as the modern books tend to emphasize.

*BEST ON SCHEMES:
Görtz; Wedhorn - Algebraic Geometry I, Schemes with Examples and Exercises. Tons of stuff on schemes; more complete than Mumford's Red Book (For an online free alternative check Mumfords' Algebraic Geometry II unpublished notes on schemes.). It does a great job complementing Hartshorne's treatment of schemes, above all because of the more solvable exercises.

*UNDERGRADUATE ON ALGEBRAIC CURVES:
Fulton - "Algebraic Curves, an Introduction to Algebraic Geometry" which can be found here. It is a classic and although the flavor is clearly of typed concise notes, it is by far the shortest but thorough book on curves, which serves as a very nice introduction to the whole subject. It does everything that is needed to prove Riemann-Roch for curves and introduces many concepts useful to motivate more advanced courses.

*GRADUATE ON ALGEBRAIC CURVES:
Arbarello; Cornalba; Griffiths; Harris - "Geometry of Algebraic Curves" vol 1 and 2. This one is focused on the reader, therefore many results are stated to be worked out. So some people find it the best way to really master the subject. Besides, the vol. 2 has finally appeared making the two huge volumes a complete reference on the subject.

*INTRODUCTORY ON ALGEBRAIC SURFACES:
Beauville - "Complex Algebraic Surfaces". I have not found a quicker and simpler way to learn and clasify algebraic surfaces. The background needed is minimum compared to other titles.

*ADVANCED ON ALGEBRAIC SURFACES:
Badescu - "Algebraic Surfaces". Excellent complete and advanced reference for surfaces. Very well done and indispensable for those needing a companion, but above all an expansion, to Hartshorne's chapter.

*ON HODGE THEORY AND TOPOLOGY:
Voisin - Hodge Theory and Complex Algebraic Geometry vols. I and II. The first volume can serve almost as an introduction to complex geometry and the second to its topology. They are becoming more and more the standard reference on these topics, fitting nicely between abstract algebraic geometry and complex differential geometry.

*INTRODUCTORY ON MODULI AND INVARIANTS: Mukai - An Introduction to Invariants and Moduli. Excellent but extremely expensive hardcover book. When a cheaper paperback edition is released by Cambridge Press any serious student of algebraic geometry should own a copy since, again, it is one of those titles that help motivate and give conceptual insights needed to make any sense of abstract monographs like the next ones.

*ON MODULI SPACES AND DEFORMATIONS:
Hartshorne - "Deformation Theory". Just the perfect complement to Hartshorne's main book, since it did not deal with these matters, and other books approach the subject from a different point of view (e.g. geared to complex geometry or to physicists) than what a student of AG from Hartshorne's book may like to learn the subject.

*ON GEOMETRIC INVARIANT THEORY:
Mumford; Fogarty; Kirwan - "Geometric Invariant Theory". Simply put, it is still the best and most complete. Besides, Mumford himself developed the subject. Alternatives are more introductory lectures by Dolgachev.

*ON INTERSECTION THEORY:
Fulton - "Intersection Theory". It is the standard reference and is also cheap compared to others. It deals with all the material needed on intersections for a serious student going beyond Hartshorne's appendix; it is a good reference for the use of the language of characteristic classes in algebraic geometry, proving Hirzebruch-Riemann-Roch and Grothendieck-Riemann-Roch among many interesting results.

*ON SINGULARITIES:
Kollár - Lectures on Resolution of Singularities. Great exposition, useful contents and examples on topics one has to deal with sooner or later. As a fundamental complement check Hauser's wonderful paper on the Hironaka theorem.

*ON POSITIVITY:
Lazarsfeld - Positivity in Algebraic Geometry I: Classical Setting: Line Bundles and Linear Series and Positivity in Algebraic Geometry II: Positivity for Vector Bundles and Multiplier Ideals. Amazingly well written and unique on the topic, summarizing and bringing together lots of information, results, and many many examples.

*INTRODUCTORY ON HIGHER-DIMENSIONAL VARIETIES:
Debarre - "Higher Dimensional Algebraic Geometry". The main alternative to this title is the new book by Hacon/Kovács' "Classifiaction of Higher-dimensional Algebraic Varieties" which includes recent results on the classification problem and is intended as a graduate topics course.

*ADVANCED ON HIGHER-DIMENSIONAL VARIETIES:
Kollár; Mori - Birational Geometry of Algebraic Varieties. Considered as harder to learn from by some students, it has become the standard reference on birational geometry.

A: I've been teaching an introductory course in algebraic geometry this semester and I've been looking at many sources.  I've found that Milne's online book (jmilne.org) is excellent.  He gives quite a thorough treatment of the theory of varieties over an algebraic closed field.  The book is very complete and everything seems to be done "in the nicest way".

A: Kenji Ueno's three-volume "Algebraic Geometry" is well-written, clear, and has the perfect mix of text and diagrams. It's undoubtedly a real masterpiece- very user-friendly.

A: The book An Invitation to Algebraic Geometry by Karen Smith et al. is excellent "for the working or the aspiring mathematician who is unfamiliar with algebraic geometry but wishes to gain an appreciation of its foundations and its goals with a minimum of prerequisites," to quote from the product description at amazon.com.

A: Another nice introductory AG book that, I believe, was not mentioned here yet is Hassett.

A: I second Shafarevitch's two volumes on Basic Algebraic Geometry: the best overview of the subject I have ever read.
Another very nice book is Miranda's Algebraic Curves which manages to get a long way (Riemann-Roch etc) without doing sheaves and line bundles until the end.  Of course, by then, you are really wanting sheaves and line bundles!

A: I liked Mumford's "Algebraic geometry I: Complex projective varieties" a lot, and also Griffiths' "Introduction to algebraic curves". Now I think I am falling in love with "Griffiths & Harris". For the record, I hate Hartshorne's.

A: Computer Scientists, me included, seem to prefer Ideals, Varieties, and Algorithms
by David A. Cox, John B. Little, Don O'Shea (http://www.cs.amherst.edu/~dac/iva.html)

A: I've tried learning algebraic geometry several times. I asked around and was told to read Hartshorne. I started reading it several times and each time put it away. I realized that  I could work through the sections and solve some of the problems, but I gained absolutely no intuition for reading Hartshorne. Discussing this with other people, I found that it was a common occurrence for students to read Hartshorne and afterwards have no idea how to do algebraic geometry. (I imagine this was the motivation for asking this question.)
After more poking around, I discovered Mumford's "Red book of Varieties and Schemes". While Mumford doesn't do cohomology, he motivates the definitions of schemes and and many of there basic properties while providing the reader with geometric intuition. This book isn't easy to read and you have to work out a lot, but the rewards are great. Another great feature of this book is that Mumford bought the rights to the book back from Springer and the book is available for free online.
Another book was supposed to be written that built on the "Red book" including cohomology. After many years, I think this is near completion; see Algebraic Geometry 2. Whlile many of the above books are excellent, it's a surprise that these books aren't the standard.

A: Joe Harris's book Algebraic Geometry might be a good warm-up to Hartshorne.

A: I'm starting to like this book, by Görtz and Wedhorn. (and hoping in volume II soon...)
Similarly to Qing Liu's wonderful book, it seems to me to be a good compromise between Hartshorne and EGA.

A: I enjoyed Griffiths-Harris a lot.

A: I believe the issue of "which book is best" is extremely sensitive to the path along which one is moving into the subject.  If your background is in differential geometry, complex analysis, etc, then Huybrechts' Complex Geometry is a good bridge between those vantage points and a more algebraic geometric landscape.  Obviously I'm taking liberties with the question, as I wouldn't advertise Huybrechts' book as an algebraic geometry text in the strict sense.  However, I think it can, for certain people, help to ease the transition into one.  It's also very well written, in my opinion.  (I should also emphasize that I'm not saying this is the only purpose of the book: its content is extremely valuable for other reasons, with material on vector bundles, SUSY, deformations of complex structures, etc.)
As for dedicated algebraic geometry texts other than Hartshorne, I also vote for Ravi Vakil's notes.  They're excellent.

A: Miles Reid's Undergraduate Algebraic Geometry is an excellent topical (meaning it does not intend to cover any substantial part of the whole subject) introduction.  In particular, it's the only undergraduate textbook that isn't commutative algebra with a few pictures thrown in.

A: Also Eisenbud.
Every algebraic geometer needs to know at least some commutative algebra. And this is
a very good introductory textbook, which teaches commutative algebra rigorously but at the same time provides a good geometric explanation.

A: I think the best "textbook" is Ravi Vakil's notes:
http://math.stanford.edu/~vakil/0708-216/
http://math.stanford.edu/~vakil/0910-216/

A: I recently completed a book on algebraic geometry. The PDF file may be freely downloaded:
Introduction to Algebraic Geometry
It is also available in paperback:Amazon listing

A: About Hartshorne and Griffiths, I think a comparison between the two texts is misleading.
The first is a introduction to the  "Grothendieck yoga" where geometrical classical ideas are "immersed" in the larger but abstract mathematical world of schemes.
But also if the complex differential manifold style of Griffiths is "more concrete" is very different from the "Algebraic Geometry" idea, also if it is a deep study of it.
As a categorist I love Grothendieck, but I find Grothendieck's work fantastic in itself (like a music), also if I never understand anything about Geometry while studying or reading EGA or some SGA.
For understanding what is "Algebraic Geometry" I had to read this
Beltrametti-Carletti-Gallarati-Monti Bragadin, Letture su curve, superficie e varietà proiettive speciali, Boringhieri
Beltrametti-Carletti-Gallarati-Monti Bragadin, Lezioni di geometria analitica e proiettiva, Boringhieri
(sorry, these are in Italian)

A: The word "best" is relative. If you have a strong background in commutative algebra and have had considerable exposure to algebraic geometry I would say Hartshorne would suit you. But for an introductory graduate text, I don't think so. We're using Fulton. Organization and exposition is okay, and the discussion is not as "hardcore" as that of Hartshorne. I'm surprised it didn't show up from those of you who posted here.


text:
Q: Using angular directive within md-virtual-repeat I'm trying to implement Angular Material's Virtual Repeat with a custom directive for the list items, and I'm having issues binding scope attrs to the directive.
Here's what I have:
HTML
<md-virtual-repeat-container id="vertical-container">

    <foo bar="item"></foo>

</md-virtual-repeat-container>

JS
myApp.directive("foo", function(){
    return {
      restrict: "E",
      scope: {
        bar: "="
      },
      template: "{{baz}}",
      link: function(scope){
        scope.baz = "new " + scope.bar;
      }
    }

Issue
The items in the virtual scrolling section seem to be there, but their value is showing as new undefined, when I'm expecting them to be new 1, new 2, and so on.
The strange thing is that some items do appear to show their values properly (namely, new 11, new 12, and sometimes new 13). Also, the issue gets solved if instead I replace my directive's template to "{{bar}}" which deems the directive's link function unnecessary. This leads me to think the problem is with the timing of the linking (would be my best guess).
Here's a link to the corresponding CodePen snippet for more clarification.
Any ideas?

A: Finally solved it - CodePen
JS
  .directive("foo", function(){
    return {
      restrict: "E",
      scope: {
        bar: "="
      },
      template: "{{test()}}",
      link: function(scope){
        scope.test = function () {
          if (angular.isDefined(scope.bar)) {
            return "new " + scope.bar;
          }
        }
      }
    }


text:
Q: Create new thread in for loop inside public void method() I have a class that ping IP addresses. To start ping I have public vod run() method to start pinging. Problem is that I want ping more IP addresses at same time (for each IP address I need new Thread). So how can I create new Thread inside for loop. Here is code of my ping class:
public void run()
    {
    if (dbConnection.ConnectToDB())
    {
        for (;GateWayKey<=GateWayKeyStop;GateWayKey++)
        {
            if(stop || this.isInterrupted()){
                return;
            }
            ip="192.168."+GateWayKey+".1";
            InetAddress address;
            try {
                address = InetAddress.getByName(ip);
                try {

                    if (address.isReachable(PingTime))
                    {

                        //System.out.println("Pronaden GateWay: "+ip)
                    //  labele.IP
                        sql="INSERT INTO `iptables` (`IP` , `COMPUTER_NAME` , `GATEWAY_KEY`) VALUES ('"+ip+"', '"+address.getHostName().toString()+"', '"+GateWayKey+"');";

                        framedocs.WriteMonitorData (ip, address.getHostName().toString(),"2000","DA",dbConnection.WriteToDB(sql));
                        for (;SubNetKey<=SubNetKeyStop;SubNetKey++)
                        {
                            if(stop || this.isInterrupted()){
                            return;
                            }
                            InetAddress addressIps = InetAddress.getByName("192.168."+GateWayKey+"."+SubNetKey);
                            System.out.println("Provjeravam IP: "+addressIps);
                            if (addressIps.isReachable(PingTime))
                            {
                                ip="192.168."+GateWayKey+"."+SubNetKey;
                                System.out.println("Pronaden IP: "+ip);
                                sql="INSERT INTO `iptables` (`IP` , `COMPUTER_NAME` , `GATEWAY_KEY`) VALUES ('"+ip+"', '"+addressIps.getHostName().toString()+"', '"+GateWayKey+"');";
                                framedocs.WriteMonitorData (ip, address.getHostName().toString(),"2000","DA",dbConnection.WriteToDB(sql));
                            }
                            else
                            {
                                framedocs.WriteMonitorData (addressIps.toString(), "N/A","2000","NE","N/A");
                            }

                        }
                    }
                    else
                    {
                            framedocs.WriteMonitorData (ip, "N/A","2000","NE","N/A");
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    framedocs.WriteMonitorData (ip, "N/A","2000",e.getMessage(),"N/A");
                }
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                ;
                framedocs.WriteMonitorData (ip, "N/A","2000",e.getMessage(),"N/A");
            }
        }

    }
    else
    {
        framedocs.WriteMonitorData ("MySQL error", "N/A","N/A","N/A","N/A");
    }

}

A: A general way to do these kinds of tasks is, first, create a class to hold the results you want to get from each thread:
final class PingResult {
    public String ip;
    public String hostname;
    //... other things you want go here
}

Then create a callable that does the actual work
class PingTask extends Callable<PingResult>{
    private final String gateWayKey, subNetKey;
    //... other parameters you need go here
    public Ping( String gwKey, String snKey /*+ others? */ ){
        // This is just a way to pass parameters to your pinging function
        this.gateWayKey = gwKey;
        this.subNetKey = snKey;
        // ...
    }

    public PingResult call(){

        // Do actual pinging work here

        if ( /* Success */ )
        {
            PingResult result = new PingResult();
            result.ip= /*Fill these in*/;
            result.hostname = /* ... */;
            return result;
        }
        // Otherwise we failed, I'm using null as a failure sentinel
        // (you can come up with something better)
        return null;
    }
}

Then in your calling code, set up a thread pool, cue up the requests, and then process the results.
// Might need to tweak the # for best performance
final int NUM_THREADS = Runtime.getRuntime.availableProcesses();
ExecutorService exec = Executors.newFixedThreadPool( NUM_THREADS );

List<Future<PingResult>> results = new ArrayList<PingResult>();

for(/* ... */){
    results.add( exec.submit( new PingTask( gateway, subnet ) ) );
}

for( Future<PingResult> future : results ){
    PingResult result = future.get();

    // Process the result here (this is where you insert into the DB)
}

exec.shutdown(); // VERY IMPORTANT. If you don't do this the JVM will never stop.

A: create a new class inside your main class and do your operations in that inner class
every-time you need to create a new thread just initiate a new instance of that inner class and call its methods created for this purpose
If you find this answer not useful check my other answer on multi-threading.


text:
Q: Inserting large BLOB into Oracle database Oracle's documentation has a sample on how to insert large BLOBs, in Java. Is it possible to do the same in C#?

A: Yes, set your parameter up like so:
var param = cmd.Parameters.Add("blobInParam", OracleDbType.Blob);
param.Direction = ParameterDirection.Input;

// Assign Byte Array to Oracle Parameter
param.Value = blobData;

A: A answer with a stream:
string path = @"D:\testfile.txt";
System.IO.FileStream myStream = new System.IO.FileStream(@path, FileMode.Open);

BinaryReader binaryReader = new BinaryReader(myStream);
byte[] data = binaryReader.ReadBytes((int)myStream.Length); //read the stream into byte

String sql =  "INSERT INTO testblob (testid, testblob) VALUES (100, :blobtodb)";

OracleCommand cmd = new OracleCommand();
cmd.CommandText = sql; // Set the sql-command
cmd.Connection = con; //con is an OracleConnection, create it before

OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.Blob); //Add the parameter for the blobcolumn
param.Direction = ParameterDirection.Input;

param.Value = data; //Asign the Byte Array to the parameter
cmd.ExecuteNonQuery(); //You are done!

This should work with every stream ;)

For Files with (over) 1TB:
WARNING: Use the OPs Solution for big files, as it is really hard to have 1TB in Memory ;)
Honestly I don't know, I can't try it here with such a big file. However BLOBs are specified by Oracle with: Maximum size: (4 GB - 1) * DB_BLOCK_SIZE initialization parameter (8 TB to 128 TB). So from database-side it should work.
But you MAYBE need to take care about the Connection Timeout and the Connection Lifetime, as it will take a long time to transfer such a big file over the network (I guess, I don't know your setup).


text:
Q: Angular resolve Rxjs map and subscribe multiple APIs Application need to fetch the jwt token first and then using token, collect portal information. This code is written in resolver.
This code make an error exception :

Type 'Subscription' is not assignable to type 'Observable'

When Observable<any> is removed, resolve data is not available in component and it initiates components before resolve completes
@Injectable()
export class PortalLoadingResolverService implements Resolve<any> {
    constructor(
      private authService:AuthService,
      private emiDataService:EmiDataService,
    ) { }

    resolve():Observable<any> {
      return this.authService.getJwtToken()
      .map(res => res.json())
      .subscribe(JwtToken => {
        debugger;
        localStorage.setItem('id_token',JwtToken.token);
        return this.emiDataService.getBasicLoadingDatas();
      });
    }
}

A: Your method isn't returning Observable here, that is what Typescript is yelling. Because once you applied subscribe method over Observable it return Subscription of observable. You could easily return a Observable by chaining Observable with switchMap operator.
resolve():Observable<any> {
  return this.authService.getJwtToken()
  .map(res => res.json())
  .switchMap(JwtToken => {
    localStorage.setItem('id_token',JwtToken.token);
    return this.emiDataService.getBasicLoadingDatas();
  });
}


text:
Q: VB-New to VB Excel I am trying to get a couple columns to change within my sheet based on the following code, however I keep receiving an error code.
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 12 Then
        Application.EnableEvents = False
        Cells(Target.Row, 13).Value = Date + Time
        Application.EnableEvents = True
    End If
    If Target.Column = 13 Then
        Application.EnableEvents = False
        Cells(Target.Row, 14).Value = Date + Time
        Application.EnableEvents = True
    End If
End Sub

A: taking a wild stab but I assume you want to format it as below
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 12 Then
    Application.EnableEvents = False
    Cells(Target.Row, 13).Value = Format(DateTime.Now, "mm/dd/yyyy")
    Application.EnableEvents = True
    End If
    If Target.Column = 13 Then
    Application.EnableEvents = False
    Cells(Target.Row, 14).Value = Format(DateTime.Now, "hh:mm:ss")
    Application.EnableEvents = True
    End If
End Sub


text:
Q: Using command line to activate Switch Control To activate Switch Control in Settings, I click the checkbox located in Accessibility -> Switch Control -> Enable Switch Control (at least in Catalina). If I want a program to open Switch Control and automate that process, I have to navigate through the System Preferences app (which I could do with AppleScript). It would be nice if there were a command I could run in the terminal to directly open the Switch Control Panel application. I couldn't find one in my research.
What I tried:
I followed the instructions in this answer. If it had worked as I wanted it to, I could have changed the "Switch Control" setting by editing its corresponding .plist file (sudo defaults write). When I tried this approach with the example provided in the answer (changing "Display Login Window as:" from "List of users" to "Name and password") it worked well. It didn't work when I tested it by changing the "Enable Switch Control" setting.
Following the instructions, I made a copy of the preferences folder and the enclosed plist setting files:
$ sudo cp -r /Library/Preferences before

After changing the Switch Control setting and exiting System Preferences, I made a new copy:
$ sudo cp -r /Library/Preferences after

Next, to see which files changed, I tried:
$ sudo diff -ur before after

which doesn't return any "Binary files differ" messages.
I then tried to use the Activity Monitor to find out what programs run when "Enable Switch Control" is on. I found a running application named Assistive Control (AssistiveControl in Activity Monitor).
I ran $ ps aux and I found this under the COMMAND column:
/System/Library/Input Methods/Assistive Control.app/Contents/MacOS/Assistive Control launchd -s

When I try running the command with Switch Control off in System Preferences, it doesn't do anything. When I try the command when Switch Control is on, I get this error:
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
How can I use the command line to activate Switch Control?
It would be great if someone could help me out or give me suggestions.

A: Here is a way from the command line in, e.g., Terminal to turn on Switch Control using a shell script using AppleScript with UI Scripting to programmatically click the Enable Switch Control checkbox in: System Preferences > Accessibility > Switch Control
The example AppleScript code, shown below, was tested in Script Editor and as an executable shell script in Terminal under macOS Catalina with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.

*

*1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
Note that the coding in this shell script assumes that Switch Control has once previously been turned on manually so as to answer the initial System Preferences is trying to unlock Accessibility preferences dialog box where you have entered your User Name and Password then clicked the Unlock button.
After setting up the shell script, and addressing settings mentioned above1, it will then be as simple as typing, e.g., esc in, e.g., Terminal to open Switch Control.
It Terminal, type the following compound command and then press enter:
f="esc"; touch "$f"; open -e "$f"; chmod +x "$f"

Copy and paste the example AppleScript code, shown below, into the opened esc document, (named for [E]nable [S]witch [C]ontrol), then save it and close the document.
You should then move the esc executable shell script to a directory that is listed within the PATH passed to the shell. I have mine in /usr/local/bin/.

Example AppleScript code:
#!/usr/bin/osascript

--  # Check to see if System Preferences is
--  # running and if yes, then close it.
--  #
--  # This is done so the script will not fail
--  # if it is running and a modal sheet is
--  # showing, hence the use of 'killall'
--  # as 'quit' fails when done so, if it is.
--  #
--  # This is also done to allow default behaviors
--  # to be predictable from a clean occurrence.

if running of application "System Preferences" then
    try
        tell application "System Preferences" to quit
    on error
        do shell script "killall 'System Preferences'"
    end try
    delay 0.1
end if

--  # Make sure System Preferences is not running before
--  # opening it again. Otherwise there can be an issue
--  # when trying to reopen it while it's actually closing.

repeat while running of application "System Preferences" is true
    delay 0.1
end repeat

--  # Open System Preferences to the Accessibility pane.

tell application "System Preferences" to ¬
    reveal pane id "com.apple.preference.universalaccess"

--  # Use System Events to achieve the goal.

tell application "System Events"
    tell window 1 of application process "System Preferences"

        --  # Wait for target pane to be available.
        --  # The target in this case has a checkbox.

        my waitForUIelement(checkbox 1)

        --  # Ascertain the target row to select.

        set rowSwitchControl to the first row of ¬
            table 1 of scroll area 1 whose value of ¬
            static text 1 of UI element 1 is ¬
            "Switch Control"

        --  # Select the target row.

        select rowSwitchControl

        --  # Wait for target checkbox to be available.

        my waitForUIelement(checkbox 1 of tab group 1 of group 1)

        --  # Click the Enable Switch Control checkbox.

        click checkbox 1 of tab group 1 of group 1

    end tell
end tell

delay 0.02

quit application "System Preferences"

--  ## Handler(s) ##

on waitForUIelement(uiElement)
    tell application "System Events"
        tell window 1 of application process ¬
            "System Preferences"
            set i to 0
            repeat until exists uiElement
                delay 0.1
                set i to i + 1
                if i ≥ 30 then return
            end repeat
        end tell
    end tell
end waitForUIelement

Notes:
The example AppleScript code  will click the target checkbox to enable Switch Control, however, as coded it does not show the UI when System Preferences is opened to do so. As a result, it will not uncheck the checkbox to disable Switch Control. That will need to be done my manually closing Switch Control.
The example AppleScript code can be modified to uncheck the checkbox to disable Switch Control, however, this will necessitate showing the UI of System Preferences. If you need it to do both and you do not mind seeing System Preferences flash on the screen for a second or two, then use the example AppleScript code show below these notes.
That said, regardless, one will see the Dock Tile bounce once in the Dock when the shell script is run and this cannot be avoided.
While this can achieve the goal of enabling Switch Control from the command line, nonetheless, UI Scripting scripting can be kludgy and prone to failure as the hierarchical UI element structure changes with updates to the OS or applications involved.  In other words, what works in, e.g., macOS Catalina may need to be tweaked for use in, e.g., macOS Big Sur.

Update to toggle the state of the Enable Switch Control checkbox.
Example AppleScript code:
#!/usr/bin/osascript

--  # Check to see if System Preferences is
--  # running and if yes, then close it.
--  #
--  # This is done so the script will not fail
--  # if it is running and a modal sheet is
--  # showing, hence the use of 'killall'
--  # as 'quit' fails when done so, if it is.
--  #
--  # This is also done to allow default behaviors
--  # to be predictable from a clean occurrence.

if running of application "System Preferences" then
    try
        tell application "System Preferences" to quit
    on error
        do shell script "killall 'System Preferences'"
    end try
    delay 0.1
end if

--  # Make sure System Preferences is not running before
--  # opening it again. Otherwise there can be an issue
--  # when trying to reopen it while it's actually closing.

repeat while running of application "System Preferences" is true
    delay 0.1
end repeat

--  # Open System Preferences to the Accessibility pane.

tell application "System Preferences" to ¬
    reveal pane id "com.apple.preference.universalaccess"

tell application "System Preferences" to activate

--  # Use System Events to achive the goal.

tell application "System Events"
    tell window 1 of application process "System Preferences"

        --  # Wait for target pane to be available.
        --  # The target in this case has a checkbox.

        my waitForUIelement(checkbox 1)

        --  # Ascertain the target row to select.

        set rowSwitchControl to the first row of ¬
            table 1 of scroll area 1 whose value of ¬
            static text 1 of UI element 1 is ¬
            "Switch Control"

        --  # Select the target row.

        select rowSwitchControl

        --  # Wait for target checkbox to be available.

        my waitForUIelement(checkbox 1 of tab group 1 of group 1)

        --  # Check to see if the Enable Switch Control
        --  # checkbox is checked, and if it is, then
        --  # uncheck it. Otherwise check it.

        if the value of checkbox 1 of tab group 1 of group 1 is 1 then

            --  # The Enable Switch Control checkbox is checked.
            --  # Click the Enable Switch Control checkbox.

            click checkbox 1 of tab group 1 of group 1

            --  # Wait for OK button to be available.

            my waitForUIelement(button 1 of sheet 1)

            --  # Click the OK button..

            click button "OK" of sheet 1

        else
            --  # The Enable Switch Control checkbox is not checked.
            --  # Click the Enable Switch Control checkbox.

            click checkbox 1 of tab group 1 of group 1
        end if

    end tell
end tell

delay 0.02

quit application "System Preferences"

--  ## Handler(s) ##

on waitForUIelement(uiElement)
    tell application "System Events"
        tell window 1 of application process ¬
            "System Preferences"
            set i to 0
            repeat until exists uiElement
                delay 0.1
                set i to i + 1
                if i ≥ 30 then return
            end repeat
        end tell
    end tell
end waitForUIelement

Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

A: Are you sure that the Accessibility prefs are stored in /Library, and not ~/Library (the user library)?
When I want to discover a plist key, I usually make the change in System Preferences, then sort the user Preferences folder by Modification Date. That narrows the list down to a few files, which hopefully are named usefully.
Testing with Switch control, I notice that a few relevant plists get changed:
com.apple.universalaccess.plist
com.apple.Accessibility.plist
com.apple.HIToolbox.plist
com.apple.AssistiveControl.switch.plist

However, I'm not sure what exactly gets changed, and it may be more than one thing.


text:
Q: Find the start and end of a word in a string using index of I have 2 strings. I ut each charcter into a list using a foreach loop. I then use a for loop to go through each character in the 2 lists to see if there is a difference. Once I find a difference between the strings I want to find the start and end of that word that has changed eg. String1 is different to String2 I want the output to be "String1 String2 is the first second string". I plan on finding the start and end of the changed word using indexOf and at the moment it's not finding the position of the index.
  static void Main(string[] args)
    {

        const string a = "String1 is the first string";
        const string b = "String2 is the second string";
        List<String> listString1 = new List<string>();
        List<String> listString2 = new List<string>();
        foreach (var item in a)
        {
            listString1.Add(item.ToString());
        }

        foreach (var item in b)
        {
            listString2.Add(item.ToString());
        }
        for (int i = 0; i < a.Length; i++)
        {
            var or = listString1[i];
            var ed = listString2[i];

            int nextSpace = or.IndexOf(' ', index);
            int previousSpace = or.LastIndexOf(' ', index);
            if (or!=ed)

            {

                Console.WriteLine();
            }
        }

    }

A: Honestly, I am confused about what you're trying to achieve.  But maybe I am on the right path with what I am providing.
static void Main(string[] args)
{
    string firstString = "I am the first string";
    string secondString = "I am the second string";

    char delimiter = Convert.ToChar(" ");

    if (firstString.Equals(secondString))
    {
        Console.WriteLine("Both strings are equal");
        Console.ReadLine();
    }
    else
    {
        var firstStringList = firstString.Split(delimiter).ToList();

        // ["I", "am", "the", "first", "string"]

        var secondStringList = secondString.Split(delimiter).ToList();

        // ["I", "am", "the", "second", "string"]

        foreach (var word in firstStringList)
        {
            if (secondStringList.IndexOf(word) == -1)
            {
                var indexOfWord = firstStringList.IndexOf(word); // 3
                secondStringList.Insert(indexOfWord, word); // Insert the word that was not found at position 3 inside secondStringList
                // ["I", "am", "the", "first", "second", "string"]
                // [ 0,    1,    2,      3,        4,         5  ]
                Console.WriteLine(string.Join(" ", secondStringList));
                // Join the secondStringList to make 1 string separated by the space character
                Console.ReadLine();
            }
        }

    }
}

This code will split the first string & second string into lists of strings containing the words that make up the strings.. then will loop through the first string list and compare each word within that list to the words in the second string list.. once it finds the word in the first string that does not exist in the second string.. it will print that word.
Again, not sure of the goal of this, but let me know based on what I posted what needs to be tailored.

A: Basic happy-path solution..
string newString = "";

string[] as1 = "String1 is the first string".Split(new char[] { ' ' });
string[] as2 = "String2 is the second string".Split(new char[] { ' ' });

for (int ndx = 0; ndx < as1.Length; ndx++)
{
    newString += (as1[ndx] == as2[ndx]) ? as1[ndx] : as1[ndx] + ' ' + as2[ndx];
    newString += ' ';
}

You need bounds checking on the arrays at least. But I'm not going to do all your homework for you :)


text:
Q: Repair OGG files that have been extracted without a header I have recently used a tool called FSBextractor to extract audio from a videogame.  The program warns me that the files do not have headers and will not be playable.  Upon extraction, the files are indeed not playable (using MPC-HC).
Is it possible to repair these files?  How unique is an Ogg Vorbis header?  Is it possible to extract a header from another file and insert it into the broken files?

A: Recently I recorded a stream using:
mplayer -dumpstream  "https://radio.tildeverse.org/radio/8000/radio.ogg" -dumpfile "/home/adamd/temp/StreamDump.ogg"

When completed it was playable with occasional skips and errors. Errors were Error parsing the packet header.. Progress indication and the ability to move to specific locations in the playback did NOT work.
Fixed by running: ffmpeg -i StreamDump.ogg SD.ogg
Perhaps it will work for you.


text:
Q: How can I embed an entire GitHub Gist dynamically on a page? I have some text that includes URLs to GitHub Gists. I'd like to look for those URLs and put the Gist inline in the content client-side. Some things I've tried:
A direct lookup to GitHub's OEmbed API.
For https://gist.github.com/733951, this means I do a JSON-P lookup to
https://github.com/api/oembed?format=json&url=https%3A%2F%2Fgist.github.com%2F733951,
extract the html property of the object, and add adding that to my page. The problem
   here is that GitHub's OEmbed API only returns the first three lines of the Gist.
Using the jQuery-embedly plugin.
Calling
jQuery('a.something').embedly({allowscripts: true})

works, but Embedly strips formatting from the Gist. Wrapping it in a <pre> tag doesn't help because there are no line-breaks.
Using GitHub's .js version of the gist.
https://gist.github.com/733951.js uses document.write, so I don't have any control over where in the page when I require it dynamically. (If I could write it into the HTML source it would show up in the right place, but this is all being done client-side.)

A: I've been inspired by client side gist embedding and built a script.js hack library just for that (I also use it to remove the embedded link style and use my own style that fits better on my page) ...
It's more generic than just embedding gists and pasties - actually I'm using it to dynamically load some third-party widgets / google maps / twitter posts) ...
https://github.com/kares/script.js
Here's the embedding example :
https://github.com/kares/script.js/blob/master/examples/gistsAndPasties.html
UPDATE: gist's API since then supports JSONP, jQuery sample:
var printGist = function(gist) {
    console.log(gist.repo, ' (' + gist.description + ') :');
    console.log(gist.div);
};
$.ajax({
    url: 'https://gist.github.com/1641153.json',
    dataType: 'jsonp', success: printGist
});

A: I just started a project called UrlSpoiler (on github).  It will help you embed gists dynamically. It's hosted on Heroku on the free/shared platform so you can play with it, but I'd recommend copying the code you need into your own app for production use.


text:
Q: windows tkinter install python 3.7.4 installed PYTHON 3.7.4 from the python.org website. Working on a windows 10 machine. everywhere it says tkinter should be part of it but it seems like it's not. I need help installing it.

A: This is the official documentation for the standard library Tkinter created by the folks at Python Software Foundation :
Tkinter
This will definitely help you install, import and get started with Tkinter on your Windows system.
For importing errors while trying to use Tkinter, please note :
The root of the problem is that the Tkinter module is named Tkinter (capital "T") in python 2.x, and tkinter (lowercase "t") in python 3.x.
To make your code work in both Python 2 and 3 you can do something like this:
try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *

But since you've already mentioned that you're on Python 3.7.4, this import statement will suffice :
import tkinter as tk

A: Tkinter is built in with every Python installation.
I don't know if you typed the command wrong, but this is the proper way.
import Tkinter as tk

Note: There is a Capital T at the beginning of Tkinter.
In Python 3 for you,
import tkinter as tk

Note: You might accidentally deleted it in the folder of python so you could just download python again.

A: Below from https://pypi.org/project/PySimpleGUI/:
Python 3.7
If you must run 3.7, try 3.7.2. It does work with PySimpleGUI with no known issues.
PySimpleGUI with Python 3.7.3 and 3.7.4+. tkinter is having issues with all the newer releases. Things like Table colors stopped working entirely. It's unclear if there's been a change that makes the tkinter API no longer working which means they are not backwards compatible. That would be a real shame. If so, more work needs to be done in PySimpleGUI

A: Can you import tkinter by import tkinter?


text:
Q: Does using only 2 phases (400V) in a 3 phase transformer affect anything? I just witnessed a 3 phase control transformer in the mcc that steps down 400V to 230V connected only with 2 phases on the 3 400V terminals, and on the other side (secondary) are your live and neutral wires.
Does only using 2 of 3 wires affect the transformer or secondary circuit in any way?
Any information would be appreciated

A:
Does only using 2 of 3 wires affect the transformer or secondary
  circuit in any way?

Due to the nature of magnetization currents that flow, the centre common part of a 3-ph transformer core may have very little magnetic flux and hence can be made quite small without worries about core saturation. If you remove one of the three phase voltages, the flux in the centre-limb is no longer zero and has a value that is significantly higher than the individual fluxes. This could easily saturate that centre-limb and cause over-heating.

Picture taken from here. Other types/constructions of 3-ph transformers may not be affected.


text:
Q: What is the true sys.all_objects? I am working with SQL Server 2008 R2 and SQL Server 2016.
I have bunch of User-Defined Data Types but they dont show in sys.all_objects. What is the true catalog view which can return all user-defined objects?
Thanks

A: Types are not objects that would show up in the objects table. You can use the types table:
select *
from sys.types
WHERE is_user_defined = 1

or you can use this bigger query from the MS docs to return all your objects, types, and schema collections:
SELECT 'OBJECT' AS entity_type
    ,USER_NAME(OBJECTPROPERTY(object_id, 'OwnerId')) AS owner_name
    ,name
FROM sys.objects
UNION
SELECT 'TYPE' AS entity_type
    ,USER_NAME(TYPEPROPERTY(SCHEMA_NAME(schema_id) + '.' + name, 'OwnerId')) AS owner_name
    ,name
FROM sys.types
UNION
SELECT 'XML SCHEMA COLLECTION' AS entity_type
    ,COALESCE(USER_NAME(xsc.principal_id),USER_NAME(s.principal_id)) AS owner_name
    ,xsc.name
FROM sys.xml_schema_collections AS xsc JOIN sys.schemas AS s
    ON s.schema_id = xsc.schema_id

GO


text:
Q: Merging two objects while keeping matching keys I'm trying to merge two javascript objets which, both have same similear key, but diffrent values.
I want them to keep the diffrent keys and but place themn together in the matching parent object.
For example:
const obj1 = {
   "title" : {
     "en-US" : "Some title"
   },
   "text": {
     "en-US": "Some text"
   }
 }
 const obj2 = {
   "title" : {
     "de-DE" : "Some diffrent title"
   },
   "text": {
     "de-DE": "Some diffrent text"
   }
 }

Desired Result:
{
    "title" : {
      "en-US" : "Some title",
      "de-DE" : "Some diffrent title"
    },
    "text": {
      "en-US": "Some text"
      "de-DE": "Some diffrent text"
    }
  }

What I tried:
Object.assign and the ES6 variant gave me this:
const mergedObj = {...obj1, ...obj2}

console.log(mergedObj);
    {
        "title" : {
          "de-DE" : "Some diffrent title"
        },
        "text": {
          "de-DE": "Some diffrent text"
        }
      }

A: You can get the keys of one of your objects, and map that to a new object, which merges the values for that key from both objects into one. You can then using Object.assign() to merge your array of mapped objects into a single resulting object like so:

const obj1 = { "title" : { "en-US" : "Some title" }, "text": { "en-US": "Some text" } }
const obj2 = { "title" : { "de-DE" : "Some diffrent title" }, "text": { "de-DE": "Some diffrent text" } }

const merge_objs = (o1, o2) =>
  Object.assign({}, ...Object.keys(o1).map(k => ({[k]: {...o1[k], ...o2[k]}})));

console.log(merge_objs(obj1, obj2));

A: you can do it like this:

const obj1 = {
   "title" : {
     "en-US" : "Some title"
   },
   "text": {
     "en-US": "Some text"
   }
 }
 const obj2 = {
   "title" : {
     "de-DE" : "Some diffrent title"
   },
   "text": {
     "de-DE": "Some diffrent text"
   }
 }

    function mergeObject(obj1,obj2){
       let c={};
       Object.keys(obj1).map((k)=>{
           let v={...obj1[k],...obj2[k]};
            c[k]=v;
        })
        return c;
      }

console.log(mergeObject(obj1,obj2));


text:
Q: Compactness implies Continuity? I am stuck on this question (probably there are many counterexamples, but I can't find any).
"Suppose $f:\mathbb{R}\mapsto\mathbb{R}$ that preserves compactness (i.e, for every $K \subseteq R$, then $f(K)$ is compact). Is $f$ continuous?"
thanks!

A: Floor function should be another example.
The image of each compact (bounded) set is a finite discrete set and therefore compact.

A: $f(x) = 1$ if $x$ is rational, otherwise $f(x)=0.$ So $f(K)$ is either one or two points.


text:
Q: Sharepoint search query to only show Site Pages (or a new Wiki library) I've got a new SharePoint Teams site that I'll be building out as a knowledge repository. We'll be creating articles in the "Site Pages" area, though happy to use a new Wiki Page Library if that makes it easier.
I'm trying to amend the Search Query used in the "All" vertical, so that it shows only results from the Site Pages. To test this, I've created a word document in the documents section and named it "Apples WORD.docx" and a Wiki page called "Apples WIKI". When I search for "Apples", I should only see "Apples WIKI" in my results.
I can't seem to figure out the query required to achieve this.
Thanks in advance.

A: So I've got this working now.
First I renamed an existing managed property by doing the following.
Go to the Site Settings, then Under the 'Site Collection Administration' go to "Search Schema".
Find an available RefinableStringXX managed property; edit it and give it an Alias. Add a mapping to "ContentTypeID".
Back out to the Site Settings then under 'Web Designer Galleries' click on "Site content types".
Find "Wiki Pages" and click on it to find the Content Type ID (which was 0x010108).
Back out to the Site Settings then under 'Microsoft Search', click on "Configure Search Settings".
Click on Verticals, then double click on the vertical that you want to edit. Click the Edit button at the bottom of the page.
Click on 'Query' and enter the text "ContentTypeID:0x010108*"
Save the vertical.
By editing the "All" vertical, the default 'current site' search from the site's homepage now only shows Wiki Page articles.

A: Maybe you could try adding the search vertical to the search navigation web part to set up a search page for displaying Site Pages.
Reference:Change settings for the Search Navigation Web Part


text:
Q: template call inside ngView not support angular directive stackoverflow My question involves how to use AngularJS directives in the template called inside ngView in an AngularJS application.
Define :
The application is single-page, so it loads an index.html that contains a div element(template url) in the DOM with the ng-view attribute.
Main Page(index.html) :

    <title>Angular App</title>

Page 1
Page 2
Page 3

app.js :
angular.module('App', [])

.controller('AppCtrl', function($rootScope, appLoading) {
    $rootScope.topScope = $rootScope;
    $rootScope.$on('$routeChangeStart', function() {
      appLoading.loading();
    });
  })

.config(function($routeProvider) {
    $routeProvider.when('/page1', {
      controller : 'Page1Ctrl',
      templateUrl : 'page1.html'
    })
    .when('/page2', {
      controller : 'Page2Ctrl',
      templateUrl : 'page2.html'
    })
    .when('/page3', {
      controller : 'Page3Ctrl',
      templateUrl : 'page3.html'
    })
    .otherwise({
      redirectTo: '/home'
    });
  })

page1.html :

<form class="login-profile" method="post" action="" name="editfrm">
<input type="text" name="email" value="" id="txtemail" data-ng-model="email" required>
<input type="password" name="password" value="" id="txtpassword" data-ng-model="password" required>
<input type="button" value="Save" name="submit">
</form>

Problem :
Template Url called inside the ngView not supported any AngularJS deirective.
data-ng-model="email" & data-ng-model="password" not working when called in the ngView on click the link Page 1
Any help will be appreciated. Thanks

A: Without seeing code for your Page1Ctrl it's hard to tell but it seems like you are trying to share data between controllers using $rootScope, no?
Well, just don't. Use either $routeParams or a service for that purpose. For example:
// app controller
.controller('AppCtrl', function(User) {
  User.set({email:'email', password:'password'}); // set user
})

// page 1 controller
.controller('Page1Ctrl', function($scope, User) {
  $scope.user = User.get(); // get user
})

// user service
.service('User', function() {
  var user = null;
  return {
    get: function() {
      return user;
    },
    set: function(val) {
      user = val;
    }
  };
});

and related HTML
<input type="text"
       name="email"
       data-ng-model="user.email"
       required>
<input type="password"
       name="password"
       data-ng-model="user.password"
       required>

A: When you click on Page 1, it loads Page1Ctrl and page1.html. Are you sure you are not able to access $scope.email and $scope.password in Page1Ctrl.
It should be accessible, if not then try to create a model object as follows:
$scope.LoginProfile = {
       email: '',
       password: ''
}

and use this LoginProfile object in your page1.html like this LoginProfile.email and LoginProfile.password.
PS: Try to interpolate on html so you can view values, (e.g. LoginProfile: {{LoginProfile}})


text:
Q: Find by unique key in xsd? Im using xsd:unique in an xsd generated code.  How do I get an item by the unique key?
I just need the Rows.Find method, but for unique keys in addition to the primary key.

A: Assuming you're talking about the output of XSD.EXE, it pays no attention to xsd:unique.


text:
Q: What power adapter do I need to charge a 7.2V 4000mAh battery? I made a Ni-CD 7.2V 4000mAh battery. What power adapter do I need to charge it?
How many volts and how many amperes should the adapter output?
Each battery cell is 1.2 volts.
I have a 9V 500mA power adapter.Is this adapter suitable for charging my battery and how long it will take?The adapter will automatically detect if the battery is full to stop charging it?

A: You made the battery, shouldn't you be telling us what we need in order to charge it?
Typically I would say you need a 400mA constant current with a voltage of 1.41V * number of cells. You would then charge it for 16 hours with some sort of timer. At that rate it would be fairly safe regardless of discharge level, but you still don't want to leave it charging for longer than the 16 hours.
If you wanted to charge it faster (and you know what the maximum rate of your battery is) you would need to monitor the voltage and/or temperature. But I think this is probably beyond the scope of your question.
In regards to your edit:
9V and 500mA are both slightly too high. The main concern is the 9V, since you should be using 8.5V. The 500mA isn't too much higher, but you would need to reduce the charge time.
Now if you use that to charge your battery, it will charge. But the over voltage will be damaging it. You could probably solve this problem with a low loss diode.
I'm not clear if what you're using is a purpose built battery charger or just a random power pack? In either case I'm going to say it probably wont stop charging, since it seems like it would expect a different battery if it's outputting 9V and wouldn't be calibrated correctly to switch off for yours when it's charged.

A: Depends.
If you want to charge it slowly, as stated in @hekete's answer, charge at a rate of C/10 (means 4000mA/10=400mA) for 16 hours and the charger's output voltage should be 1.4V per cell, which equals to (7.2V/1.2V) x 1.4V = 8.4VDC. But with this method, you need a mechanism (i.e. MCU, timer, etc.) to stop charging so that it does not past 16 hours.
If you want faster charging, C/3 for 5 hours or C/5 for 8 hours (with the same charging voltage) can be acceptable. But please note that you need to check battery voltage and temperature as well. Also, to ensure any problems not to occur, you need to discharge the battery down to at least 1V per cell then start charging.

A: Back in the days when people used NiCd batteries, you could buy off-the-shelf chargers that would charge them.  I still have a 7.2V "racing pack" charger specifically designed for such a job.
A 9V adaptor would over-charge the pack, quickly damaging either the adaptor or the battery.  You would need to limit the current to no more than 400mA (C/10).  Without knowing the specification of the adaptor, it's hard to tell how sophisticated that current limiter would need to be.  NiCd cells can be trickle charged at rates of up to C/10 for long periods safely.
NiCd batteries are largely obsolete now, as:

*

*NiMH ones have a larger capacity.

*Cadmium is toxic.


text:
Q: Как задать тип для аргумента функции из динамически сформированного массива? Есть класс
class Constants {
  static LocaleCodes = {
    English: {
      code: 'en',
      value: 'English',
    },
    Russian: {
      code: 'ru',
      value: 'Русский',
    },
    Chinese: {
      code: 'ch',
      value: '中国人',
    },
  };

  static Locales = Object.keys(I18nConstants.LocaleCodes).map(
    (locale) => I18nConstants.LocaleCodes[locale].code
  );
}

Хочу создать функцию которая будет принимать, в качестве аргумента, только набор элементов из массива Constants.Locales
Прочитал что можно сделать вот так:
  static Locales = Object.keys(I18nConstants.LocaleCodes).map(
    (locale) => I18nConstants.LocaleCodes[locale].code
  ) as const;

и в самой функции написать
someFoo(lang: typeof Constants.Locales[number]) {
....
}

Такой способ действительно работает, если массив статический, но как указать тип из динамически сформированного массива, не представляю.
Может быть есть какой-то способ, чтобы указать тип из объекта LocaleCodes?
Что-то вроде:
someFoo(lang: typeof Constants.LocaleCodes[key]['code']) {
....
}