text:
Q: Nan results when concatenating dataframes of different indices I have 3 dataframes I would like to concatenate  maintaining the index of df1.
df1:
       sq/ft

R     0.026715
A    -0.016556
P     0.007440
V     0.009841

 df2:
       ml/sq

0     0.032394
1     0.065046
2     0.009021
3     0.041041

df3:
       mlsq/rt
0     0.000871
1    -0.000148
2     0.000484
3     0.026715

The desired output would be something like this:
       sq/ft         ml/sq     mlsq/rt

R     0.026715     0.032394   0.000871
A    -0.016556     0.065046  -0.000148
P     0.007440     0.009021   0.000484
V     0.009841     0.041041   0.026715

This is what I have tried following pandas doc:
http://pandas.pydata.org/pandas-docs/stable/merging.html#set-logic-on-the-other-axes
print(pd.concat([df2,df1,df3], axis=1, join_axes=[df1.index]))

The 3 of them are df and my current output is
      ml/sq         sq/ft

R      NaN       0.026715
A      NaN      -0.016556
P      NaN       0.007440
V      NaN       0.009841

df3 it isn't even returned as an output.

A: I think you need align indexes - simpliest is set indexes in df2.index and df3.index by df1.index:
df2.index = df1.index
df3.index = df1.index
print(pd.concat([df2,df1,df3], axis=1))


text:
Q: Recent decline in health contributed to his death I am lost for a word to replace "recent" if the event (death) happend few years ago - "Recent decline in health contributed to his death". May be I have to use "decline in his health immediately before his death contributed to it" - too wordy.. Any suggestions?

A: I would simply go with one of the following, depending on the actual situation:

A gradual decline in his health led to his death.
  A slow decline in his health led to his death.
A sudden decline in his health led to his death.
  A rapid decline in his health led to his death.

Depending on how quickly it came on, you can make some good assumptions about how long prior to his death his health started to fail.
As you had wanted to use recent relative to the event, it sounds like either sudden or rapid would fit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Biopython error - The system cannot find the file specified I have encountered an error which I am not able to resolve.
I am trying to perform the easiest set of commands that will perform a tBLASTn algorithm,
looking for a sequence (sequence specified as a "pytanie.fasta" file) in a database (also specified as file -> cucumber.fasta). The result will be saved in the "wynik.txt" file.
The code looks as following:
from Bio.Blast. Applications import NcbitblastnCommandline
database = r"\Biopython\cucumber.fasta"
qr = r"\Biopython\pytanie.fasta"
output = r"\Biopython\wynik.txt"
e = raw_input("Enter e-value: ")
tblastn_cline = NcbitblastnCommandline(cmd='blastn', db=database, query=qr, out=output, evalue=e, outfmt=7)

print tblastn_cline

stdout, stderr = tblastn_cline()

And the error I get:
 File "C:\Users\IBM_ADMIN\Desktop\PYTHON\Workspace\Biopython\blast.py", line 20, in <module>
stdout, stderr = tblastn_cline()
File "C:\Python27\lib\site-packages\Bio\Application\__init__.py", line 435, in __call__
shell=(sys.platform!="win32"))
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

I am using:

*

*Eclipse SDK Version: 3.7.1

*Python version 2.7

*OS: 64 bit Windows 7

I have tried this also on 32-bit Windows XP and it produces the same error.
Biopython package should work fine since it went through the tests suggested by biopython website. I have also tried other formats of the path where the files are located, but it did not work. My friend uses the same code on Ubuntu and it works fine.
Does anybody know how to fix this error?

A: What are the paths of the files?
The path r"\Biopython\cucumber.fasta", for example, is an absolute path on the current drive (because it starts with a backslash and no drive letter), which I think in your case is r"C:\Biopython\cucumber.fasta". Is that correct?


text:
Q: String to String Array Android project On developing an Android project I have got stacked in position
I don't want to describe because it is simple.
String str = "Physics,Chemistry,Biology"

This is my String and three queries are divided by comma.
One of my method returns string like this.
So I want to make it to a string array.
This will like that dividing comma based.
String[] strArr = {"Physics", "Chemistry", "Biology"};

A: there is a method in String class that can help you convert it,
but you should give this method the regex , in your case regex is ","
you can use this method to convert it:
   public String[] convertToArray(String str, String regex){
    return str.split(regex);
   }

   String[] str = convertToArray(str, ",");

A: String[] strArr = str.split(",");


text:
Q: function not working on remote server the function is for checking if an url is pointing to a valid image by checking the meta info in the head section of the given file.
the echo in the below code gives me the correct wrapper data but on my remote server it echoes "ArrayResource id #11"  How this is possible?
local:PHP Version 5.3.4
remote server: PHP Version 5.2.9
 function isImage($url)
      {
         $params = array('http' => array(
                      'method' => 'HEAD'
                   ));
         $ctx = stream_context_create($params);
         $fp = @fopen($url, 'rb', false, $ctx);
         if (!$fp)
            return false;  // Problem with url

        $meta = stream_get_meta_data($fp);
        if ($meta === false)
        {
            fclose($fp);
            return false;  // Problem reading data from url
        }

        $wrapper_data = $meta["wrapper_data"];
        if(is_array($wrapper_data)){
          foreach(array_keys($wrapper_data) as $hh){
            echo substr($wrapper_data[$hh], 0, 19);//////////////ECHO////////////////////////
              if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19
              {
                fclose($fp);
                return true;
              }
          }
        }

        fclose($fp);
        return false;
      }

EDIT: I adapted the function so it checks if 'Content-Type: image' is somewhere in the header of the file. this works cross server...
function isImage($url)
  {
     $params = array('http' => array(
                  'method' => 'HEAD'
               ));
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     if (!$fp)
        return false;  // Problem with url

    $meta = get_headers($url);

    if ($meta === false)
    {
        fclose($fp);
        return false;  // Problem reading data from url
    }
    foreach ($meta as $key => $value) {
        $pos = strpos($value, 'Content-Type: image');
            if($pos!==false){
             fclose($fp);
             return true;
            }
    }

    fclose($fp);
    return false;
  }

A: Refer to this. stream_get_meta_data can return values in several datatypes. On your remote server it is returning an array.


text:
Q: Load 2 svg files in snap.svg with a onclick function At the moment i am loading up 1 SVG File with snap.svg and i manipulate it a little bit.
But now I want to open up another SVG File when i click on a rectangle in my already loaded SVG file. Is that possible if yes how?
Tried some different onclick stuff but it never worked
As showed down below in the code this is how i wana load up the SVG file btw. the other svg file that is already loaded up should disapear and only the svg file that gets loaded with the onclick function should be there to see
myelement.onclick(function() {
Snap.load("2ndsvg.svg");
});

Hope you can help me thanks


text:
Q: SQL Function for returning recursive value I'm trying to create a function for returning a recursive value but I getting a syntax error.
CREATE FUNCTION getObs
(
    @obs int
)
RETURNS
WITH ret2 AS(
    SELECT *
    FROM OBS
    WHERE OBS_Id = @obs
    UNION ALL
    SELECT t.*
    FROM OBS as t INNER JOIN
        ret2 r ON t.OBS_Id = r.UnitId
    )
SELECT *
FROM ret2 r
WHERE unity_id = 7

A: RETURNS specifying return type of the function, after that you have to define function body, like this:
CREATE FUNCTION getObs
(
    @obs int
)
RETURNS table -- <-- returns table so it's a table function
as
return  -- <- here's actual return
(
    WITH ret2 AS(
        SELECT *
        FROM OBS
        WHERE OBS_Id = @obs
        UNION ALL
        SELECT t.*
        FROM OBS as t INNER JOIN
            ret2 r ON t.OBS_Id = r.UnitId

        )
    SELECT *
    FROM ret2 r
    WHERE unity_id = 7
)

here's an example - sql fiddle demo

A: Your RETURNS part of the statement does not specify what it will return.


text:
Q: Correct mvn version for dispatch.databinder.net The last version of the library dispatch.databinder.net is 0.9.5, according to the website.
What is the correct mvn dependency?
<dependency>
  <groupId>net.databinder.dispatch</groupId>
  <artifactId>core_2.10</artifactId>
  <version>0.9.1</version>
</dependency>

or
<dependency>
  <groupId>net.databinder.dispatch</groupId>
  <artifactId>dispatch-core_2.10</artifactId>
  <version>0.9.5</version>
</dependency>

or something else?
and how to find out this in general?

A: Since the website says
libraryDependencies += "net.databinder.dispatch" %% "dispatch-core" % "0.9.5"

The corresponding maven notation for Scala 2.10.x should be:
<dependency>
  <groupId>net.databinder.dispatch</groupId>
  <artifactId>dispatch-core_2.10</artifactId>
  <version>0.9.5</version>
</dependency>

Starting sbt 0.12.0, the Scala version postfix got shortened to _2.10 for Scala 2.10.x and above to take advantage of binary compatibilities between minor releases of Scala.


text:
Q: Replacing every item at i with j value in an array with JavaScript Update here is a link of a working copy in a sandbox:
https://codesandbox.io/s/3pkzc
So I am trying to run this code - trying to use the DOM to get index .href value and replace it.
But I am stuck at the last part of actually replacing the value [j] index with the value [i] index.
I've tried to push it on as it is an array and researched other methods but I am getting no where with this.
// Get the URL of the big red button
const bigRedbtn = document.querySelectorAll('.bigRed');
//Convert into an array
const bigRedbtnArray = Array.from(bigRedbtn);
//Get all the links
const bookTitles = document.querySelectorAll('.wp-show-posts-entry-title a');
console.log(bookTitles.length);
//Convert into an array
const bookTitlesArray = Array.from(bookTitles);
console.log(bookTitlesArray.length);

for (var i = 0; i < bigRedbtnArray.length; i++) {
    for (var j = 0; j < bookTitlesArray.length; j++) {

        //  what is the links for the book?
        const link = bigRedbtnArray[i].href;
        console.log(link);
        // console.log('bigRedbtn: ', bigRedbtn[i].href);

        //this is the title url to be replaced with the link from bigRedBtn
        const titleLink = bookTitlesArray[j].href;
        console.log(titleLink);

        //So can you do something like this

        //This is where I am stuck at
        //I need to replace each bookTitlesArray[j].href with the value of bigRedbtnArray[i].href

    }
}

A: S I asked on Reddit and this is the answer I got:
const bigRedbtn = document.querySelectorAll('a.bigRed');
const bookTitles = document.querySelectorAll('.wp-show-posts-entry-title');
bigRedbtn.forEach((n, i) => n.href = bookTitles[i].href)

Thanks to all who helped.


text:
Q: FailedPreconditionError: 2 root error(s) found. (0) Failed precondition: Attempting to use uninitialized value Variable_179 i have taken code from https://github.com/FengleiFan/QAE and i changed the dataset. i executed code on google colab with tensorflow 1.x version,but i am getting error which i couldn't able to solve.
Below mentioned code is for the architecture of Quadratic AutoEncoder. Instead of Conv2D they used Quadratic Convolution function.
def CTcnn(shape=(SIZE,SIZE,1)):
x_input = Input(shape=(SIZE,SIZE,1))
encode_conv1 = Quad_conv_layer_same(x_input,shape=[3,3,1,15])
encode_conv2 = Quad_conv_layer_same(encode_conv1,shape=[3,3,15,15])
encode_conv3 = Quad_conv_layer_same(encode_conv2,shape=[3,3,15,15])
encode_conv4 = Quad_conv_layer_same(encode_conv3,shape=[3,3,15,15])
encode_conv5 = Quad_conv_layer_valid(encode_conv4,shape=[3,3,15,15])
decode_conv4 = tf.nn.relu(Quad_deconv_layer_valid_linear(encode_conv5,shape=[3, 3,15,15],outputshape=tf.shape(encode_conv4))+encode_conv4)
decode_conv3 = Quad_deconv_layer_same(decode_conv4,shape=[3, 3,15,15],outputshape=tf.shape(encode_conv3))
decode_conv2 = tf.nn.relu(Quad_deconv_layer_same_linear(decode_conv3,shape=[3, 3,15,15],outputshape=tf.shape(encode_conv2))+encode_conv2)
decode_conv1 = Quad_deconv_layer_same(decode_conv2,shape=[3, 3,15,15],outputshape=tf.shape(encode_conv1))
x_output = tf.nn.relu(Quad_deconv_layer_same_linear(decode_conv1,shape=[3, 3,1,15],outputshape=tf.shape(x_input))+x_input)

model=tf.keras.Model(inputs=x_input, outputs=x_output, name='CTcnn')
return model

**model = CTcnn(shape=(SIZE,SIZE,1))**  #getting error in this line
model.compile(optimizer='adam', loss='mean_squared_error')
model.summary()

Here's the full error:
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-49-07fdc66cd455> in <module>()
----> 1 model = CTcnn(shape=(SIZE,SIZE,1))
      2 model.compile(optimizer='adam', loss='mean_squared_error')
      3 model.summary()

<ipython-input-48-503bfc463612> in CTcnn(shape)
     16   x_output = tf.nn.relu(Quad_deconv_layer_same_linear(decode_conv1,shape=[3, 3,1,15],outputshape=tf.shape(x_input))+x_input)
     17
---> 18   model=tf.keras.Model(inputs=x_input, outputs=x_output, name='CTcnn')
     19   return model
     20

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/training.py in __init__(self, *args, **kwargs)
    145
    146   def __init__(self, *args, **kwargs):
--> 147     super(Model, self).__init__(*args, **kwargs)
    148     _keras_api_gauge.get_cell('model').set(True)
    149     # initializing _distribution_strategy here since it is possible to call

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/network.py in __init__(self, *args, **kwargs)
    162         'inputs' in kwargs and 'outputs' in kwargs):
    163       # Graph network
--> 164       self._init_graph_network(*args, **kwargs)
    165     else:
    166       # Subclassed network

/tensorflow-1.15.2/python3.6/tensorflow_core/python/training/tracking/base.py in _method_wrapper(self, *args, **kwargs)
    455     self._self_setattr_tracking = False  # pylint: disable=protected-access
    456     try:
--> 457       result = method(self, *args, **kwargs)
    458     finally:
    459       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/network.py in _init_graph_network(self, inputs, outputs, name, **kwargs)
    265
    266     if any(not hasattr(tensor, '_keras_history') for tensor in self.outputs):
--> 267       base_layer_utils.create_keras_history(self._nested_outputs)
    268
    269     self._base_init(name=name, **kwargs)

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/base_layer_utils.py in create_keras_history(tensors)
    182     keras_tensors: The Tensors found that came from a Keras Layer.
    183   """
--> 184   _, created_layers = _create_keras_history_helper(tensors, set(), [])
    185   return created_layers
    186

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
--> 231           layer_inputs, processed_ops, created_layers)
    232       name = op.name
    233       node_def = op.node_def.SerializeToString()

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
--> 231           layer_inputs, processed_ops, created_layers)
    232       name = op.name
    233       node_def = op.node_def.SerializeToString()

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    227           else:
    228             with ops.init_scope():
--> 229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
    231           layer_inputs, processed_ops, created_layers)

/tensorflow-1.15.2/python3.6/tensorflow_core/python/keras/backend.py in __call__(self, inputs)
   3474
   3475     fetched = self._callable_fn(*array_vals,
-> 3476                                 run_metadata=self.run_metadata)
   3477     self._call_fetch_callbacks(fetched[-len(self._fetches):])
   3478     output_structure = nest.pack_sequence_as(

/tensorflow-1.15.2/python3.6/tensorflow_core/python/client/session.py in __call__(self, *args, **kwargs)
   1470         ret = tf_session.TF_SessionRunCallable(self._session._session,
   1471                                                self._handle, args,
-> 1472                                                run_metadata_ptr)
   1473         if run_metadata:
   1474           proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Attempting to use uninitialized value Variable_179
     [[{{node Variable_179/read}}]]
     [[Variable_179/read/_1]]
  (1) Failed precondition: Attempting to use uninitialized value Variable_179
     [[{{node Variable_179/read}}]]
0 successful operations.
0 derived errors ignored.

Any ideas as to how I can fix this?


text:
Q: Android: Control action to happen if user closes app with Recent Apps Button my app have a availability states to show if user is online or not, now when user closes the app it would gives value of 0 and 1 if he is online.
now when user closes the app with recent apps button there is no activity lifecycle for it so i can't control the action to send info that user is offline.
so any solution to be able to control what happens when user closes app with recent apps?

A: Update user online status in onPause().
onPause() use-case as per Docs.

This callback is mostly used for saving any persistent state the
activity is editing, to present a "edit in place" model to the user
and making sure nothing is lost if there are not enough resources to
start the new activity without first killing this one. This is also a
good place to stop things that consume a noticeable amount of CPU in
order to make the switch to the next activity as fast as possible.


text:
Q: What is axios rate limit? Does anyone know's the rate limit of the axios api because it is throwing a lot of 429 errors when i am using it
here is my codes
const instance = axios.create({ baseURL: 'http://9rv324283.ngrok.io' })

<NavigationEvents
onWillFocus={() => {

  try {

    const response = await instance.get('fetchNewDishes');

    this.setState({data: response.data})

  } catch(err) {

    console.log(err)

  }

}}>

<TouchableOpacity onPress={() =>  instance.patch(`/postNewDish/${this.state.dish}`)}>
            <Text style={{ fontSize: 16, color: '#555', padding: 15 }}>Post Dish</Text>
          </TouchableOpacity>

A: Axios is an Http Client. Http Clients won't have a rate limit. However, API's typically have rate limiting implemented (especially public onces). The error message you're receiving is saying the following:

The HTTP 429 Too Many Requests response status code indicates the user
has sent too many requests in a given amount of time ("rate
limiting").

With that being said, the only thing you can do on your side is make requests less frequently. Rate Limiting is something implemented by the API you're using. You should consult their documentation to figure out the specifics on what their rate limits are.


text:
Q: How to connect Hive to asp.net project Hi I'm very new to Hadoop.
I have installed Microsoft HDInsight to my local system.
Now I want to connect to hive and HBase but for HIVE connection
I have to specify Connection string, port, username, password.
But I'm not able to figure out how I will get this value.
I have tried with localhost and 8085 as a port but this doesn't work.
I also done it by giving localhost IP and my system IP too.
Please help with this and let me know how i should proceed for HBase connectivity

A: Your best bet is probably to use Microsoft's Hive SDK (also available on nuget as Microsoft.Hadoop.Hive)
There is a great sample on how to connect and run a Linq-to-Hive query at
http://hadoopsdk.codeplex.com/wikipage?title=Simple%20Linq%20To%20Hive%20Query&referringTitle=LINQ%20to%20Hive
This used the WebHcat API to submit your query to Hive, and will work against an HDInsights cluster in the Azure cloud (hence the need to provide a storage key to get the results back again).
If you're only interested in using the local copy you can adapt the example to exclude the storage account credentials.
var db = new HiveConnection(
            webHCatUri: new Uri("http://localhost:50111"),
            userName: (string) "hadoop", password: (string) null);

var result = db.ExecuteHiveQuery("select * from w3c");
result.Wait();

works against a base install of HDInsight Preview.


text:
Q: Android gradle package R does not exist in heir library I am not able to use resourse "net.londatiga.android.R.drawable.menu_down_arrow" file from "NewQuickAction3D" library in heir library called "AndroidXXXLib", but other classes I am able to use.
I get an error during gradle build "error: package net.londatiga.android.R does not exist".
How can I fix build scripts to have ability of use "net.londatiga.android.R" in my heir library?
The main goal is be able to use android resources from parent library inside heir library.
There are dependencies between projects:

*

*AndroidXXXDemo

*

*AndroidXXXLib

*

*DragSortListView

*NewQuickAction3D

settings.gradle file in root folder contains:
include ':libraries:DragSortListView:DragSortListViewLib'
include ':libraries:NewQuickAction3D:NewQuickAction3DLib'
include ':AndroidXXXLib'
include ':AndroidXXXDemo'

It is build.gradle inside AndroidXXXLib:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.9.+'
    }
}
apply plugin: 'android-library'
apply plugin: 'idea'

repositories {
    mavenCentral()
}

android {

    compileSdkVersion 19
    buildToolsVersion '19.1.0'

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':libraries:DragSortListView:DragSortListViewLib')
    compile project(':libraries:NewQuickAction3D:NewQuickAction3DLib')
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
    compile 'com.android.support:support-v4:19.0.+'
    compile 'net.simonvt.menudrawer:menudrawer:3.0.+@aar'
    compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}

idea project looks like:

A: Issue resolved.
Build tool merge all resources, that's why main R file of my heir library has to be used instead of  "net.londatiga.android.R".
Note: Also need to make sure that there are no identical layout names in projects resources to avoid errors related to missing view ids (Priority Order for Library Dependencies)


text:
Q: Improper Output from call to subroutine My program is meant to take input of GPA, student status, and credit hours from an excel worksheet and use them to calculate tuition, fees, discount, and total amount due for a given student.
I have to use separate subroutines to solve the tuition, fees, discount, and total for each person in the worksheet.
My problem is when I try to call a different subroutine to my primary subroutine and get a value I need, it displays a random number and doesn't use access any part of the fees or other subroutines set values.
I've tried moving my declarations, but the code just gets more errors.
'Primary subroutine
Sub Proj_5p2()

'Variables
Dim dblGPA As Double
Dim strStat As String
Dim intRow As Integer
Dim intCredHrs As Integer
Dim curTuition As Currency
Dim curFees As Currency
Dim curDisc As Currency
Dim curTotal As Currency

'Processing
Do While (Range("a" & intRow) <> "")
    'Get required input for each row
    dblGPA = Range("c" & intRow).Value
    strStat = UCase(Range("d" & intRow).Value)
    intCredHrs = Range("e" & intRow).Value

    'Call subroutines
    Call Tuition(curTuition, intCredHrs, strStat)

    'Display subroutines
    Range("f" & intRow) = curTuition
Loop

End sub

'Call from subroutine
Sub Tuition(curTuition As Currency, intCredHrs As Integer, strStat As String)

   If strStat = "GRADUATE" Then
        If intCredHrs < 18 Then
            curTuition = 335 * intCredHrs
        Else
            curTuition = 6500
    End If

    ElseIf strStat = "UNDERGRADUATE" Then
        curTuition = 550 * intCredHrs
    End If

End Sub

I need it to calculate a students tuition based off their credit hours and status in college.
In my code, I had it do an undergrad with 10 credit hours.
This should result in a Tuition of $3,350.00 but instead it just turns out a value of $300.00.
I have no idea where it gets the 300 from.

A: It is hard to say without seeing the entire thing (data + macro), but I would bet on the fact that you don't have the Workbook or Worksheet declaration in your main Subroutine. Now it could read from some other sheet or even workbook that is open.
I'd add:
    Sub Proj_5p2()

    ' Delcare your workbook and worksheet
    Dim wb as Workbook
    Dim ws as Worksheet
    ' If data in the same workbook as the macro,
    ' or a static name: Set wb = Workbooks("bookname.xlsx")
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("nameofsheet")

    'Variables
    Dim dblGPA As Double
    Dim strStat As String
    Dim intRow As Integer
    Dim intCredHrs As Integer
    Dim curTuition As Currency
    Dim curFees As Currency
    Dim curDisc As Currency
    Dim curTotal As Currency

    ' Adds the worksheet reference, now each range object with .Range
    With ws

    'Processing
    Do While (.Range("a" & intRow) <> "")
    'Get required input for each row
    dblGPA = .Range("c" & intRow).Value
    strStat = UCase(.Range("d" & intRow).Value)
    intCredHrs = .Range("e" & intRow).Value

    'Call subroutines
    Call Tuition(curTuition, intCredHrs, strStat)

    'Display subroutines
    .Range("f" & intRow) = curTuition
    Loop

    End With

End sub


text:
Q: Starting mongodb server using npm scripts I am starting mongodb server using cmd with the following command:
"C:/Program Files/MongoDB/Server/3.6/bin/mongod.exe"
It starts the mongodb server perfectly.
Now I need to do it via npm script. Below is my package.json file:
package.json:
"scripts": {
"ng": "ng",
"prestart": "start /b \"C:/Program Files/MongoDB/Server/3.6/bin/mongod.exe\"",
"start": "ng serve | node server.js",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}

Now when I hit npm start, it doesn't starts the mongodb server.
I also included the path "C:/Program Files/MongoDB/Server/3.6/bin/mongod.exe" in environment variables (both user&system).
Can anyone help me to know where I was wrong?

A: I read help for the start cmd command and was able to run it in a separate named window:
"scripts": {
    "db": "start \"ToDo MongoDB instance\" /D \"C:/Program Files/MongoDB/Server/4.0/bin/\" mongod.exe --dbpath=\"C:/GIT/NodeJS/todo/db\""
},

A: Try to escape the space in Program Files with a backslash, i.e. Program\ Files. I'm not a Windows guy but I hope this works there as well.
EDIT
As you figured out yourself, you also can enclose the path in (escaped) quotes, then resolving a directory name containing a space should work.

A: This is what worked for me for Windows:
"scripts": {
    "db": "path_to_mongod.exe --dbpath path_to_mongodb-data_folder"
}

A: For me worked on WINDOWS 10 with escape characters for backslash character and for quote character . In your case You used only for quote character. I think that may wary depending on OS and terminal you start with. I go with VSC terminal.
"scripts": {
"db": "C:\\Users\\<HERE_GOES_YOUR_USER>\\<PATH_TO_MONGO>\\mongodb\\bin\\mongod.exe --dbpath=\"c:\\Users\\<HERE_GOES_YOUR_USER>\\<PATCH_TO_DIR_WITH_DATA>\\data\" "
},


text:
Q: Android Java Buttons coordinates I want to resize buttons if the screen is big . So I have done it using this method . I got screen size and put button width screenWidth/4 . But now I can't put buttons position . I used relative layout and I put their position from xml but when I change their sizes the are lying each on other at 0,0 position.

Here is XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/pink"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.vahe_muradyan.yourquote.MainActivity" >

    <Button
        android:id="@+id/openCamera"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="71dp"
        android:background="@drawable/roundbuttom"
        android:text="@string/camera" />

    <Button
        android:id="@+id/openGallery"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignLeft="@+id/openDefaults"
        android:layout_below="@+id/openDefaults"
        android:layout_marginTop="43dp"
        android:background="@drawable/roundbuttom"
        android:text="@string/gallery" />

    <Button
        android:id="@+id/openDefaults"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignLeft="@+id/openCamera"
        android:layout_centerVertical="true"
        android:background="@drawable/roundbuttom"
        android:text="@string/defaults" />

</RelativeLayout>

I have upploaded images on Nexus S and nexus 10 .

A: Add dimensions per screen size
you need to create in your res folder new folders named
values-sw600dp
and in the normal values folder create an xml file called
dimens.xml
in that file write
<dimen name="button_width">70dp</dimen>
<dimen name="button_height>70dp</dimen>
<dimen name="button_text_size">14sp</dimen>

in your values-sw600dp create another dimens.xml file
in it write
<dimen name="button_width">140dp</dimen>
<dimen name="button_height>140dp</dimen>
<dimen name="button_text_size">20sp</dimen>

//play with the sizes to find the good fit
in your xml file write this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/pink"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.vahe_muradyan.yourquote.MainActivity" >

    <Button
        android:id="@+id/openCamera"
        android:layout_width="@dimen/button_width"
        android:layout_height="@dimen/button_height"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="71dp"
        android:background="@drawable/roundbuttom"
        android:textSize="@dimen/button_text_size"
        android:text="@string/camera" />

    <Button
        android:id="@+id/openGallery"
        android:layout_width="@dimen/button_width"
        android:layout_height="@dimen/button_height"
        android:textSize="@dimen/button_text_size"
        android:layout_alignLeft="@+id/openDefaults"
        android:layout_below="@+id/openDefaults"
        android:layout_marginTop="43dp"
        android:background="@drawable/roundbuttom"
        android:text="@string/gallery" />

    <Button
        android:id="@+id/openDefaults"
        android:layout_width="@dimen/button_width"
        android:layout_height="@dimen/button_height"
        android:textSize="@dimen/button_text_size"
        android:layout_alignLeft="@+id/openCamera"
        android:layout_centerVertical="true"
        android:background="@drawable/roundbuttom"
        android:text="@string/defaults" />

</RelativeLayout>

The system will choose the correct values based on the device you run the app on.
The buttons will be big enough (providing you give good values in values-sw600dp/dimens.xml file)
This is the folder tree:

have fun!


text:
Q: DirectShow with capture card blurry pixels I'm programming a directshow application with streaming card. First I installed the drivers and tried their streaming software, everything works perfect and its pixel perfect.
Then make C# code for capturing still images through directshow, pretty much exact copy of  DxWebCam example, to be found here in official net library:
https://sourceforge.net/projects/directshownet/files/DirectShowSamples/2010-February/
I also tried more modern approach of using pins and smartee, however I was not able to make it work.
The issue is, the images captured with directshow are just a bit off, like it is using some sort of compression. To demonstrate my issue, here is the original pixel perfect image:
and here is the directshow captured image, with some sort of horizontal pixel mashup:   (need to zoom in to see the wrong pixels)
I've tried setting massive bitrate as well as playing with video formats etc.
However I'm just not able to stream pixel perfect in directshow, yet on the same computer with native manufacturer application it works perfectly.
I'm lost as in how to continue or how to try to debug this. Any help appreciated


text:
Q: WCF Rest .NET 4.0 Unhandled Exceptions I've found a bunch of questions that were very close to what I need. But I'm worried that I have missed some important information.
How do I catch all unhandled exceptions using WCF Rest with .NET 4.0?
For security purposes I do not want unhandled exceptions going to the client. I want to log all exceptions and for unknown exceptions just send back 500 Internal Server Error.
My best research so far tells me I need to implement IErrorHandler and throw WebFaultExceptions for known exceptions. One issue I have with this is that all of my business logic is in a separate project from the WCF service and it doesn't make sense to throw a Web exception from the underlying class library since the class library could be consumed by another process which may not be a WCF Rest Service. Is there a nice way to map exceptions?

A: Yes, you can implement IErrorHandler and use it to map exceptions. You don't need to throw WebFaultException from your business logic, just throw your custom exceptions.
For example, you can map YourCustomException to some simple json string. Instead of string you can put some object. Sample IErrorHandler.ProvideFault implementation:
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
        if (error is YourCustomException)
        {
            fault = Message.CreateMessage(version, string.Empty, String.Format("Error: {0}.", error.Message), new DataContractJsonSerializer(typeof(string)));
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));

            webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.InternalServerError);
        }
}

So when YourCustomException is thrown by business logic it will be catched by the handler and converted to proper fault.
See also: CodeProject article


text:
Q: How to keep my date value correct for submitting to API? I'm on an angular app with .net core 3.1 backend.
I use a material datepicker.
When I pick up a date I can see in the console it looks like
Wed Feb 10 2021 00:00:00 GMT+0100

However, when it arrives in my web api controller, the value has changed. It's now in utc and therefor, it's set to the previous day
StartDate.ToString()
//"09/02/2021 23:00:00"
StartDate.Kind
//Utc

I understand it's something to do with gmt vs utc.
But I'm not sure about the best way to fix it.
Any advice?

A: I assume you use DateTime type in your DTO models on server side.
DateTime does not contain any info about timezone, so I assume that json serealizer converts it into UTC if the target type cannot keep timezone info (if the target type is DateTime).
Please try to use DateTimeOffset type instead. Let me know if it helps.


text:
Q: Nesting strings in Tcl for puts and join I want to generate output that looks like this:
foo:
  1
  2
  3

My naïve attempt would be something like puts "foo:\n  [join {1 2 3} {\n  }]" but of course that doesn't work because {\n  } isn't unescaped and it produces this instead:
foo:
  1\n  2\n  3

I can't seem to find the right sequence of escapes to nest a string within a string such that join sees the spaces and unescapes the \n to a newline. Is there a way to do what I want?

A: Use double quotes instead of braces:
% puts [join {foo: 1 2 3} "\n  "]
foo:
  1
  2
  3

Or instead of trying to build up a single string, use a loop:
puts "foo:"
foreach i {1 2 3} {
    puts "  $i"
}

A: After experimenting more, here's what I found:

*

*Just don't escape anything, which (surprisingly to me) works:
puts "foo:\n  [join {1 2 3} "\n  "]"

*Encode the spaces:
puts "foo:\n  [join {1 2 3} \n\x20\x20]"

*Use a variable:
set delimiter "\n  "
puts "foo:${delimiter}[join {1 2 3} $delimiter]"

*As Shawn's answer describes, use a loop:
puts "foo:"
foreach ii {1 2 3} { puts "  $ii" }

... or any number of multi-statement variations on that theme. Another example:
puts -nonewline "foo:\n  "
puts [join {1 2 3} "\n  "]

For reasons, the multi-statement versions don't work for me, but I can use the first option.


text:
Q: How to disable push-notifications using Selenium for Firefox and Chrome? I want to disable the notification when I launch Firefox browser through Selenium  Webdriver.
I found this answer, but it's deprecated and does not work for me on Firefox (it works perfectly on Chrome though).
I'm use this dependency for my pom.xml:
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.11.0</version>
</dependency>

A: If your usecase is to disable the notification following are the options :

*

*To disable Push Notification in Firefox browser client take help of a FirefoxProfile and pass the Keys dom.webnotifications.enabled and dom.push.enabled along with the desired Value as false :
System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile testprofile = profile.getProfile("debanjan");
testprofile.setPreference("dom.webnotifications.enabled", false);
testprofile.setPreference("dom.push.enabled", false);
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, testprofile);
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dc);
WebDriver driver =  new FirefoxDriver(opt);
driver.get("https://www.ndtv.com/");

Note : This method uses an existing FirefoxProfile by the name debanjan stored in my local system which was created following the documentation at Creating a new Firefox profile on Windows

*

*To disable notification in Chrome browser client take help of a setExperimentalOption() to pass a HashMap containing profile.default_content_setting_values.notifications with Value as 2 :
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
options.addArguments("--disable-notifications");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.ndtv.com/");


text:
Q: DNS lookup fails after resume from sleep My Windows 7 Ultimate x64 PC has a strange networking issue. When I resume from sleep, no web pages will load (other programs such as Hamachi VPN are also unable to locate their servers). If I use Google Chrome, it says that DNS lookups are failing. However, if I then open a command window and use NSLOOKUP to perform lookups for the web pages that just failed, the lookups appear to be working correctly. So the command prompt is able to perform lookups, while other applications such as web browsers are not.
I can clear this problem by disabling then enabling the network adapter in 'Network and Sharing Center'. After doing this, everything works again. It's a pain to have to do that each time I resume from sleep, though.
Anyone know the cause for this, or have a suggestion for how to troubleshoot it?

A: One cause of this problem is the presence of virtual network adapters, for example the adapters that get installed with VirtualBox or VMWare.

The presence of Virtual Network Adapters for (example) VMWare or AT&T Network Client appears to cause problems with resumption of DNS operation over wireless after resume from sleep.  Disabling the virtual adapters seems to allow normal networking to continue after resume from sleep.

Source:
http://answers.microsoft.com/en-us/windows/forum/windows_7-networking/windows-7-no-dns-or-no-network-after-resume-wake/c1253ab0-4793-449e-8975-a900ce7dec4f?auth=1

A: Change the settings in advanced power profile properties so your LAN adapter doesn't go to sleep/power down.
This can be disabled regardless of your network adapter.
Source: Microsoft Technet

Configuring power management using the user interface
To turn power management features on or off

*

*Open Network and Sharing Center (click the Start button, type Network and Sharing in the Start Search box, and press Enter).

*Click the Change adapter settings link in the upper left of the navigation pane.

*Right click the network connection you want to enable/disable power management support on and click Properties.

*Click Configure.

*On the Power Management tab, check or clear the Allow the computer to turn off this device to save power check box.
When checked, power management is enabled on the network adapter.
When cleared, power management is disabled on the network adapter.

A: Check whether you have multiple DNS servers listed.  If you do, make sure all of them are valid.  Having a mix of good and bad DNS servers can cause very inconsistent DNS behavior.
If you are getting the DNS server from a DHCP server, check whether the DHCP server is configured with multiple DNS and whether they are all correct.

A: Same in Windows 8 and 8.1: After sleep the Windows DNS client does not work properly. Open the service control, look for DNS client and restart it. DNS lookup should work again without restarting the machine.

A: If you have hamachi, maybe is the culprit, after i uninstalled it all worked again, another alternative is try to enable and disable the hamachi network adapter

A: reset network device
resetting "Realtek PCIe GBE Family Controller" fix it for me
devcon restart "PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09"
PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09\4&21A1C3AE&0&00E5: Restarted
1 device(s) restarted.

uninstall realtek network driver doesn't fix it
uninstalling the realtek network driver doesn't fix it for me. dns lookup is still often broken when i return from sleep
test
before reset nslookup takes several seconds
nslookup google.com
DNS request timed out.
    timeout was 2 seconds.
Server:  UnKnown
Address:  8.8.8.8

DNS request timed out.
    timeout was 2 seconds.
Name:    google.com
Address:  2a00:1450:400f:804::200e

after reset it returns instantly
nslookup google.com
Server:  google-public-dns-a.google.com
Address:  8.8.8.8

Non-authoritative answer:
Name:    google.com
Addresses:  2a00:1450:400f:804::200e
          216.58.209.142

my dns server is 8.8.8.8 instead of my isp's because i changed it in case that was the problem. which it wasn't
netsh interface ipv4 add dnsserver "Local Area Connection" address=8.8.8.8

after the test i reset the dns server and nslookup still works
netsh interface ip set dns "Local Area Connection" dhcp

before reset dhcp renew timeout
C:\Users\User>ipconfig /release & ipconfig /renew

Windows IP Configuration

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::a1cf:1ddf:5c50:191%8
   Autoconfiguration IPv4 Address. . : 169.254.1.145
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :

Ethernet adapter VMware Network Adapter VMnet8:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::3dae:5a21:fdc0:e49e%6
   IPv4 Address. . . . . . . . . . . : 192.168.217.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Tunnel adapter isatap.{1D0B324E-565A-4A26-9ED5-5C638FA964E3}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{EE0FF7D8-C160-4203-91ED-73706E508332}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter Local Area Connection* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Windows IP Configuration

An error occurred while renewing interface Ethernet : unable to contact your DHCP server. Request has timed out.

before the network device reset i also did these reset commands. it's probably irrelevant but it might not be because they say a os restart is required to complete it. which might mean a network device restart
netsh interface ip reset
Resetting Global, OK!
Resetting Interface, OK!
Resetting Unicast Address, OK!
Resetting Neighbor, OK!
Resetting Path, OK!
Resetting , failed.
Access is denied.

Resetting , OK!
Restart the computer to complete this action.

netsh winsock reset catalog
You must restart the computer in order to complete the reset.

i also disabled VMware Bridge Protocol for the network connection associated with the device, which is probably irrelevant
system
my system is
Operating System
    Windows 8.1 Enterprise 64-bit
Motherboard
    ASUSTeK COMPUTER INC. P8Z77-M PRO (LGA1155) 30 °C

devcon driverfiles "PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09"
PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09\4&21A1C3AE&0&00E5
    Name: Realtek PCIe GBE Family Controller
    Driver installed from C:\WINDOWS\INF\oem30.inf [RTL8168FB.ndi]. 5 file(s) used by driver:
        C:\WINDOWS\system32\DRIVERS\au630x64.sys
        C:\WINDOWS\system32\RtNicProp64.dll
        C:\Program Files\ASUS\AMDA\U3\U3.dll
        C:\Program Files\ASUS\AMDA\U3\U3BoostSvr64.dll
        C:\Program Files\ASUS\AMDA\U3\U3BoostSvr64.exe.manifest
1 matching device(s) found.

devcon drivernodes "PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09"
PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09\4&21A1C3AE&0&00E5
    Name: Realtek PCIe GBE Family Controller
Driver node #0:
    Inf file is C:\WINDOWS\INF\oem30.inf
    Inf section is RTL8168FB.ndi
    Driver description is Realtek PCIe GBE Family Controller
    Manufacturer name is Realtek
    Provider name is Realtek
    Driver date is 2013-03-14
    Driver version is 8.13.314.2013
    Driver node rank is 16719872
    Driver node flags are 0000B045
        Inf is digitally signed
Driver node #1:
    Inf file is C:\WINDOWS\INF\oem30.inf
    Inf section is RTL8168FB.ndi
    Driver description is Realtek PCIe GBE Family Controller
    Manufacturer name is Realtek
    Provider name is Realtek
    Driver date is 2013-03-14
    Driver version is 8.13.314.2013
    Driver node rank is 16711680
    Driver node flags are 0004B045
        Inf is digitally signed
Driver node #2:
    Inf file is C:\WINDOWS\INF\oem81.inf
    Inf section is RTL8168FB.ndi
    Driver description is Realtek PCIe GBE Family Controller
    Manufacturer name is Realtek
    Provider name is Realtek
    Driver date is 2012-02-03
    Driver version is 7.52.203.2012
    Driver node rank is 16719872
    Driver node flags are 00003045
        Inf is digitally signed
Driver node #3:
    Inf file is C:\WINDOWS\INF\netrt630x64.inf
    Inf section is RTL8168FB.ndi
    Driver description is Realtek PCIe GBE Family Controller
    Manufacturer name is Realtek
    Provider name is Microsoft
    Driver date is 2013-05-10
    Driver version is 8.1.510.2013
    Driver node rank is 16719872
    Driver node flags are 00102045
        Inf is digitally signed
1 matching device(s) found.

after uninstalling the realtek network driver windows revert to this driver which doesnt have a wake problem
C:\Users\User>devcon driverfiles "PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09"
PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09\4&21A1C3AE&0&00E5
    Name: Realtek PCIe GBE Family Controller
    Driver installed from C:\WINDOWS\INF\netrt630x64.inf [RTL8168FB.ndi]. 1 file(s) used by driver:
        C:\WINDOWS\system32\DRIVERS\Rt630x64.sys
1 matching device(s) found.

C:\Users\User>devcon drivernodes "PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09"
PCI\VEN_10EC&DEV_8168&SUBSYS_85051043&REV_09\4&21A1C3AE&0&00E5
    Name: Realtek PCIe GBE Family Controller
Driver node #0:
    Inf file is C:\WINDOWS\INF\oem81.inf
    Inf section is RTL8168FB.ndi
    Driver description is Realtek PCIe GBE Family Controller
    Manufacturer name is Realtek
    Provider name is Realtek
    Driver date is 2012-02-03
    Driver version is 7.52.203.2012
    Driver node rank is 16719872
    Driver node flags are 00002045
        Inf is digitally signed
Driver node #1:
    Inf file is C:\WINDOWS\INF\netrt630x64.inf
    Inf section is RTL8168FB.ndi
    Driver description is Realtek PCIe GBE Family Controller
    Manufacturer name is Realtek
    Provider name is Microsoft
    Driver date is 2013-05-10
    Driver version is 8.1.510.2013
    Driver node rank is 16719872
    Driver node flags are 00142045
        Inf is digitally signed
1 matching device(s) found.

A: Open CMD and try this command to clear DNS cache:
ipconfig /flushdns
after that, run test ping to google.com:ping google.com.
If this work you should ping success to google.com. Hope this helpful!


text:
Q: Windows task scheduler - log file C# I have a c# program that has app.config. I have
<appSettings>
    <add key="logFile" value="Logs.txt"/>
  </appSettings>

namespace LogTesting
{
    class LogMessages
    {
        public static string WriteToFile(string Exceptionfrom, string text)
        {
            var dir = new System.IO.DirectoryInfo(Program.destnDirectoryName);
            if (!dir.Exists) dir.Create();
            var path = Path.Combine(dir.FullName, ConfigurationManager.AppSettings["logFile"]);

            using (StreamWriter w = File.AppendText(ConfigurationManager.AppSettings["logFile"]))
            {
                Log(Exceptionfrom, text, w);
            }
            return path;
        }

        public static void Log(string Exceptionfrom, string logMessage, TextWriter w)
        {
            w.WriteLine("{0}\t{1} ", Exceptionfrom, logMessage);

        }
    }
}

using LogTesting;
namespace MainProgram
{
       class Program
    {
        public const string destnDirectoryName = @"C:\tempLogs";
[STAThread]
        static void Main(string[] args)
        {
LogMessages.WriteFile("in main", DateTime.Now.ToString());
}
}
}

When I run this F5 or CTRL+F5, log gets written to C:\tempLogs\Logs.txt. When I put this in windows task scheduler, log does not get written . Why is it?
Thanks
R


text:
Q: Sort columns in a matrix I have a matrix (or a multidimensional array) of non unique values like this one:
var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]

I want to sort a row of this matrix but the others rows should reorder the same in order to keep the column like organization.
//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]

I would prefer a lodash solution if possible.

A: You could use an array with the indices and sort it with the values of matrix[0]. Then build a new array with sorted elements.

var matrix = [[1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4]],
    indices = matrix[0].map((_, i) => i);

indices.sort((a, b) => matrix[0][a] - matrix[0][b]);

result = matrix.map(a => indices.map(i => a[i]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Using lodash you could transpose the matrix with zip, sort it with sortBy by a given row number, and then transpose it back:
_.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row))

var matrix = [
    [1, 3, 2, 4, 1],
    [2, 4, 1, 3, 2],
    [4, 3, 2, 1, 4]
];
var row = 0;

result = _.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row));

console.log(result.join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

With the rest parameter syntax you can also write this as:
_.zip(..._.sortBy(_.zip(...matrix), row));


text:
Q: Change Default Uploading for Digital Ocean Space to Public for files from Filezilla pro I have millions of small images about 1KB-5KB, which I need to upload them to the Digital Ocean Space.
I have Filezilla Pro , and  I can successfully upload the files to the Digital Ocean Space using the Filezilla Pro , but when I upload those files to the Digital Ocean Space using the Filezilla Pro , their default statuses are Private.
As a result accessing those files through a URL is not possible as I get an

Access Denied Error.

Another way is using the Rclone but for that I need to upload those files to the Digital Ocean's Droplet by zipping them and then using the Rclone to upload them to Digital Ocean space.
But it's very long process because I have to do the zipping process from Windows and then transfer the files to the droplet in order to unzip them and upload them to the Digital Ocean's Droplet using Rclone.
How could I upload all of my files , directly  , with a public status from Windows using the FileZilla Pro or any other client similar to it?


text:
Q: OS Window PopUp to save a file is giving a problem in file downloading using javascript I want to show some kind of notification based on my file download status like it's failed or success. what's the actual problem here it is when I'm clicking download button it's opening default OS popup window like where to save the downloaded file and I'm triggering below method's code on the click of download button and it's showing notification of success before downloading a file. I could not able to do find any resource that can me help out to find the status of downloading of a file
Below is the code of downloading a file
   const type = 'text/json';
      const fileName = `${programName}.json`;
      const data = JSON.stringify(json);
      const blob = new Blob([data], { type });
      // Create an anchor element and dispatch a click event on it
      // to trigger a download
      const a = document.createElement('a');
      a.download = fileName;
      a.href = URL.createObjectURL(blob);
      const clickEvt = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
      });
      a.dispatchEvent(clickEvt);
      a.remove();
      setOpen(true);  // here I'm showing notification

I've tried to show the notification once the file is downloaded
I want to show the notification only after the file is either download is success or failure or else if I can listen the save or cancel button event of os window file saver in my code that would also work.
It's actually showing the notification before downloading the file because of OS window popup where to save the file


text:
Q: How do I stop javascript automatically adding tags during selection? Please see Fiddle Here
Basically it's a text-highlighter that nearly works perfectly.
The issue arrises when tags such as
 or
 are within the selection.
The JavaScript seems to automatically add tags.
If you go to function filterHtmlLevels and add alert(htmlStr);,
then when you select an area of text over two paragraphs you can see it has added the
 tags when it shouldn't.
I could use .replace but unsure how to safely keep the DOM structure.
EDIT
I have found it occurs during the function getSel() where it wraps a div around the selection. Unsure how to change this to NOT add extra tags - i.e. treat the html as a string

A: Fixed (TESTED CHROME ONLY):
http://jsfiddle.net/6L58X/
Please comment with any updates / improvements, or edit!
Documented for if link dies:
JS:
$('#highlightable').bind('mouseup', function () {
    highlight();
});

function highlight() {
    // not IE case
    var selHtml;
    if (window.getSelection) {
        selHtml = getSel();
    }
    // IE case
    else if (document.selection && document.selection.createRange && document.selection.type != "None") {
        selHtml = getSelIE();
    }
    else { return; }
    if(selHtml.length == 0) { return; }
    var allhtml = $('#highlightable').html().toString();
    var temphhtml = '
';
    var pos = allhtml.indexOf(temphhtml);
    var endpos = pos + selHtml.length;

    var preSelStr = allhtml.substring(0, pos);
    var postSelStr = allhtml.substring((pos + temphhtml.length + selHtml.length + 6), allhtml.length);

    preSelStr = cleanEnd(preSelStr);
    postSelStr = cleanStart(postSelStr);

    //alert(preSelStr+'          '+postSelStr);
    var prepend = '';
    var postpend = '';

    var cs = countSpans(preSelStr);
    if (cs > 0) {
        prepend = '';

        var insSS = locations('', selHtml);
        var insSE = locations('', selHtml);

        if (insSS.length > insSE.length) {
            postpend = postpend + '';
        } else if (insSS.length == insSE.length) {
            postpend = '';
        }
    }
    var newSelStr = filterHtmlLevels(selHtml, allhtml);
   // alert(newSelStr);
    var newHtml = preSelStr + prepend + newSelStr + postpend + postSelStr;
    //  alert(newHtml);
    $('#highlightable').html(newHtml);

}

function cleanEnd(preSelStr) {
    var tags = ["
", "
"];
    if (typeof String.prototype.endsWith != 'function') {
        String.prototype.endsWith = function (str) {
            return this.slice(-str.length) == str;
        };
    }
    for (var i = 0; i < tags.length; i++) {
        if (preSelStr.endsWith(tags[i])) {
            var len = tags[i].length;
            var cleanStr = preSelStr.substring(0, preSelStr.length - len);
            return cleanStr;
        }
    }
    return preSelStr;
}

function cleanStart(postSelStr) {
    if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (str) {
            return this.slice(0, str.length) == str;
        };
    }
    var tags = ["
", "
", "
"];
    for (var i = 0; i < tags.length; i++) {
        if (postSelStr.startsWith(tags[i])) {
            var len = tags[i].length;
            var cleanStr = postSelStr.substring(len, postSelStr.length);
            return cleanStr;
        }
    }
    return postSelStr;
}

function filterHtmlLevels(htmlStr, allhtml) {
    var newStr = htmlStr.replace(//g, "");
    newStr = newStr.replace(/<\/span>/g, '');
    newStr = cleanEnd(newStr);
    newStr = cleanStart(newStr);
   // alert(htmlStr);
     newStr = newStr.replace(/
/g, '
');
      newStr = newStr.replace(/<\/p>/g, '
');
    return newStr;
}

function locations(substring, string) {
    var a = [],
        i = -1;
    while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
    return a;
}

function getSel() {
    var selObj = window.getSelection();
    var selRange = selObj.getRangeAt(0);
    var newElement = document.createElement("b");
    var documentFragment = selRange.extractContents();
    newElement.appendChild(documentFragment);
    var filteredElement = divWrap(newElement.innerHTML);
    selRange.insertNode(filteredElement);
    selObj.removeAllRanges();
    return filteredElement.innerHTML.toString();
}

function getSelIE() {
    var range = document.selection.createRange();
    var selectedText = range.htmlText;
    var newText = '
' + selectedText + '
';
    document.selection.createRange().pasteHTML(newText);
    return newText;
}

function divWrap(htmlString) {
    var wrapper = document.createElement('div');
    wrapper.className = "temph";
    wrapper.innerHTML = htmlString;
    return wrapper;
}

function countSpans(preSelStr) {
    // returns 0 if same num, > 0 if more span starts
    var StartSpans = locations(preSelStr, '');
    var EndSpans = locations(preSelStr, '');
    var count = StartSpans.length - EndSpans.length;
    return count;
}

HTML:

stibulum nisl orci, viverra in sollicitudin sed, iaculis vel erat. Nam lacus quam, volutpat et porta non, consequat ac tortor. Fusce non lorem vitae

libero imperdiet convallis. Morbi vestibulum viverra ligula, porttitor dapibus justo dictum ut. Pellentesque eget laoreet metus. Curabitur rhoncus consectetur nulla, id imperdiet nulla pellentesque sit amet. Cras sodales arcu ac orci suscipit pulvinar sollicitudin risus gravida. Praesent condimentum erat sit amet ipsum tristique mattis. Cras dolor ante, hendrerit vel suscipit a, pellentesque sit amet felis. Vivamus suscipit, tellus ut sollicitudin pulvinar, odio urna auctor quam, ut bibendum ipsum arcu ac nibh. Phasellus sollicitudin, ipsum at pretium consectetur, arcu nisi auctor quam, a lobortis erat neque viverra diam. Nam congue libero sed est gravida dignissim. Nulla pulvinar condimentum diam in porta. Aenean id interdum odio. Fusce cursus sagittis urna dictum scelerisque. Sed nunc massa, cursus et pharetra at, ullamcorper vel est. Aliquam erat volutpat. Ut accumsan commodo lorem, gravida rutrum diam venenatis eu.

stibulum nisl orci, viverra in sollicitudin sed, iaculis vel erat. Nam lacus quam, volutpat et porta non, consequat ac tortor. Fusce non lorem vitae libero imperdiet convallis. Morbi vestibulum viverra ligula, porttitor dapibus justo dictum ut. Pellentesque eget laoreet metus. Curabitur rhoncus consectetur nulla, id imperdiet nulla pellentesque sit amet. Cras sodales arcu ac orci suscipit pulvinar sollicitudin risus gravida. Praesent condimentum erat sit amet ipsum tristique mattis. Cras dolor ante, hendrerit vel suscipit a, pellentesque sit amet felis. Vivamus suscipit, tellus ut sollicitudin pulvinar, odio urna auctor quam, ut bibendum ipsum arcu ac nibh. Phasellus sollicitudin, ipsum at pretium consectetur, arcu nisi auctor quam, a lobortis erat neque viverra diam. Nam congue libero sed est gravida dignissim. Nulla pulvinar condimentum diam in porta. Aenean id interdum odio. Fusce cursus sagittis urna dictum scelerisque. Sed nunc massa, cursus et pharetra at, ullamcorper vel est. Aliquam erat volutpat. Ut accumsan commodo lorem, gravida rutrum diam venenatis eu.

CSS:
.highlighted {
    color: red;
}


text:
Q: What is the accuracy of a clustering algorithm? I have a set of points that I have clustered using a clustering algorithm (k-means in this case). I also know the ground-truth labels and I want to measure how accurate my clustering is. What I need is to find the actual accuracy. The problem, of course, is that the labels given by the clustering do not match the ordering of the original one.
Is there a way to measure this accuracy? The intuitive idea would be to compute the score of the  confusion matrix of every combination of labels, and only keep the maximum. Is there a function that does this?
I have also evaluated my results using rand scores and adjusted rand score. How close are these two measures to actual accuracy?
Thanks!

A: First of all, what does The problem, of course, is that the labels given by the clustering do not match the ordering of the original one. mean?
If you know the ground truth labels then you can re-arrange them to match the order of the X matrix and in that way, the Kmeans labels will be in accordance with the true labels after prediction.

In this situation, I suggest the following.

*

*If you have the ground truth labels and you want to see how accurate your model is, then you need metrics such as the Rand index or mutual information between the predicted and true labels. You can do that in a cross-validation scheme and see how the model behaves i.e. if it can predict correctly the classes/labels under a cross-validation scheme. The assessment of prediction goodness can be calculated using metrics like the Rand index.

In summary:

*

*Define a Kmeans model and use cross-validation and in each iteration estimate the Rand index (or mutual information) between the assignments and the true labels. Repeat that for all iterations and finally, take the mean of the Rand index scores. If this score is high, then the model is good.

Full example:
from sklearn.cluster import KMeans
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.datasets import load_iris
from sklearn.model_selection import LeaveOneOut
import numpy as np

# some data
data = load_iris()
X = data.data
y = data.target # ground truth labels
loo = LeaveOneOut()

rand_index_scores = []
for train_index, test_index in loo.split(X): # LOOCV here
   X_train, X_test = X[train_index], X[test_index]
   y_train, y_test = y[train_index], y[test_index]

   # the model
   kmeans = KMeans(n_clusters=3, random_state=0)
   kmeans.fit(X_train) # fit using training data
   predicted_labels = kmeans.predict(X_test) # predict using test data
   rand_index_scores.append(adjusted_rand_score(y_test, predicted_labels)) # calculate goodness of predicted labels

print(np.mean(rand_index_scores))

A: Since clustering is an unsupervised learning problem, you have specific metrics for it: https://scikit-learn.org/stable/modules/classes.html#clustering-metrics
You can refer to the discussion in the scikit-learn User Guide to have an idea of the differences between the different metrics for clustering: https://scikit-learn.org/stable/modules/clustering.html#clustering-performance-evaluation
For instance, the adjusted Rand index will compare a pair of points and check that if the labels are the same in the ground-truth, it will be the same in the predictions. Unlike the accuracy, you cannot make strict label equality.

A: you can use sklearn.metrics.accuracy as documented in link mentioned below
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html
an example can be seen in link mentioned below
sklearn: calculating accuracy score of k-means on the test data set


text:
Q: How to sum this this JSON data values below I am Imran, Please see the JSON data below and tell how to sum the result below:
{
    "_id" : "59ae33130d83f7001112ea5e",
    "user" : {
        "passcode" : "****",
        "operator" : "premiereservices",
        "phone_num" : "8587366808",
        "balance" : 1.99
    },
    "location_id" : "58ec4e82addba5001160fc07",
    "customer_id" : "premiereservices",
    "shopping_cart" : {
        "item_count" : 2,
        "items" : [
            {
                "customer_id" : "premiereservices",
                "barcode" : "666",
                "description" : "Test Item",
                "price" : 1.99,
                "taxable" : false,
                "fixed_price_tax" : 0.05,
                "__v" : 0
            },
            {
                "customer_id" : "premiereservices",
                "barcode" : "777",
                "description" : "Test Item",
                "price" : 1.99,
                "taxable" : false,
                "fixed_price_tax" : 0.05,
                "__v" : 0
            }
        ],
        "total_due" : 4.08
    },
    "cart_total" : 4.08,
    "Date" : "2017-09-04T23:16:03-06:00",
    "__v" : 0
}
{
    "_id" : "59ae38f186c7e70011a4e224",
    "location_id" : "58ec522a99da86001123ec47",
    "customer_id" : "premiereservices",
    "user" : {
        "phone_num" : "4129514766",
        "balance" : 0.03
    },
    "cart_total" : 3.55,
    "shopping_cart" : {
        "items" : [
            {
                "barcode" : "028400020008",
                "description" : "Smartfood White Cheddar Popcorn",
                "price" : 1.25,
                "taxable" : false,
                "tax_collected" : 0
            },
            {
                "barcode" : "012000286209",
                "description" : "Pureleaf Unsweetened Tea",
                "price" : 2.3,
                "taxable" : false,
                "tax_collected" : 0
            }
        ]
    },
    "Date" : "2017-09-04T23:41:05-06:00",
    "__v" : 0
}
{
    "_id" : "59ae3c569ce8ec00112775d6",
    "location_id" : "58ec522a99da86001123ec47",
    "customer_id" : "premiereservices",
    "user" : {
        "phone_num" : "7192358363",
        "balance" : 9.99
    },
    "cart_total" : 3.25,
    "shopping_cart" : {
        "items" : [
            {
                "barcode" : "10002",
                "description" : "GnG Burrito Bacon/GChili/Potato",
                "price" : 3.25,
                "taxable" : true,
                "tax_collected" : 0
            }
        ]
    },
    "Date" : "2017-09-04T23:55:34-06:00",
    "__v" : 0
}

Result Will be
cart_total: 10.88
price: 10.78
tax_collected: 0
Please anybody help me what will be the aggregate query functions

A: There you go:
db.collection.aggregate({
    $project: { // for each document...
        cart_total: 1, // ...keep the "cart_total" field
        price: { $sum: "$shopping_cart.items.price" }, // ...sum up all "price" fields
        tax_collected: { $sum: "$shopping_cart.items.tax_collected" } // ...sum up all "price" fields
    }
}, {
    $group: {
        _id: null, // group all documents into the same bucket and sum up a bunch of values
        cart_total: { $sum: "$cart_total" },
        price: { $sum: "$price" },
        tax_collected: { $sum: "$tax_collected" }
    }
}, {
    $project: {
        _id: 0 // remove the "_id" field
    }
})


text:
Q: How can I find the width and height of an object rendered on screen in THREE.js using an orthographic camera I have a THREE.js scene that I will be adding various meshes to that is rendered using an orthographic camera, like so:

I want to be able to find the width and height of the area that the object appears within on screen so I can draw an element in the DOM on top of the scene, like this:

Is this possible?
Many thanks!


text:
Q: How to matched object from main image with the template sub-Image using normxcorr2 I try to determine the coordinates of a puzzle piece on the original image using the normxcorr2 function. Then I draw a rectangle on the correspondence of the two elements. Unfortunately, I notice that the coordinates that this match has given me are not good. Could someone have an idea how to improve the use of this feature and get some better results.
The puzzle piece has the name "cpiece" and the original picture has the name "bild"
clear all;
close all;
clc

cpiece = im2gray(imread('cpiece1.jpg'));
bild = im2gray(imread('original.jpg'));

figure(1)
montage({bild,cpiece})

c = normxcorr2(cpiece,bild);
figure(2)
surf(c)
shading flat

[ypeak,xpeak] = find(c==max(c(:)));

yoffSet = ypeak-size(cpiece,1);
xoffSet = xpeak-size(cpiece,2);

figure(3)
imshow(bild)
drawrectangle(gca,'Position',[xoffSet,yoffSet,size(cpiece,2),size(cpiece,1)],'FaceAlpha',0);

A: It seems, the problem returns back to the  quality of your template image, And Check if the scales between original image and the template are exactly the same


text:
Q: Asp.Net : IHttpModule + m_context.Server.Transfer = session state error I have an IHttpModule that implements IRequiresSessionState.
The session state is at "on" on the page directive and I also added it to the web.config.
In the method "OnBeginRequest" in the IHttpModule, I make a Server.Transfer but I get the error :
Session state can only be used when enableSessionState is set to
true, either in a configuration file or in the Page directive.
When I access the page directly or with a Response.Redirect, there is no error.
Any idea?
Update :
The error occur in a page extending System.Web.UI.Page in the method InitializeCulture() which is an override.

A: Well, since I'm using DashCommerce, I used the Rewrite URL module instead and it worked fine.


text:
Q: Elixir - Cannot invoke remote function inside match I'm working through a practice exercise on exercism and can't figure out why I'm getting the following error:
(CompileError) anagram.exs:19: cannot invoke remote function String.codepoints/1 inside match
(stdlib) lists.erl:1353: :lists.mapfoldl/3
(stdlib) lists.erl:1353: :lists.mapfoldl/3

I guess I'm not understanding pattern matching as well as I thought because I don't quite understand how I'm trying to call a remote function inside a match. Here are a couple examples of the test suite for context:
defmodule AnagramTest do
  use ExUnit.Case

test "no matches" do
  matches = Anagram.match "diaper", ["hello", "world", "zombies", "pants"]
  assert matches == []
end

test "detect simple anagram" do
  matches = Anagram.match "ant", ["tan", "stand", "at"]
  assert matches == ["tan"]
end

Here's my code:
defmodule Anagram do
  @doc """
  Returns all candidates that are anagrams of, but not equal to, 'base'.
  """
  @spec match(String.t, [String.t]) :: [String.t]
  def match(base, candidates) do
    base
    |> String.codepoints
    |> Enum.sort
    |> scan_for_matches(candidates)
  end

  defp scan_for_matches(base, candidates) do
    Enum.scan candidates, [], &(if analyze(&1, base), do: &2 ++ &1)
  end

  defp analyze(candidate, base) do
    candidate
    |> String.codepoints
    |> Enum.sort
    |> match?(base)
  end

  defp match?(candidate, base) do
    candidate == base
  end
end

Am I not just passing variables through to the analyze/2 function so that it ultimately returns a boolean? I appreciate any insight.

A: This does need an answer, so I guess I'll add it in. match?/2 is a function exported from Kernel by default. You can override default imports via import Kernel, except: [match?: 2].


text:
Q: Coefficients in a linear combination general form My book gives the following linear combination of vectors
in an example
$r(1, 1, 0) +s(1, 0, 1) + t(0, 1, 1) = (a_1, a_2, a_3)$
It then says that
$r = \frac{1}{2}(a_1 + a_2 - a_3)$
$s = \frac{1}{2}(a_1 - a_2 + a_3)$
$t = \frac{1}{2}(-a_1 + a_2 + a_3)$
I'm confused as to how they actually came up with these equations? I'm lost ; how did they get those values for $r, s, t$ ?

A: Since$$r(1,1,0)+s(1,0,1)+t(0,1,1)=(r+s,r+t,s+t),$$they just solved the equation $(r+s,r+t,s+t)=(a_1,a_2,a_3)$, which is equivalent to$$\left\{\begin{array}{l}r+s=a_1\\r+t=a_2\\s+t=a_3,\end{array}\right.$$whose solutions are $r=\frac12(a_1+a_2-a_3)$, $s=\frac12(a_1-a_2+a_3)$, and $t=\frac12(-a_1+a_2+a_3)$.


text:
Q: Using RPUSH with TTL in a single command in Redis I'm trying to push an entry in a list in Redis and also want to update the TTL of the list every time a new entry comes in. I can do that my simple calling the EXPIRE "my-list" ttl using Redis. Since my application is receiving heavy traffic, I want to reduce the number of calls to redis.
Can I set my TTL during the push operation in Redis, i.e RPUSH "mylist" I1 I2...IN ex "TTL", does redis support this time of command functionality. I can see that it does support this for the String data structures.

A: Redis does not have dedicated commands to push and expire the List, although as you've mentioned it does have something like that for the String data type.
The way you'd go about this challenge is to compose your own "command" from existing ones. Instead of having your application call these commands, however, you would use a Lua script as explained in the EVAL documentation page.
Lua scripts are cached and run atomically on the server. One such as the following would probably help in your case - it expects to get the key name, the pushed element and the expiry value:
local reply = redis.call('RPUSH', KEYS[1], ARGV[1])
redis.call('EXPIRE', KEYS[1], ARGV[2])
return reply


text:
Q: Expecting JSON/XML data in Webapi when i request one webapi request, i got error like Expecting JSON/XML data
try
{
    string oRequest = _xml.UpdateInvereqxml(UserName, Password,OTAhotelid, Invy);
    string uri = @"service/update";
    System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
    req.Method = "POST";
    req.ContentType = "text/xml";
    System.IO.StreamWriter writer = new System.IO.StreamWriter(req.GetRequestStream());
    writer.WriteLine(oRequest);
    writer.Close();
    System.Net.WebResponse rsp = req.GetResponse();
    Stream istrm = rsp.GetResponseStream();
    string StreamReader = new StreamReader(istrm).ReadToEnd();
}

A: I suggest using HttpClient to communicate with ASP.NET Web API. The class provides many functions for working with REST service (example)
public EnumProduct Post(EnumProduct product)
{
HttpResponseMessage reponse = httpClient.PostAsJsonAsync("api/enumproducts/Post", product).Result;
if (reponse.IsSuccessStatusCode)
{
var enumProduct = reponse.Content.ReadAsAsync().Result;
return enumProduct;
}
else
return null;
}


text:
Q: ListView SectionIndexer's box is transparent In my app I'm using a listview with a section indexer that displays the letter of the current selection. It's fine on a lot of devices, but when I use my app on a Galaxy Tab running Android 3.2 the letter is displayed without the little box. I don't know how to make it appear or change the color of this letter.
I tried to use android:textColorPrimary but I didn't find how to use it and I find no sample.
To see my problem, below is a screenshot. If you look carefully, the letter G is in white above the second element of the list.

A: This is kind of a strange answer, because I fixed it, but I'm not sure why. When I set FastScrollEnable = true later than in the contructor of my derived ListView I get this behaviour aswell. Although, my letter is almost completly off the screen.
I'll probably get downvotes for this answer, but it saved me after 6 hours of prodding around. I noticed it when I removed my prototype code from our main classes to change the FastScrollEnable from outside.


text:
Q: OpenLayers Color an SVG Icon I have been following the Icon Colors example on the OpenLayers site, http://openlayers.org/en/latest/examples/icon-color.html?q=color.
This works well for me with png and jpg images, however when I switch to using svg images the color does not change at all. There are no errors. The color just does not change.
Here is the snippet of code where the color change happens:
    /*set the colour*/
    var style = new ol.style.Style({
        image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
            anchor: [0.5, 0.5],
            src : 'img/icons/example.svg',
            color: '#8959A8'
        }))
    });

Any advice would be greatly appreciated!

A: Apparently the fill property for your SVG needs to be white (#fff). The doc doesn't say anything about this but my conclusion is that any white (#fff) will be colorized with the value passed to the color attribute, independently of the type of the image.


text:
Q: memcpy with startIndex? I wish to copy content of specific length from one buffer to another from a specific starting point. I checked memcpy() but it takes only the length of content to be copied while I want to specify the starting index too.
Is there any function which can do this or is there any good approach to do it with the existing memcpy function?

A: An index is not required because you can simply update the source pointer by the specified number of bytes.  The following wrapper should do the trick
void* memcpy_index(void *s1, const void *s2, size_t index, size_t n) {
  s2 = ((char*)s2)+index;
  return memcpy(s1, s2,n);
}

A: Just add the offset you want to the address of the buffer.
char abuff[100], bbuff[100];
....
memcpy( bbuff, abuff + 5, 10 );

This copies 10 bytes starting at abuff[5] to bbuff.

A: Simply increase your pointer to your start index.
Example
const unsigned char * src = reinterpret_cast<const unsigned char*>(your source);
unsigned char * dest = reinterpret_cast<unsigned char *>(your dest);
memcpy(dest, src + offset, len);

What about using STL collections to avoid memory access errors?

A: Just add the offset to the addresses. For example, if you wanted to copy the buffer starting with the Nth byte:
memcpy( destination, source + N, sourceLen - N );

This will copy to the destination. If you also want to offset the destination - add the offset to both:
memcpy( destination + N, source + N, sourceLen - N );

A: I always prefer the syntax
memcpy( &dst[dstIdx], &src[srcIdx], numElementsToCopy * sizeof( Element ) );

A: This site needs a way to allow anonymous followups in addition to anonymous answers.
Why, more than once, do I see this insane assertion that an "index" must be in units of 1 byte?  It's the complete opposite of convention.  An "index" is usually symbolic, a measure whose physical byte offset is determined by the size of the element in the array (or vector, which may not even have the physical layout of an array, but then memcpy() is irrelevant too of course).
So, the 5th element in an array has "index" 5, but:

*

*If the array is type char, then the byte offset of that "index" is 5.

*If the array is type short (on x86), then the byte offset of that "index" is 10.

*If the array is type int (on x86), then the byte offset of that "index" is 20.

*If the array is type of some large 48-byte object, then the byte offset of that "index" is 240.

Which way is the correct way to access that specific element is a side point.  The important part is that you understand the difference, choose one, and make the code correct.

On the meaning of words, I would much rather read:
 void* memcpy_offset(void *s1, const void *s2, size_t offset, size_t n);

than:
 void* memcpy_index(void *s1, const void *s2, size_t index, size_t n);

I find the idea that a completely generic void * could have an "index" to be misleading.  (While we're here, "dest" and "source" or "in" and "out" would be much less ambiguous than "s1" and "s2".  Code doesn't need as many comments when you pick self-explanatory variable names.)

A: Simply add the index to the address of the buffer, and pass it to memcpy() as the source parameter, e.g. copy from 3rd item of buffer b
char a[10], b[20];
::memcpy(a,b+2,10);

Also take into account the type of items in the buffer, length (3rd) parameter of memcpy() is in bytes, so to copy 4 ints you shall put 4*sizeof(int) - which will probably be 16 (on a 32 bit system. But the type does not matter for the start address, because of pointer arithmetics:
int a[10], b[10];
::memcpy( a+2, b, 2*sizeof(int) );
// a+2 will be address of 3rd item in buffer a
// not address of 1st item + 2 bytes

A: You could have a function like below.
template<typename T>
T* memcopy_index(T* dst,T* src,unsigned int index, unsigned int element_count)
{
    return (T*)memcpy(dst,src + index, element_count * sizeof(T));
}

It can be used as below:
int src[]={0,1,2,3,4,5,6};
int dst[15];

memcopy_index(dst,src,2,5);    //copy 5 elements from index 2

You have to make sure that destination buffer has enough room to copy the elements.

A: If you're using c++, it is probably better to use std::copy() instead of memcpy(). std::copy can take pointers just as easily as iterators.
e.g.
int src[20];
int dst[15];

// Copy last 10 elements of src[] to first 10 elements of dst[]
std::copy( src+10, src+20, dst );

As with memcpy(), it's your responsibility to make sure the pointers are valid.
NOTE. If your usage is performance critical you may find a memcpy() as detailed in the other answers quicker, but probably not by much.


text:
Q: Having trouble with code to find average of an array of 10 random whole numbers Not sure if this is how I should post the problem I'm having - please give me pointers if so. Don't want to get it closed, so I will do my best. The task is to write code that finds the average of an array of 10 random whole numbers between 1-100. I've managed to get together some code to create an array of 10 random whole numbers between 1-100, which works. Next I got some code to find the average of a specified array of numbers, which also works. However, when I try to use that code to the find the average of the array of 10 random whole numbers between 1-100, it runs but gives an individual average for each number - not quite sure how it even calculates that. Hope someone can take a look and help me adjust the code so that it runs right.
Here is the code to create an array of 10 random whole numbers between 1-100 :
package Array.codejava;

import java.util.Random;

public class Array2 {

    public static void main(String[] args) {
        // range
          int max = 100;
          int min = 1;

          int[] list = new int[10];

            for(int i = 0; i < list.length; i++) {
              int randomNumber = (int) (Math.random() * 100);
              list[i] = randomNumber;

The code I have for finding an average of a specified array of numbers is -
package Array.codejava;

public class Average {
    public static void main(String[] args) {
        double score[] = {96, 92, 81, 54, 58, 13, 81, 6, 48, 67};
        int i, sum, avg;
        sum = 0;
        for(i=0; i<score.length; i++) {
            sum +=score[i];
        }

        avg = sum /score.length;
        System.out.println("The average of given Score:" +avg);

    }

}

Next when I combine the code (tried to adjust and make it work right), I get that problem I explained.
package Array.codejava;

import java.util.Random;

public class Array2 {

    public static void main(String[] args) {
        // range
          int max = 100;
          int min = 1;

          int[] list = new int[10];

            for(int i = 0; i < list.length; i++) {
              int randomNumber = (int) (Math.random() * 100);
              list[i] = randomNumber;

        // create instance of Random class
          Random randomNum = new Random();
          int random = min + randomNum.nextInt(max);
          System.out.println(random);

        // average
          int i1, sum, avg;
            sum = 0;
            for(i1=0; i1<list.length; i1++) {
                sum +=list[i1];
            }

            avg = sum /list.length;
            System.out.println("The average of given list:" +avg);

        }}}

Hope someone is able to help with this.

A: You can define a function to return an int[] populated with random integers and another function to return the average of these integers. I also recommend you use ThreadLocalRandom.current().nextInt(int origin, int bound) to get an int value between origin (inclusive) and bound (exclusive) so that you do not have to cast the generated random number.
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        // Test

        // Five random integers and their average
        int[] list = getRandomNums(5);
        System.out.println("Average of " + Arrays.toString(list) + ": " + getAverage(list));

        // Ten random integers and their average
        list = getRandomNums(10);
        System.out.println("Average of " + Arrays.toString(list) + ": " + getAverage(list));
    }

    static int[] getRandomNums(int n) {
        int[] list = new int[n];
        for (int i = 0; i < list.length; i++) {
            list[i] = ThreadLocalRandom.current().nextInt(1, 101);
        }
        return list;
    }

    static double getAverage(int[] list) {
        return Arrays.stream(list).average().getAsDouble();
    }
}

A sample run:
Average of [32, 22, 91, 48, 95]: 57.6
Average of [48, 33, 39, 22, 55, 11, 66, 58, 45, 23]: 40.0

Note that your code, (int) (Math.random() * 100) returns an int from 0 to 99, not from 1 to 100. If at all, you want to use Math.random(), you should use (int) (Math.random() * 100 + 1).


text:
Q: Angular 7, recursive object table rows Assume we have the following class:
export class MyClass {
    field1: string,
    next: MyClass
}

I have a table printing a list of MyClass but inside each item, there can be a next value.

     <ng-template #recursive let-current>
         {{cur.field1}}
     </ng-template>
     <ng-container *ngTemplateOutlet="recursive; context {$implicit: c}"></ng-container>

But im kind of stuck here cause i need to create another tr or some row but I cannot figure how..
Thanks.
Output Example:
 let classes = [];

let class1 = new MyClass();
class1.field1 = 1;
class1.next = new MyClass();
class1.next.field1 = 5;

let class2 = new MyClass();
class2.field1 = 3;

classes.push(class1);

    1

    5

    3

A: To achieve what you need, you can use nested ng-containers.
 <ng-container *ngFor="let c of _myclasses">
    <ng-container *ngTemplateOutlet="recursive; context {$implicit: c}"></ng-container>
 </ng-container>

 <ng-template #recursive let-current>

        {{cur.field1}}

    <ng-container *ngIf="cur.next">
         <ng-container *ngTemplateOutlet="recursive; context {$implicit: cur.next}"></ng-container>
    </ng-container>
 </ng-template>

Or maybe you can create a pipe that takes _myclasses and flatten it recursively and returns a one-level array of objects.

A: You did almost right, just a little correction:
 <ng-template #recursive let-cur="current">
     <ng-template [ngIf]="cur">

             {{cur.field1}}

         <ng-container [ngTemplateOutlet]="recursive"
             [ngTemplateOutletContext]="{ current: cur.next }">
         </ng-container>
     </ng-template
 </ng-template>

<ng-template ngFor let-item [ngForOf]="_myclasses">
     <ng-container [ngTemplateOutlet]="recursive"
         [ngTemplateOutletContext]="{ current: item }">
     </ng-container>
</ng-template>

But for may taste this looks weird and too complex. May be its better to just unroll that recursive class to a flat array before rendering?


text:
Q: FLOPS in Python using a Haswell CPU (Intel Core Processor (Haswell, no TSX)) I need to measure the FLOPS for analyzing a Python program I did.
Based on what I found on the Internet it seems like there are two main options:

*

*Including counters in the program (which, I understand, it may make sense if the program is very simple and you are able to get access to a very atomized computations).

*Using libraries that access the CPU counters to derive the number of FLOPS. Like this one: http://www.bnikolic.co.uk/blog/python/flops/2019/09/27/python-counting-events.html
Sadly, the installation fails and, on top of that, the website clearly states that the Haswell CPUs are not supported because they don't have counters for floating point calculations. It turns out my server has this CPU. Hence I am stuck over there.
Nonetheless, I was thinking about including a system call to use perf (maybe os.system("perf --event event_for_flops "))
The problem is I have no clue about what is the proper event to monitor for the FLOPS information (assuming there is one, which, based on the "python-papi" library seems quite unlikely).
I listed all the possible events, but I am quite lost there. I tried to find some information on the Internet, but it was not helpful.
Any idea on what is the proper event to monitor (if any)? Or how to do this, without manually adding a counter at the very low level of the code, which for my case is directly unfeasible.
Please find here the full list of events:
List of events of Haswell CPU obtained with perf list command


text:
Q: Coin weighing puzzle I have 4000 coins, 2000 coins weighing 1 gram and 2000 coins weighing 2 grams. I cannot tell the difference between these coins. However, I have a weighing scale (like a digital one, not a balance scale) that is fixed to some unknown integer N. 1 < N < 6001
This means that whenever I weigh a group of coins on this scale, it will show me one of two results. The first result it will show me is '$<$N' if the coins together weigh less than N. The second result it will show me is '$\geq$N' if the coins together weight at least as much as N.
How can I prove that I can find a set of coins that weigh exactly N grams? Furthermore, how can I prove that I can find this set in at most 10000 weighings?
My approach so far has been to add one coin at a time to the scale until it finally flips from '<N' to '>=N'
Now, we know that the group of coins on the scale weigh exactly N grams or N+1 grams.
Let us label these coins on the scale $a_1$, $a_2$, $\dots$ $a_M$. So there are M coins on the scale.
Next, remove coin $a_1$. If the scale stays at "$\geq$N", then we are done. If instead it shows <N, then we put coin $a_1$ back on to the scale. Repeat this for coins $a_2$ until coin $a_M$. If at any point the scale ever shows "$\geq$N" after removing a coin, we are done.
However, let's say that the scale never shows "$\geq$N" after removing any one of the M coins on the scale. Now, we have two possibilities.
The first possibility is that the coins on the scale sum to N+1, and that all the coins being weighed weigh 2 grams. The second possibility is that the coins on the scale sum to N.
And this is where I got stuck so I'd really appreciate some help.

A: As Lourrran points out you can save a few weighings by doing a binary search to get to $N$ or $N+1$ instead of adding one coin at a time.  You will get to $N$ with less than $20$ weighings.
As Brian Hopkins points out, if you have more than $2000$ coins on the balance when you get to $N$ or $N+1$ you are guaranteed to have a $1$ coin on the balance, so your technique of removing one coin will work to find $N$.  This will take at most $2001$ weighings because you will pull at least one $1$ gram coin by then.
The remaining case is that you have less than $2000$ coins on the balance when you get to the $N$ or $N+1$ case.  Take that many coins out of the ones that are left and weigh them.  Play around to find $N$ or $N+1$ with this batch.  If the numbers of coins that get you to $N, N+1$ differ, there are some $1$ gram coins in the larger group, so try that group one by one to find one or to find you are at exactly $N$.  If the numbers do not differ and add to $2000$ or less you might have all $2$ gram coins in both batches.  Make another batch from what is left and repeat.  You will eventually use over $2000$ coins total, so there will be some $1$ gram coins in any batch you want if they are all the same size, or in the largest batch if they are not.

A: Here's the solution.
When you know that the total weight is $n$ or $n+1$ and that an $n+1$ means that all coins are $2$ grams, you completed $t$ weighings when adding coins ($t$ is defined to be the number of coins on the scale at this stage) and $\max(t,2001)$ weighings when testing the removal of coins (we can stop after removing the $2001$st coin to get at most $6001$). Mark the coins that you know make $n$ or $n+1$ with an $O$ (there are $t$ marked coins at this stage.)
If $t$ is $1,$ since $n$ can't be $1,$ we know we're done. In the other case, start by replacing each $O$ coin by a blank coin one at a time. If the weight gets below $n$ for the first time after a replacement, then we can go back to before that replacement to get a set of coins that weighs exactly $n.$ If the weight is still above $n$ after the first round of replacement (by after the round of replacement I mean after all the previously marked coins were replaced), then we can mark all the blank coins on the scale with an $X$ and repeat, marking the coins with an $X$ for each successive round. If the initial weight was $n+1,$ then all the coins marked with $O$ are $2$ grams. Therefore, if the initial weight was $N+1,$ in each round, only a single $1-$gram coin can be marked $X,$ since marking two or more $1-$gram coins $X$ would mean that the weight dropped to $n-1$ or lower, at which point we would find a set with weight $n$ instead of marking. Since there are more $1-$gram coins that are not marked $O$ than $2-$gram coins that are not marked $O$ (if the initial weight before this process was $n+1$), at one point, we must have more $1-$gram coins on the scale than $2-$ gram coins. At this point, there are at least two $1-$gram coins on the scale, so we are done. This takes at most $4000$ weighings to reach. Therefore, an upper bound on the maximum possible number of weighings with this method is $t + t + 4000$ which is bounded above by $8000.$ If this process doesn't terminate with less than $n$ on the scale, then the original coins marked $O$ weigh exactly $n.$ Therefore, it is possible in at most $8000$ weighings.


text:
Q: displaying custom tooltip on chart points I am looking for a chat library where i can show custom tool tips on chart points. and can give click events on axis and points.
I have wasted lot of my time for Google all these but can't find all these feature in chart library.
Please suggest me chart api which have all such features.

A: Use Open Flash Chart 2
It's Basic features are :
It provides functions for custom Tool-tips, user interactivity and data exploration
you can re-size the charts
Can save the chart as an image
You can highlight or emphasize one (or many) points
You can Perform click events on it's elements.

A: You can use tooltips with Google's Visualization Chart. As an example, the following adds a tooltip to a bar chart:
function drawVisualization() {
    data = new google.visualization.DataTable()
    data.addColumn('string', 'Date');
    data.addColumn('number');
    data.addColumn({type:'string',role:'tooltip'});
    data.addRow();
    base = 10;
    data.setValue(0, 0, 'Datapoint1');
    data.setValue(0, 1, base++);
    data.setValue(0, 2, " This is my tooltip1 ");

    data.addRow();
    data.setValue(1, 0, 'Datapoint2');
    data.setValue(1, 1, base++);
    data.setValue(1, 2, "This is my second tooltip2");

    // Draw the chart.
    var chart = new google.visualization.BarChart(document.getElementById('visualization'));
    chart.draw(data, {legend:'none', width:600, height:400});
}