text:
Q: Retry try/catch on promise catch I am trying to run a script with the firebase admin sdk that is looping through all my users with listUsers() and I am handling it like so:
admin.auth().listUsers(batch, nextPageToken)
    .then(function(listUsersResult) {
        // process successful results
    })
    .catch(function(error) {
        // log the error
    });

Every now and then the call to listUsers itself fails with error Error: www.googleapis.com network timeout. Please try again.
I catch the error, but my script will not continue after this.
I have used retry before in this situation, but am wondering if or how I could continue from the same batch/token of users that I am on without having to restart my listUsers loop. Maybe I am missing something really easy?

A: I'm not sure if i got you right.
You want to retry on a error with same arguments ?
Manually you would do that like this:
function fun(batch, nextPageToken, retries = 5) {
  return admin
    .auth()
    .listUsers(batch, nextPageToken)
    .then(listUsersResult => {
      // process successful results
    })
    .catch(error => {
      if (err.code === 'ETIMEDOUT' && retries > 0) {
        const turnsLeft = retries - 1;
        return fun(batch, nextPageToken, turnsLeft);
      }
      throw error;
    });
}

But you should use some library for that.

A: Here is a perfectible base to work from:
const withRetry = async (fn, maxAttempts, args, fails=0) => {
    // fn: function that needs retry on error,
    // maxAttempts: maximum of try attempts
    // args: arguments to be passed to the function it could be a single value, an array or an object it depends on how you use it inside "fn"
    // fails: amount of failed attempts to simulate in order to test the retry mechanism

    const retry = async (attempt=1) => {
        let result = undefined;
        console.log(' • attempt:', attempt); // logs attempt #

        try {

            if (attempt <= fails) { // attempt inferior or equals to the defined amount of failures
                result = await fn(args);
                throw new Error("   Expected to fail"); // force a failure by throwing
            }

            else
                result = await fn(args);

        } catch (err) {

            console.log(err.message);

            if (attempt < maxAttempts) {
                // if you want to define some delay before retrying it goes here

                return retry(attempt + 1); // RETURN AND RETRY HERE

            } else if (attempt == maxAttempts) {
                console.log("\n> Error: max attempts have been reached without success");
                return 'err'; // RETURN "err" IN CASE OF MAX ATTEMPT REACHED
            }

        }

        console.log('   operation was a success: ');
        return result; // RETURN SUCCESS
    }

    return await retry();

}

Below is some code to test it :
async function codeToRetry(args) { // will be used as argument when calling withRetry()
    let delay;

    if (args != null && args.delay)
        delay = args.delay;
    else
        delay = 1000;

    await new Promise(_r => setTimeout(_r, delay));
    return '\x1b[92;1m' + '   some value' + '\x1b[0m';
}

async function test() {
    console.log('> first test:');
    let result = await withRetry(codeToRetry, 5, {delay: 2000}); // will success on first attempt
    console.log(result);

    console.log('\n> second test:');
    result = await withRetry(codeToRetry, 5, null, 2); // will success on 3rd attempt
    console.log(result);

    console.log('\n> third test:');
    result = await withRetry(codeToRetry, 2, null, 2); // will fail by exceeding the amount of attempts which is 2
    console.log(result);
}

test();

It will produce the following output:

> first test:
 • attempt: 1
   operation was a success:
   some value      ------ returned value

> second test:
 • attempt: 1
   Expected to fail
 • attempt: 2
   Expected to fail
 • attempt: 3
   operation was a success:
   some value      ------ returned value

> third test:
 • attempt: 1
   Expected to fail
 • attempt: 2
   Expected to fail

> Error: max attempts have been reached without success
err                ------ returned value


text:
Q: Resize the image to div I have this code:

.post-container {
  overflow: auto
}

.post-thumb {
  width: 300px;
  height: 300px;
  overflow: hidden;
}

.post-thumb img {
  min-width: 100%;
}

I want to show an Image who shouldn't get stretched. But right now the side creates a scrolling box to scroll the image in the width because the image is very long.

A: can you try :
.post-thumb img {
  width:100%;
  min-height: 1px;
  display: block;
}

Tell me if this helps you or changes something.

A: You can scale your image using a CSS style:
.post-thumb img{
  transform: scale(2,6); // example scale ( width, heigth )
}

Note: first look how browsers support this

A: I would suggest regular responsive setup as in
.post-thumb img {
  display: block;
  max-width: 100%;
  height: auto;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio Asp.net Website Compilation error: Child nodes not allowed "Child nodes not allowed" seems to be notorious compilation error on Asp.net website if you do some googling.
Environment: WinXp, VS2008 and VS2008 SP1, .NET 3.5 SP1
Behavior: create a brand new Asp.net website (not web application), then just build it, you got compilation error "Child nodes not allowed" on the Web.config on line where it says providerOption name="CompilerVersion" value="v3.5"/>
I got this problem after I re-installed vs2008.  Now, a lot of people are suggesting fixes but none worked for us.  Only one guy mentioned he successfully got rid of this problem by re-installing windows, but we don't want to go that far if we don't have to.  There is another person who opened a ticket to MS but hasn't gotten back a response yet.
If there is anyone out there who has similar environment like us and know how to get around this problem, we'd really appreciate it!!!
Edit  The weirdest part of all this is that I don't know how I got it.  It is a brand new box and brand new installation.

A: My colleague just found a fix for this dreadful problem, it is a .NET Framework Cleanup Utility at http://cid-27e6a35d1a492af7.skydrive.live.com/self.aspx/Blog|_Tools/dotnetfx20|_cleanup|_tool.zip
Just download, run and restart your machine and re-install .NET Framework 3.5 SP1 (since the cleanup util removes all the .NET Frameworks for you)!  Really hope this could help others who have the same problem, it's been 4 days fighting with this one issue, thanks Microsoft!
Thank you guys very much for your input, I voted up for you both, appreciate it!
Ray.

A: You probably need to reinstall Visual Studio 2008 SP1.

A: I haven't got that specific error, but try the following (if you haven't already):

*

*Since you re-installed the vs 2008, try re-applying the SP1

*Clear all the asp.net temporary folders it generates for the web sites.


text:
Q: Combine 3 WiFi routers into one network I have 3 WiFi routers. I want them to all work together to make one network all throughout the house.
Router A: Actiontec PK5000 (DSL modem/router combo)
Router B & C: TP-Link TL-WR841N
Ethernet switch: Netgear FS105
Router A is connected directly to the internet because it's also a modem.
One Ethernet cable goes from Router A to an Ethernet switch. From the switch, one Ethernet cable goes to Router B, and another goes to Router C.
Currently, I have them all set up with different SSIDs. I'd like them all to be one network with three different access points (I think that's the term?).
[Router A]-----------------[ethernet switch]
                              |          |
                        [Router B]   [Router C]

None of the WiFi networks have passwords because this is a really rural area and there is simply no need.
I want all 3 WiFi networks to work together to create one WiFi network with one SSID. If possible, I also want a printer connected to Router A to be able to be used by a device connected to any other routers.
I think that there's something about turning off DHCP on Router B and C and then... I'm not sure what exactly.
Also, the router control panel IPs are set to:
Router A: 192.168.0.1, Router B and C: 192.168.1.1
Any guidance would be appreciated, thanks.

A: The steps you need to take are:

*

*Make sure TP units are connected via LAN not WAN port.

*Disable DHCP on both TP units

*Assign the TPs static IPs within the range of the Actiontec, eg 192.168.0.250 and 192.168.0.251 (Currently they are conflicting)

*Replicate the SSID across all 3, but use different channels (eg CH1, CH6, C11)

Devices will then all "see" each other and roam relatively smoothly.


text:
Q: Sort 4 ints, smallest to biggest Suppose I have 4 integers.
int a = 4;
int b = 2;
int c = 4;
int d = 1;

How can I sort these integers from smallest to biggest. The output needs to be something like this:  d, b, a, c Most methods of sorting only give me the value of the sorted integer. I need to know the name.
Edit: Well, I'm writing an AI algorithm. I have 4 ints that store direction priority. (If the AI comes into a wall, it chooses the next best direction). So, I need to find the lowest int, and if the AI can't move that way, I choose the second to lowest etc.

A: There appears to be some confusion here; in your example a is not the "name" for the value 4, it is the name of an integer variable which currently contains 4. In other words "a" is not part of the data of your program.
What I assume you mean is you have name/value pairs which you wish to sort using the value as key. A common way to do this is to define a type for your pair, create a collection, and sort the collection.
In plain C you can declare:
typedef struct
{
   char *name;
   int value;
} MyPair;

You can create an array of these and sort it using standard C functions for array sorting, using just the value field as the key.
In Objective-C you can declare a class for your pair:
@interface MyPair : NSObject
{
   NSString *name;
   int value;
}

// methods/properties

@end

You can create an NSMutableArray of instances of MyPair and then sort the array, again you just use the value property (or instance variable) when doing the comparisons for the sort algorithm.
There are other variations of course. Once sorted you can iterate through the sorted array and display the name field/property.

A: Here is an objective-c approach.  Unfortunately, you will not have the fun of writing the AI portion, the sorting is built into the libraries already.
int north = 1, south = 3, east = 2, west =4;

  NSDictionary * nDict = [NSDictionary dictionaryWithObjectsAndKeys:@"north", @"name", [NSNumber numberWithInt:north], @"value", nil];
  NSDictionary * sDict = [NSDictionary dictionaryWithObjectsAndKeys:@"south", @"name", [NSNumber numberWithInt:south], @"value", nil];
  NSDictionary * eDict = [NSDictionary dictionaryWithObjectsAndKeys:@"east", @"name", [NSNumber numberWithInt:east], @"value", nil];
  NSDictionary * wDict = [NSDictionary dictionaryWithObjectsAndKeys:@"west", @"name", [NSNumber numberWithInt:west], @"value", nil];

  NSArray * toBeSorted = [NSArray arrayWithObjects:nDict,sDict,eDict,wDict,nil];
  NSArray * sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"value" ascending:NO]];
  NSArray * sorted = [toBeSorted sortedArrayUsingDescriptors:sortDescriptors];
  NSLog(@"sorted %@", sorted);

Output
2012-01-23 19:50:21.079 TestEnvironment[19792:207] sorted (
        {
        name = west;
        value = 4;
    },
        {
        name = south;
        value = 3;
    },
        {
        name = east;
        value = 2;
    },
        {
        name = north;
        value = 1;
    }
)

Now you can check the highest priority by
NSString * highestPriority = [[sorted objectAtIndex:0] objectForKey:@"name"];

Now you have some classes you can look up (NSArray, NSDictionary, NSSortDescriptor, NSNumber)

A: You've tagged this Objective-C, but you haven't written anything that suggests using Objective-C. If you want to use Objective-C, I'd put the elements into an NSMutableArray (they'll need to be converted to NSNumbers to do that), and have the array sort them, as seen here.
If you just want to put them into a straight C array, you could sort them using heapsort (), qsort(), or mergesort().


text:
Q: Help with comparing to array values in JavaScript I have developed this code with help from you guys here on stackoverflow.  I have added an extra part to it where it compares two numbers from two different arrays, in this case offhire1 and pro2.
The problem is in my code where I have:
(offhire1[i].value > pro2[i].value)

It only allows me to contine if the numbers match i.e 100=100. But what I'm after is identifing any numbers that are greater than the value only 120 > 100.  I have tested if the values are being passed and they are.
What is my mistake here can anyone suss it out.
function validateoffhire(form) {
  var num1 = document.getElementById('num1');
  var test2Regex = /^[0-9 ]+(([\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;

  var accumulator = 0;
  var num2 = num1.value;
  var i=0;
  var offhire1 = [];
  var pro2 =[];
  for(var i = 0; i < num2; i++) {
    offhire1[i] = document.getElementById('offhire1' + i);
    pro2[i] = document.getElementById('pro2' + i);
    var offhire2 = offhire1[i].value;
    // var pro3 = pro2[i].value;

    if(!offhire2.match(test2Regex)){
      inlineMsg('offhire1' + i,'This needs to be an integer',10);
      return false;
    }
    else if (offhire1[i].value > pro2[i].value) {
      alert("You entered: " + pro2[i].value)

      inlineMsg('offhire1' + i,'You have off hired to many items',10);
      return false;
    }
    else{
      accumulator += parseInt(offhire2);
    }
  }
  if(accumulator <= 0){
    inlineMsg('num1' ,'You have not off Hired any items',10);
    return false;
  }

  return true;
}

A: I'm not quite sure I follow you.  If the numbers are the same, the statement won't match.
One issue in your code is that you're comparing strings, not numbers.  You may want to change it to:
(parseInt(offhire1[i].value) > parseInt(pro2[i].value))


text:
Q: Identify numbers in mixed formats within a string in C I have the following string:
 char *line;
 char temp_line;

After some processing my pointer line pointing to temp_line contains the following string:
 "H2 + CH = CO2      4.00e-003     3.00e10     43.00"

I need a routine which can identify the three numbers you see. I can always assume there will be three different numbers. But I cannot assume  that all three numbers are given in exponential form.
What is the best way to achieve this in C?
Is there a way to let C read the line reversely, and instruct it to extract the last three figures of that line?

A:
Is there a way to let C read the line reversely, and instruct it to extract the last three figures of that line?

Sure, parse the string and save last 3 successful conversions.
The below does consume s.
// Return parse count;
int read_last_3_double(char *s, double y[3]) {
  const char *delimiters = " \n\t";
  int i = 0;
  char *token = strtok(s, delimiters);
  while (token) {
    char *endptr;
    double x = strtod(token, &endptr);
    // If no conversion or fails to end with a null character.
    if (token == endptr || *endptr) {
      // No conversion
      i = 0;
    } else {
      if (i == 3) {
        y[0] = y[1];
        y[1] = y[2];
        y[2] = x;
      } else {
        y[i++] = x;
      }
    }
    token = strtok(NULL, delimiters);
  } // endwhile
  return i;
}


text:
Q: Module can only be default-imported using the 'esModuleInterop' flag i am getting this error Message. I tryed to change the Conifg but it didnt change the Output of the error
These error Message started to come up as soon as i imported erthers form hardhat
node_modules/@nomicfoundation/ethereumjs-evm/dist/types.d.ts:8:13-error TS1259:  Module '"/demo-app-seller/node_modules/@types/async-eventemitter/index"' can only be default-imported using the 'esModuleInterop' flag
node_modules/@types/async-eventemitter/index"' can only be default-imported using the 'esModuleInterop' flag

8 import type AsyncEventEmitter from 'async-eventemitter';
              ~~~~~~~~~~~~~~~~~

  node_modules/@types/async-eventemitter/index.d.ts:20:1
    20 export = AsyncEventEmitter;
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    This module is declared with 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

Found 1 error in node_modules/@nomicfoundation/ethereumjs-evm/dist/types.d.ts:8

and my TSConfig looks like that
{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "strict": true,

  },
  "exclude": ["dist", "node_modules"],
  "include": ["./test", "./src", "./scripts"],
  "files": ["./hardhat.config.ts"]
}

Can you guys help me out ?
i tried these in the config
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,


text:
Q: I can't guess what the file format is App exports data in strange way, it says it is .edi but it doesn't look like .edi...
I want to make an xml from it or something that I could use in my android app.
In my app I want to make select like "select from [Document] from Poz where Symbol=getSymbol();"
Here is an example of it:
[Dokument]
Rejestr=FakturyZak
[ZawartoscDokumentu]
[Poz1]
Nazwa=postionon1
Symbol=123
CenaNetto=0.96000
[Poz2]
Nazwa=position2
Symbol=12345
CenaNetto=0.96000
[Poz3]
Nazwa=position3
Symbol=1281
CenaNetto=14.11000

It should works like I write down 12345 and it will give me all CenaNetto of the position2 fields from all [Dokument] statements
The problem is that I've got plenty of statements like [Dokument], there is no ID and so on that I can iterate over it, also I've got other statements like [Info], [Pakiety]..

A: This is structured like a lot of configuration files.
Should be fairly easy to use (lots  of libraries).
It is not one of the commonly used edi standards (edifact, x12 etc)
But a lot of ERP software uses an internal format (inhouse format) for import/export. Translation from/to eg edifact is done by edi translator.
Hope this helps.


text:
Q: Python inheriting base class variable If I inherit a class variable from a base class, and then want to use that variable as a default parameter in a method in my child class, how do I access it?
def get_records_by_domain(self, domain, search_period_days=self._X):

where _X is a variable in a parent class that is instantiated in the init of the child class?
When I try to test this function, I get the error:
NameError: name 'self' is not defined


text:
Q: Rotate screen when HTML5 video playing in fullscreen First of all, i would like to apologize for my bad level in english, and for all the  mistakes i might have done in this post.
I'm also a "junior" in Android devloppement (i'm doing this on my free time), i'm not good and experienced enough yet ^^ so sorry if i might have some difficulties to understands the answer you might give me.
So what i'm doing ?
I'm creating a simple Android App. It's just a Webview to load my website.
My website is just a random Youtube video player.
First i had the problem to play HTML5 Video in Fullscreen. I succeed to done that with this project VideoEnabledWebView
So my app is exactly the same as VideoEnabledWebView.
What is my problem ?
I block the screen rotation in my app. Only "Portrait" mode and i succeed to done that.
But when i play a video in fullscreen mode, i can't be in landscape mode. I understand why, but i can't find a solution, a hack to able to do that.
So i would like to rotate the screen in landscape mode only if i'm playing the video in fullscreen.
First, Here is my MainActivity.java :
public class MainActivity extends ActionBarActivity
{
    private VideoEnabledWebView webView;
    private VideoEnabledWebChromeClient webChromeClient;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        webView = (VideoEnabledWebView)findViewById(R.id.webView);

        View nonVideoLayout = findViewById(R.id.nonVideoLayout); // Your own view, read class comments
        ViewGroup videoLayout = (ViewGroup)findViewById(R.id.videoLayout);

        View loadingView = getLayoutInflater().inflate(R.layout.view_loading_video, null); // Your own view, read class comments
        webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, loadingView, webView) // See all available constructors...
        {
            @Override
            public void onProgressChanged(WebView view, int progress)
            {

            }
        };
        webChromeClient.setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback()
        {
            @Override
            public void toggledFullscreen(boolean fullscreen)
            {
                if (fullscreen)
                {
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14)
                    {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
                    }
                }
                else
                {
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14)
                    {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                }

            }
        });
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(new myWebViewClient());

        webView.loadUrl("https://www.awesomekraken.com/fr");
    }

    public class myWebViewClient extends WebViewClient
    {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    }

    @Override
    public void onBackPressed()
    {
        if (!webChromeClient.onBackPressed())
        {
            if (webView.canGoBack())
            {
                webView.goBack();
            }
            else
            {
                super.onBackPressed();
            }
        }
    }
}

As you can see in the onCreate method, i put the line :
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

I think it's in this part i can resolve my problem :
 webChromeClient.setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback()
        {
            @Override
            public void toggledFullscreen(boolean fullscreen)
            {
                if (fullscreen)
                {
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14)
                    {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
                    }
                }
                else
                {
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14)
                    {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                }

            }
        });

I tried to put setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); under the if(fullscreen) but that doesn't work. The app switch in Landscape for a half second and the webview reload the all page.
I searched a lot on Google & StackOverflow but from now i found nothing very helpfull.
Only this post is the same as mine, but he got no any answer.
If anyone have a solution, tip or advice ...
Of course, i will update this post if i get more information, or solve my problem.
Thanks in advance for your help !

A: I ended up in rotating the custom view container:
public class RotatedVerticalFrameLayout extends FrameLayout{

    public RotatedVerticalFrameLayout(Context context, AttributeSet attrs){
        super(context, attrs);
    }

    @SuppressWarnings("SuspiciousNameCombination")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        int w = getWidth();
        int h = getHeight();

        setRotation(90.0f);
        setTranslationX((h - w) / 2);
        setTranslationY((w - h) / 2);

        ViewGroup.LayoutParams lp = getLayoutParams();
        lp.height = w;
        lp.width = h;
        requestLayout();
    }
}

This looks like landscape mode if you only show the custom view instead of actionbar and other contents.


text:
Q: How to assign a variable in a switch statement in typescript? I want to use a switch statement to assign a new variable some value.
Example:
let name: string

switch(index) {
    case 0:
       name = "cat"
    case 1:
       name = "dog"
    ....
}

But it is telling me 'name' is declared but its value is never read. Not sure how to fix this...anyone know the proper way to go about this?


text:
Q: How do you put the text from a string into code? I am trying to make a one line JavaScript code software and right now it looks perfectly fine... until you hit the run button. Instead of running the code (like it's supposed to), it does absolutely nothing. So yeah, you can see the problem I am having with this.
Here's my HTML (in case you want to look over it):
<!DOCTYPE html>

      <input type="text" id="codeInput" placeholder="document.write(`Hello, world!`)" value="document.write(`Hello, world!`)" class="code">

      <button onclick="convertString()">Run</button>

Here's my JavaScript:
function convertString () {
  let code = document.getElementById("codeInput").value
  document.getElementById("code").innerHTML = code
}

And here's my CSS (not sure why I put this in here, but you can look over it if you want to):
.code {
  color: #162;
}
.default {
  display: block;
  margin: 8px;
}

So uhh... I'm having trouble. can you please help me?

Thank you!

Edit 1 (4 Jul 2020): No, this is not the same as stackoverflow.com/questions/1197575. S/he was trying to use onload="" to do a  inside the onload="". I am trying to call a function with a separate run function in my JavaScript and using a separate  tag.

A: In your html code, you're referring to a function (convertString()) which is defined outside the html page, in a separate file. You need to reference the JS file from your HTML page


text:
Q: The preposition 'Of' as in 'House of Cards' I got two questions regarding the usage of the preposition 'of.'
First is when we say 'a house of cards' do we mean either of or only one of the following?:

*

*I am referring to a house made of cards

*I am referring to a house that belongs to cards, metaphorically speaking.

1 or 2 or either 1 or 2?
Second question is that when we say 'a cup of coffee,' I am referring to a cup that contains coffee; then the question is whether or not the preposition "of" in "a cup of coffee" works the same way as the "of" in, for example, "Such a jerk of a guy!" or "both of you."
I reckon either 1 or 2 is correct depending on the context; the 'of' in 'a cup of coffee' works the same as when you say "a picture of a bear" looking at a picture that shows a bear.

A: The preposition of can express a lot of different relationships. Some have special names such as partitive genitive (a cup of coffee, how much of what), others have no standard name.
Longman's DCE lists 25 relationships expressed by of.  http://www.ldoceonline.com/dictionary/of
See also: https://en.m.wikipedia.org/wiki/Genitive_case


text:
Q: Calculate the distance within php or js? First of all, I am not sure this question should be in stackoverflow or other stackexchange network. So if wrong place just move for me.
It is better to calculate the distance between 2 points of lat/lng in DB or js?
Since Google maps provide computeDistanceBetween(). This is really easy to use, but i am thinking if i have 10000 rows and only 5 rows are within the distance and to display into the map.
Any idea?

A: If your question is only about where it should be calculated then I prefer client side. It is simple, fast, more flexible and dinamic, and you unload your server.

A: Without knowing much about your problem, I'd probably go with doing calculation-intensive tasks on the client side (or "in JS"). This will never put too much load on your server-side application, by distributing it among clients.
Of course there are many variables you have to take into account to choose the best approach.
Other things you may consider:

*

*doing it server-side and caching the results,

*using google-api and also caching it on your server,

*many many more...

A: It depends to the frequency of calculations.
If your points are permanent then you can calculate all required distances only once before inserting the row into table and save the calculated result to provide it to clients later.
But if calculations are repeatable and coordinates of points will be changed eventually then it's better to use client-side calculations.
Really it's not that hard task for browser to execute some JavaScript which will calculate distances even for a lot of points.
Also if you have really tons of input data you can consider some background pre-calculations on client-side and caching of results in localStorage* so your users will never wait.
* store.js could help you to ensure cross-browser compatibility.

A: Where it is better to calculate distance is completely dependent on your application. If you the client has the information then it is better in JS.
In this scenario you appear to be trying to calculate the nearest points stored in your database to a given point. This is most certainly better handled by the database using geospatial indexes.
The typical algorithm narrows down the result set with a unsophisticated approach. Within x & y +/- 10KM and then with that result set do a full calculation.
I would say if your information is in the database then look into using built in geospatial tools for your DBMS.


text:
Q: Content being cropped when scaling a div I'm trying to make a div that can be zoomed in on using the 'scale' property. However, when I scale up an image, it scales fine, however the outsides of the image are being cropped and I can't scroll around the page to see the rest of the image for some reason.
Example on codepen:
http://codepen.io/anon/pen/xLGFl
So if you look at Greenland for example, and then you click the 'in' button, you'll see after the image has been scaled, 90% of Greenland disappears and you cannot scroll back up to view the missing part of Greenland or anywhere else on the map, which is what I want to be able to do.
I've tried things like adding background-size:cover and 100% 100%, I've tried adding overflow:auto, I've tried putting the image in an image tag within the map-container div and I've tried putting another div around the map-container div that has a fixed width and height with overflow:auto on it but I'm getting the same results every time.
Any help with this is much appreciated!
EDIT WITH SOLUTION:
To fix it, I used Candlejack's solution and change my zoomIn() function by setting a variable to change the top/left position depending on how far it was zoomed in. I had to do trial/error to get the right values for my site. I also had to use the same code below (with zoomMargin changes in the switch statement) in my zoomOut() function to change back to the previous zoomMargin value.
var zoomMargin = 0;
function zoomIn(){
    //get the id of the element to be scaled and scale it using GSAP
    var mapContainer = document.getElementById("map-container");
    TweenMax.set(mapContainer,{transformOrigin: "50% 50%"});
    TweenMax.to(mapContainer, 0.4, { scale: "+=1"});
    console.log("scale: "+mapContainer._gsTransform.scaleX);
    //switch between the scale value (the scale value in my switch statement is from the GSAP library)
    switch(mapContainer._gsTransform.scaleX){
        case 1:
            zoomMargin = 24.9;
        break;
        case 2:
            zoomMargin = 33.3;
        break;
        case 3:
            zoomMargin = 37.5;
        break;
        case 4:
            zoomMargin = 39.9;
        break;
        case 5:
            zoomMargin = 41.6;
        break;
    }
    $('#map-inner-container').css( "top", zoomMargin+"%" );
    $('#map-inner-container').css( "left", zoomMargin+"%" );
}

HTML:

A: I took the background image out of your #map-container and placed it in the markup as an img - as shown here.
This allows scrolling to the full extent of the image, regardless of zoomed level.
You may need to tweak the image styling to resemble your original design, but this should at least solve the immediate scrolling issue.
EDIT:
New version here: http://codepen.io/anon/pen/eHDmG
Added position: relative to the img CSS, and then altered the top rule in the JS functions for zoomIn/zoomOut.
So far I've used static values of 20% and 0% to demonstrate the point - it only really looks good the first time you zoom in. Ideally these values should be set dynamically depending on which zoom depth you are at. You could set a variable to store an integer which increments every time the user zooms in and decrements every time the user zooms out, and then calculate an appropriate top position value depending on this variable.


text:
Q: Listview setOnItemClickListener - Not working for custom listview but working into simple listview I have problem with the get the listview item when click listitem.
I Got listview item for the simple listview(Arrayadapter), but I have face problem for the custom listview.
I am using
listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {

  //String  selectedFromList = (String) listview.getItemAtPosition(pos);
   String  selectedFromList = (String) adapter.getItem(pos);

    System.out.println("selected value >> >> >> >> >> >>"+selectedFromList);

    SelectedAnswer.setAnswer(selectedFromList);

              }

          });

Into Logcat give me the null value :
I/System.out( 1238): selected value >> >> >> >> >> >>null

main.class
 protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quiz_questions);

        listview = (ListView) findViewById(R.id.questions_list);

        GoToNextQuestion();
  }

private void GoToNextQuestion() {
    // TODO Auto-generated method stub

     currentGame = ((Quizapplication)getApplication()).getCurrentGame();
    currentQ = currentGame.getNextQuestion();

       setQuestions();

    listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {

  //String  selectedFromList = (String) listview.getItemAtPosition(pos);
   String  selectedFromList = (String) adapter.getItem(pos);

    System.out.println("selected value >> >> >> >> >> >>"+selectedFromList);

    SelectedAnswer.setAnswer(selectedFromList);

              }

          });

}

 private void setQuestions() {

    // set the available options
    List<String> answers = currentQ.getQuestionOptions();
    System.out.println("value of the options >>>>>>>>>>>>>:"+answers);

     //ArrayAdapter< String> myadapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_single_choice ,answers);

    //ArrayAdapter< String> adapter = new ArrayAdapter<String>(this, R.layout.quiz_questions_listitem, answers);

             // working for the simple adapter

      adapter = new ListviewAdapter(this,answers);

     listview.setAdapter(adapter);
     //listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

 }

EDIT:
 public class ListviewAdapter extends BaseAdapter{

public List<String> Questions;

public Activity context;
public LayoutInflater inflater;

public ListviewAdapter(Activity context,List<String> answers) {
    super();

    this.context = context;
    this.Questions = answers;

    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return Questions.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public static class ViewHolder
{

    TextView txtquestion;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    ViewHolder holder;
    if(convertView==null)
    {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.quiz_questions_listitem, null);

        holder.txtquestion = (TextView) convertView.findViewById(R.id.textView_option);

        convertView.setTag(holder);

      /*  convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>"+v.toString());
                notifyDataSetChanged();

                 SelectedAnswer.setAnswer(v.toString());
            }
        });*/
    }
    else
        holder=(ViewHolder)convertView.getTag();

    holder.txtquestion.setText(Questions.get(position));

    return convertView;
}

}

A: You probably return null from the getItem() method of your custom adapter, ListviewAdapter(you should add the code for the adapter). Also, there is no need to set the listener on the ListView again.
Modify your getItem() method like this:
@Override
public Object getItem(int position) {
    return Questions.get(position);
}

A: Try to do this for your list :
list.setItemsCanFocus(false);

and make sure that items inside your list had attributes
android:focusable="false"
android:focusableInTouchMode="false"

A: you may select wrong adapter, try this
String  selectedFromList =  myAdapter.getItemAtPosition(pos).toString();

A: Use  this
   public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {

   String  selectedFromList = myAdapter.getItemAtPosition(pos);

  System.out.println("selected value >> >> >> >> >> >>"+selectedFromList);

  SelectedAnswer.setAnswer(selectedFromList);

          }

      });

A: try to Do this.
public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {

  //String  selectedFromList = (String) listview.getItemAtPosition(pos);

   ListviewAdapter adapter=(ListviewAdapter) listview.getAdapter();
   String  selectedFromList = (String) adapter.getItem(pos);

    System.out.println("selected value >> >> >> >> >> >>"+selectedFromList);

    SelectedAnswer.setAnswer(selectedFromList);

              }

          });


text:
Q: Set Twig variable inside an include and use it afterward imagine you have a twig template (tplA.twig) that include an other one

Twig template A

{% set test = "in tpl A" %}

first, variable is: {{ test }}

{% include "tplB.twig" %}

and the variable is: {{ test }}

and the included template (tplB.twig)

Content of tpl B

{% set test = "now is tpl B" %}

What is the best way to set/change a variable in an included template and use it in the master template? How to use globals? Note that I can't use blocks and extends, and I'm not using Symfony.
Many thanks
EDIT
The real context is a very basic multilingual structure. For a page, I have one master template:

{{ i18n('mainTitle') }}

current language (fr, en): {{ ln }}

        localized A

        localized B

It is a very small website, so I didn't created a complex structure with database, and I wanted to manage all this stuff in the template.
The thing is: how is it possible to display the right localized strings? What I thought about was to include a localized template, to separate concerns. Something like:

{% include ln ~ '/photos-list.twig' %}

And inside this template, I would have setted all the variables in the right locale, so I could use them in my photos list. (as explained in the first part of my question)
note that I have this structure for all others pages. Text content is separated in the locale folder, and each page has a master template (again, it's a very basic personal website)
What I did finally was to insert a hudge if statement before the photos list. If locale is fr, set variables with french texts, if it's en, set variables with english texts.
That does the trick, so I'm ok with that ^^

A: Why don't you move the second call of {{ test }} in tplB ( for this occasion ) ?

Content of tpl B

{% set test = "now is tpl B" %}

and the variable is: {{ test }}


text:
Q: Processing records in a sql task Using SSIS, I have retrieved a recordset from a query in a dataflow task.
I have a foreach loop that iterates through the records one at a time.
What I need to accomplish is to perform an update on each record.
The two variables are named   CUSTOMER_NUMBER and DECEASED_DATE    customer_number is a varchar, and deceased date is a date type.
update  set deceased = 'T', deceased_date = @deceased_date where customer_no = @customer_number
What do I need to change in the above query to use the variables?


text:
Q: Permanent listener for incoming Queue Messages I would like to do the following:
Create a DLL that is started once by a function and then listens permanently for new incoming Service Bus Messages.
In my opinion, my basic problem is to find a way to wait until the Event Handler can be executed. I want to do this permanently. So it should always be possible that the Event Handler can be executed.
Currently the GetPayloadAsync entry function terminates too fast.
In .NET the code looks like this:
Function GetPayloadAsync
   public static async Task GetPayloadAsyc()
    {

        _tokenSource = new CancellationTokenSource();
        var token = _tokenSource.Token;
        await ReceiveMessagesAsync(token));

    }

The ReceiveMessagesAsync function looks like this and registers the Event Handler:
static async Task ReceiveMessagesAsync(CancellationToken token)
    {

        ServiceBusClient client = new ServiceBusClient(AZURE_SERVICE_BUS_CONNECTIONSTRING, new ServiceBusClientOptions
        {
            TransportType = ServiceBusTransportType.AmqpWebSockets
        });

        ServiceBusSessionProcessor processor = client.CreateSessionProcessor(QUEUE_NAME, new ServiceBusSessionProcessorOptions
        {
            MaxConcurrentSessions = 1,
            AutoCompleteMessages = false
        });

        // add handler to process messages
        //processor.
        processor.ProcessMessageAsync += MessageHandler;

        // add handler to process any errors
        processor.ProcessErrorAsync += ErrorHandler;

        // start processing
        await processor.StartProcessingAsync(token);

    }

Does anyone have a suggestion how I can solve the problem?

A:
In my opinion, my basic problem is to find a way to wait until the
Event Handler can be executed. I want to do this permanently. So it
should always be possible that the Event Handler can be executed.
Currently the GetPayloadAsync entry function terminates too fast.

You can use the service bus trigger of azure function, which is a ready-made tool that can be used to process new incoming messages to the queue. And it will not terminate (this meets your requirement of 'permanent'). You can follow this to create an azure function:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-trigger?tabs=csharp


text:
Q: Numbering duplicate rows in bigquery I'm trying to number rows in which column a and column b is a match and when they occur again regardless of the date.
The dataset looks like this and I want the row_number column:

rider
driver
date
row_number

jim
joe
2020-10-20
1

jim
joe
2020-10-28
2

jim
jack
2020-10-29
1

jim
joe
2020-10-31
3

john
jane
2020-10-29
1

john
jane
2020-10-31
2

I thought about using the function <row_number over partition by> but I don't think it worked..
Help would be appreciated! Thanks!

A: Row_number() is actually for what you are looking for.
WITH data as (

SELECT "jim" as rider, "joe" as driver, "2020-10-20" as date UNION ALL
SELECT "jim", "joe", "2020-10-28" UNION ALL
SELECT "jim", "jack" , "2020-10-29" UNION ALL
SELECT "jim", "joe","2020-10-31" UNION ALL
SELECT "john", "jane", "2020-10-29"  UNION ALL
SELECT "john", "jane", "2020-10-31" )

SELECT
  rider, driver, date,
  ROW_NUMBER() OVER (partition by rider, driver) as row_number
FROM data
ORDER by rider, driver

A: Consider below - usually numbering tightly coupled with some particular order which in your case is clearly defined by data - so I do think it is important here to have order by within the window definition
select *,
  row_number() over win as row_number
from `project.dataset.table`
window win as (partition by rider, driver order by date)


text:
Q: how to counter attack a xmlrpc.php attack I want to counter attack or flood the attacker with useless data a loop or something... ?
Having a high rate of xml-rpc attacks and since i dont use xml-rpc and am currently routing them to a shame on you html page, but thought it would be innovative to either counter attack or simply respond to the data request with a flood of useless data preferably never ending flood till they escape it :)

A: Try css transition property with slide time.

A: I would try something like this in jQuery. After clicking I would do a clearInterval();
Note: Add jQUery library before testing this.
$(document).ready(function(){
      setInterval(functionToExecute, 30000);
      });

    function functionToExecute(){
      setTimeout(slide1, 5000);
      setTimeout(slide2, 10000);
      setTimeout(slide3, 15000);
      setTimeout(slide4, 20000);
    }

    function slide1(){
      $("#slide-1-trigger").trigger("click");
    }
      function slide2(){
      $("#slide-2-trigger").trigger("click");
    }
      function slide3(){
      $("#slide-3-trigger").trigger("click");
    }
      function slide4(){
      $("#slide-4-trigger").trigger("click");
    }


text:
Q: Error: vuex do not mutate vuex store state outside mutation handlers Even with const passed to mutation as advise by @skirtle on another same problem, used const to mutate my state but get error. to be more clear, my state is an empty array, it will be filled the first time, but i get the error if i even try to change my select!!! let alone send another mutation!! so i think if i fill my state before this, (in case of editing my product), i'll get the error the on first try too. here is the codes:
<template>
<div class="pt-6">
    <v-row class="ma-0">
    <v-col cols="12" md="12" class="pa-0">
        <v-row class="ma-0">
        <!-- form 1 -->
            <template v-for="(select, index) in selects">
                <component
                :is="select"
                :key="select.name"
                v-model="catId"
                @changed="addComponent(index)"
                :catid="catId"
                :selectindex="index"
                :pcat="productCat[index]"
                :subcat="subCat"
                ></component>
            </template>
        <!-- btn -->
        <v-col cols="12" sm="6" md="3" class="px-1">
            <v-btn width="100%" class="theme__little__color2 text_main_color px-2" @click.prevent="addCatBtn()">{{lang.addcat}}</v-btn>
        </v-col>
        {{selectedCatArr}}
        <!-- btn -->
        <addproductbtn :section="section" />
        </v-row>
    </v-col>
    </v-row>
</div>
</template>

<script>
import addproductbtn from '~/components/global/cms/addproductbtn'
import selectcategory from '~/components/global/cms/selectcategory'

export default {
    components:{
        'addproductbtn': addproductbtn
    },
    data(){
        return{
            section: 'cat',
            selects: [selectcategory],
            catId: 0,
            subCat: true,
            selectedCatArr: []
        }
    },
    methods:{
        addComponent(index){

                this.selects.length = index + 1
                setTimeout(() => {
                    this.selects.push(selectcategory)
                }, 1);

        },
        addCatBtn(){
            this.goToRedirect('/cms/category/insert', this.$route.path, this.ProductId)
        },
        async insertCategory(){
            const data = {
                pId: this.editProduct.pId,
                catId: this.catId
            }
            // let response = await this.axiosPost('product/catupdate', data)
            const productCategory = this.selectedCatArr
            this.setEditProductCat(productCategory)
        }
    },
    computed:{
        productCat(){
            return this.editProduct.categories
        },
        ProductId(){
            return this.editProduct.pId
        }
    },
    created(){
        this.$nuxt.$on('insert', ()=>{
            this.insertCategory()
        })
        this.$nuxt.$on('nextcat', (subCat)=>{
            this.subCat = subCat
        })
        this.$nuxt.$on('nextpanel', ()=>{
            this.insertCategory()
        })
        this.$nuxt.$on('selectedcat', (selected, index)=>{
            delete selected.subCategory
            this.selectedCatArr.length = index
            this.selectedCatArr.push(selected)
        })
    }
}
</script>

and my select component:
<template>
    <v-col cols="12" sm="6" md="3" class="px-1 text_details_color3" v-if="showCat">
        <v-select
        return-object
        :items="items"
        :label="lang.category"
        v-model="selected"
        @change="emitEvent"
        item-text="title"
        item-value="id"
        outlined></v-select>
        {{selected}}
    </v-col>
</template>

<script>
export default {
    props:['selectindex','catid','pcat','subcat'],
    data(){
        return{
            selected:{},
            items:[],
            showCat: true
        }
    },
    async fetch(){
        // this.items = await this.axiosGet(`categories/${this.catid}/1`)
        this.items = [
            {id: this.catid + 1, title: this.catid+'title1', subCategory: true},
            {id: this.catid + 2, title: this.catid+'title2', subCategory: true},
            {id: this.catid + 3, title: this.catid+'title3', subCategory: false},
            {id: this.catid + 4, title: this.catid+'title4', subCategory: true}
        ]
    },
    methods:{
        emitEvent(){
            this.$emit('input', this.selected.id)
            this.$emit('changed')
            $nuxt.$emit('nextcat', this.selected.subCategory)
            $nuxt.$emit('selectedcat', this.selected, this.selectindex)
        }
    },
    computed:{
        //
    },
    created(){

    },
    mounted(){
        this.selected = this.pcat
        this.showCat = this.subcat
    }
}
</script>

and my store is like this:
state:
editProduct:{
   categories: [],
}

mutation:
SET_EDITPRODUCT_CAT(state, cat){
   state.editProduct.categories = cat
}

action:
setEditProductCat({commit}, cat){
   commit('SET_EDITPRODUCT_CAT', cat)
},

UPDATE

*

*i'm on Nuxtjs and my mapActions and mapGetters are imported globally in my mixins

*as i tried on other parts of my app, found out that this problem only occur when my state is array or obj. string, bool, int and other single types are ok. i can set them as many time as i want.


text:
Q: Prove $\{0,1\}^* -\{0^i 1^i\mid i \ge 0\}$ is context free? Is the only way to prove that this language is context-free to construct a Context-Free Grammar that accepts it?
If so any hints on how to get started?

A: HINT: Let $L=\{0,1\}^*\setminus\{0^i1^i:i\ge 0\}$. Then $L$ consists of all words of the following three kinds:

*

*any word of the form $x10y$, where $x,y\in\{0,1\}^*$;

*any word of the form $0^i1^k$ with $i<k$; and

*any word of the form $0^i1^k$ with $i>k$.

It's not hard to write context-free grammars for each of these types, and once you have them, it's not hard to combine them into a single context-free grammar that generates $L$.

A: What do you think about the following? Does it work?
$$S\to M1X$$
$$S\to X0M$$
$$M\to 0M1$$
$$M\to \Lambda$$
$$X\to 1X$$
$$X\to 0X$$
$$X\to \Lambda$$


text:
Q: High charts showing the composition of count as tooltip I have a chart as below.
http://jsfiddle.net/Mn6sB/4/
$(function () {
        $('#chartContainer').highcharts({
            chart: {
                renderTo: 'chartContainer',
                type: 'column',
                marginTop:50,
                spacingBottom: 5,
                marginBottom: 100
            },
            credits: {
                  enabled: false
              },
            title: {
                text: 'Product health',

            },
            subtitle: {
                text: ''
            },
            xAxis: {
                type: 'datetime',
                minTickInterval: 24 * 3600 * 1000,
                dateTimeLabelFormats: {
                    month: '%e %b',
                    year: '%b'
                }
            },
            yAxis: {
                min: 0,
                max:100,
                tickInterval:10,
                title: {
                    text: 'Passrate'
                },
            },
            legend: {
                            title: {
                                text: 'To toggle between different branches click on the branch names in the legend',
                                style: {
                                    fontStyle: 'italic'
                                }
                            },
                            layout: 'horizontal',
                        },
            tooltip: {
                formatter: function() {
                         return 'Branch: '+ this.series.name +
                            '
Date: '+ Highcharts.dateFormat('%e %b',this.x)+
                                '
Pass rate: '+ this.y +'%';
                }
            },
            plotOptions: {
                spline: {
                    dataLabels: {
                        enabled: 'True'
                    },
                    enableMouseTracking: false
                }
            },
            series: [{name: 'BranchX', data:[[Date.UTC(2013,9,3),88],[Date.UTC(2013,9,4),100],[Date.UTC(2013,9,5),100],[Date.UTC(2013,9,6),100],[Date.UTC(2013,9,7),100],[Date.UTC(2013,9,8),100],[Date.UTC(2013,9,9),100],]},{name: 'BranchY', data:[[Date.UTC(2013,9,3),75.27],[Date.UTC(2013,9,4),83.33],[Date.UTC(2013,9,5),100],[Date.UTC(2013,9,6),63.64],[Date.UTC(2013,9,7),98.31],[Date.UTC(2013,9,8),98.9],[Date.UTC(2013,9,9),64.71],]},]
        });
    });

This is a column graph showing the pass percentage.
I wanted to pass the numbers (passcount, total count) which were used to calculate the % vlaues, so that I can show them as tooltip. Is is possible?

A: yes this is possible and simple
pass the addl numbers in the series along with data
access them from tool tip as shown below from the formatter
tooltip:{
 formatter: function() {
  this.point.options.passCount
  this.point.options.total
 }
}

series:[{
 data: [{
  x: timestamp,
  y: value,
  passCount: someVlaue,
  totalCount: someValue
 },{
  x: timestamp,
  y: value,
  passCount: someVlaue,
  totalCount: someValue
 },{
  x: timestamp,
  y: value,
  passCount: someVlaue,
  totalCount: someValue
 }]
}]


text:
Q: Simple jQuery and AJAX Tutorial Example I've looked it up and saw several similar posts, but, to be honest, the examples given demonstrating my problem, were too complicated for me to figure out.
I've done a couple of tutorials using plain JavaScript to demonstrate AJAX, and it was all pretty straight forward, with the XMLHttpRequest function, etc.
However, I cannot get jQuery to process AJAX, even with very basic code, such as the code below:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>ajax_test_002.html</title>

Let jQuery AJAX Change This Text

    <button>Get External Content</button>

I'm using jQuery 3.5.1.  My source file, demo_test.txt has only a couple of lines.
In other post, I see something about a header, but, I have no idea where the jQuery/AJAX header is to edit it.
Thanks for your patience with this beginner.
-The CodeSchlocker


text:
Q: Void task with generics in C# I would like to reuse the following static generic Profile function in my application:
private static async Task<T> Profile<T>(Func<Task<T>> func, string operation)
{
    Console.WriteLine($"{operation} is called");
    return await func();
}

And I have the following interface to implement:
public interface ICustomerOperations
{
    Task<Customer> GetCustomerAsync(string id);

    Task DeleteCustomerAsync(string id);
}

I can use Profile method with GetCustomerAsync without any problem.
public async Task<Customer> GetCustomer(string id)
{
    return await Profile(() => _customerOperations.GetCustomerAsync(id), $"GetCustomerAsync");
}

However when I try to use Profile with DeleteCustomerAsync
public async void DeleteCustomer(string id)
{
    await Profile(() => _customerOperations.DeleteCustomerAsync(id), $"DeleteCustomerAsync");
}

Build failed:

The type arguments for method 'CrmService.Profile(Func<Task>,
string)' cannot be inferred from the usage. Try specifying the type
arguments explicitly.

So my question is how can I reuse Task<T> with void?

A: You can create an overload without duplicating the method:
private static Task Profile(Func<Task> func, string operation)
{
  return Profile<object>(async () => { await func(); return null; }, operation);
}

A: A simple solution is to duplicate your method:
private static async Task Profile(Func<Task> func, string operation)
{
    Console.WriteLine($"{operation} is called");
    await func();
}

I think duplicating your method is cleaner than doing some hacks like this:
public async void DeleteCustomer(string id)
{
    await Profile(async () => { await _customerOperations.DeleteCustomerAsync(id); return 0; }, $"DeleteCustomerAsync");
}


text:
Q: VBA - sumifs in for loop - is there a more efficient way? I am trying to build a macro that calculates several sumifs, looking for conditions on a different worksheet. This is the code I have so far:
Sub SumPerYear()

Dim NoClients As Long
NoClients = Worksheets("Temp").Range("A2").End(xlDown).Row - 1

Sheets("Temp").Activate

For i = 2 To NoClients + 1

    'Fill 2015 € in column E
    Cells(i, 5).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2015, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2015 # in column F
    Cells(i, 6).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2015, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2016 € in column G
    Cells(i, 7).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2016, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2016 # in column H
    Cells(i, 8).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2016, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2017 € in column I
    Cells(i, 9).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2017, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2017 # in column J
    Cells(i, 10).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2017, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill Tot € in column K
    Cells(i, 11).Value2 = Cells(i, 5) + Cells(i, 7) + Cells(i, 9)

    'Fill Tot # in column L
    Cells(i, 12).Value2 = Cells(i, 6) + Cells(i, 8) + Cells(i, 10)

Next i

End Sub

This code works, but because there are thousands of records, it takes a long time to complete. Is there a way to make this more efficient/faster?
Thanks for your input!

A: Unfortunately, Application methods work too slow on big count of cells, so you should write some code, that's not so nice and simple as yours.
Main idea is catched here:
Dim arrA as Variant 'change Variant to your type
Dim arrCD as Variant
Dim arr as Variant
Dim i as long
Dim k as integer
Dim NoClients As Long
NoClients = Worksheets("Temp").Range("A2").End(xlDown).Row - 1

'assign Ranges to arrays
'we can't assign non-contiguous range, so we create two arrays
arrA = Range("A:A")
arrCD = Range("C:D")
ReDim arr(UBound(arrA), 3)
ReDim outArr(NoClients, 5 to 10)
'loop and fill third merged array
For i = 1 To UBound(arrA)
    arr(i, 0) = arrA(i, 1)
    arr(i, 1) = arrCD(i, 1)
    arr(i, 2) = arrCD(i, 2)
Next i

'the rest of code You just loop through
For k = 2 To NoClients + 1 'get client
    For i = 1 To UBound(arr) 'count summuries for him
        if (arr(i,0) = 2016) and (arr(i,1) = true) and (arr(i,2) = _
            Worksheets("Temp").Range("A" & k).Value2) then
            'sumifs replacement
            outArr(k, 5) = outArr(k, 5)  + Worksheets("Q ALL").Cells(1+i, "I").Value2
            'countifs replacement
            outArr(k, 6) = outArr(k, 6) + 1
        end if
    Next i
Next k

Worksheets("Temp").Range("A2").Value2 = outArr 'prints array on sheet with top left corner at A2


text:
Q: How to remove block-library menu elements (blocks)? How can I remove menu items in the block library, within the gutenberg editor?
I have already removed unwanted blocks with whitelisting blocks, using the "allowed_block_types_all" filter.
However, in this case there are two items, which belong to the "group" block, which are not removed, even when the "__experimentalLayout" is set to false, which deactivates the options, but doesn't remove them from the block-library menu.
Can wp.data be used to remove specific library items using javascript?
Is there a PHP filter for the block-library?
Screenshot of group items


text:
Q: How to create a default user in global.asax? The project I'm working on uses ms identity hooked into a mongo database. For deployment purposes (since there is no public registration), I'd like for the page to automatically check for an admin account and create one if its missing. I can't seem to do that however since there is no owin context when executing Application_Start() and thats the only way i know how to get to the user manager outside the whole mvc thing. Right now, It checks for the admin account every time the home page is loaded but it occurred to me that this is unnecessary bloat and I'd like to move it to somewhere thats visited less frequently.

A: The best solution I can provide you here is create an install.aspx. This you will execute manually and create a user for you.
In addition you could perform various application tasks, such as, refreshing application variables and so on...


text:
Q: LINQ to Entities does not recognize the method
LINQ to Entities does not recognize the method 'Boolean
TagsCheck(Library.MVVM.Model.Book)' method, and this method cannot be
translated into a store expression

Насколько я понял, эта ошибка появляется потому что выражение в запросе не может преобразоваться в sql запрос. И я не могу понять как мне заменить мою функцию на запрос.
Сам запрос
BookList = db.Books.Include("Tags").Where(b => b.Name.Trim().Contains(BookSearch.Trim()) && TagsCheck(b)).ToList();

И функция
bool TagsCheck(Book book)
{
    using (DatabaseContext db = new DatabaseContext())
    {
        foreach (Tag tag in FilterTagList)
            if (!book.Tags.Contains(db.Tags.FirstOrDefault(t => t.TagId == tag.TagId)))
                return false;
        return true;
    }
}

В самом запросе я пытаюсь получить список книг, в список тегов которых, входят теги из списка FilterTagList. Подскажите возможное решение.

A: Если вы корректно описали ту часть кода, которую вы не показали здесь, касательно строения классов Book и Tag, а так-же BookSearch поля, заведены компараторы на подобии TagComparer, то должно быть достаточно:
class TagComparer : IEqualityComparer<Tag>
{
    public bool Equals(Tag t1, Tag t2)
    {
        if (t1 == null && t2 == null) return true;
        else if (t1 == null || t2 == null) return false;
        else if (t1.TagId == t2.TagId) return true;
        else return false;
    }

    public int GetHashCode(Tag tx)
    {
        return (tx?.TagId ?? 0).GetHashCode();
    }
}

BookList = db.Books
   .Include("Tags")
   .Where(b
      => b.Name.Contains(BookSearch.Trim())
      && b.Tags.Any(a => FilterTagList.Contains(a, new TagComparer())))
   .ToList();

A: Метод TagsCheck должен возвращать Expression<Func<Book, bool>>, чтобы его можно было использовать в linq-запросах Entity Framework.
Насколько я понял, в этом методе проверяется, содержится ли хоть один тег, назначенный книге, в списке FilterTagList.
Этот код можно записать так:
Expression<Func<Book, bool>> TagsCheck()
{
    return book => book.Tags.Any(tag => FilterTagList.Contains(tag));
}

Использовать его следует так:
var books = db.Books.Include("Tags")
    .Where(b => b.Name.Trim().Contains(BookSearch.Trim()))
    .Where(TagsCheck())
    .ToList();

Обратите внимание, его обязательно нужно использовать так: Where(TagsCheck()). Потому что он возвращает Expression! Он не возвращает значение bool!
Его невозможно использовать вот так: .Where(book => TagsCheck()), потому что тогда он конвертируется в делегат.
Он возвращает выражение book => book.Tags.Any(tag => FilterTagList.Contains(tag)) и именно оно будет подставлено в месте вызова.
И, соответственно, такой метод не получится использовать с логическим оператором &&. Отсюда следует отдельный вызов Where.

Метод не принимает параметр, потому что параметр book принимает Expression (выражение). Поэтому, чтобы не возникло соблазна всё-таки попытаться воткнуть какой-нибудь параметр, можно сделать свойство вместо метода:
Expression<Func<Book, bool>> TagsCheck =>
    book => book.Tags.Any(tag => FilterTagList.Contains(tag));

Его использование, естественно, будет без круглых скобочек:
.Where(TagsCheck)


text:
Q: J, creating a function I just started learning J and I tried to create a function that checks if a number is prime.
<./<./13|*/~(2}.i.)13

This checks if 13 is prime and will return 1.
<./<./10|*/~(2}.i.)10

And this will return 0.
So my question: how do I make a function out of this? How do I specify the argument?
prime(x) =: <./<./x|*/~(2}.i.)x

This, ofcourse, won't work. But how can I create this function in J?
PS. I know the function doesn't work for 2, I'll deal with that later :D

A: In order to replace the specific values in those sentences with a named parameter you may use a script, like this:
   prime=: verb :'<./<./y|*/~(2}.i.)y'
   prime 13
1
   prime 10
0

(Here the word 'verb' is merely 3. It acts as the left parameter to the colon, while the script body is the colon's right parameter. But feel free to ignore that detail for awhile, and treat as a pattern 'verb :' before the quoted body of a script.)
You'll notice I've used y, not x, as the parameter name. In explicit J form the left parameter is x (when there is one) and the right parameter, y.
It's natural in J for a verb to receive arrays of indefinite shape, but the one defined above will error if given anything but a scalar. Here's a way to fix that:
   prime=: (verb :'<./<./y|*/~(2}.i.)y')"0
   prime 10 11 12 13
0 1 0 1

As a stylistic matter, the repetition of <./ (least among) might not communicate your intent as well as this:
   prime=: (verb :'<./ , y|*/~(2}.i.)y')"0

I'd like to mention that while programs like this are great for exploring the language, qualifying whether a number is prime is handled by a J primary. That symbol, p: , would normally be used. If an assigned name was desired, and explicit form chosen, here's a typical definition:
   prime=: verb :'1 p: y'

As before, 'y' will be interpreted as the value of the right parameter of the named verb ("prime").
In summary: To specify arguments, in place of particular values, explicit form is used. That involves a script, i.e. text. In explicit verbs write 'x' and 'y' as left and right arguments, respectively. If you use only one argument, it is 'y'.
J programmers often use tacit form, instead. In tacit form there is no script, and arguments are always implied, not specified. (There's no problem with working in explicit form when that is more comfortable.) "Explicit" is so called because, in that form, arguments are indicated explicitly.


text: Q: Data Extension Contact ID? Does Marketing cloud have a unique Identifier that can be used in Data Extensions when a contact is created? It seems odd that the only way I have been able to make use of a subscriber key is by using RandomBetween.


text:
Q: How to parse data inside a string? I have data like this:

    '[        {
     "agent_id": 558921,
     "agent_name": "The City Townhouse",
     "attributes": {
     "agent_ratings_enabled": 0,
     "approved": 1,
     "attribute_set_id": 1,
     "categories": JSON.parse("[15,19]"),
     "indoor_features": ["Balcony","Maid\\\'s room"],
     "is_agent": 1}    ];'

And I dont have any idea how parse them. Its just a part of a string.
My code is here:
import requests
import re

res = requests.get('https://www.lamudi.com.ph/brandnew-modern-duplex-2-car-garage-house-and-lot-for-sale-in-betterliving-md.html')
res = res.content
RE_OFFER_DATA_JSON_FROM_FLAT_PAGE = r".dataLayer = (.+?)<\/script>"
OFFER_DATA_JSON = re.compile(RE_OFFER_DATA_JSON_FROM_FLAT_PAGE)
data = OFFER_DATA_JSON.search(str(res)).group(1)
text = data.replace("\\n", "")
print(text)

I know, that it's not good idea to use regex, but I don't have another way.
Thanks for any advise

A: To load the JSON data from this site, it needs to be cleaned from Javascript first:
import re
import json
import requests

res = requests.get(
    "https://www.lamudi.com.ph/brandnew-modern-duplex-2-car-garage-house-and-lot-for-sale-in-betterliving-md.html"
)

data = re.search(r"dataLayer = (\[.*?\]);", res.text, flags=re.S).group(1)

# clean the data from Javascript artifacts:
data = re.sub(r'JSON.parse\("(.*?)"\)', r"\1", data)
data = re.sub(r",\s*}", r"}", data)
data = re.sub(r"navigator\.userAgent", r'""', data)

# parse the data
data = json.loads(data)

# pretty print the data:
print(json.dumps(data, indent=4))

Prints:
[
    {
        "agent_id": 558921,
        "agent_name": "The City Townhouse",
        "attributes": {
            "agent_ratings_enabled": 0,
            "approved": 1,
            "attribute_set_id": 1,
            "categories": [
                15,
                19
            ],
            "indoor_features": [
                "Balcony",
                "Maid's room"
            ],
            "is_agent": 1,
            "listing_type": "Classifieds",
            "other_features": [],
            "outdoor_features": [
                "Garage"
            ],
            "price_formatted": "\u20b1 11,300,000 ",
            "price_not_shown": false,
            "seller_is_trusted": 1,
            "show_listing_address": 1,
            "show_mobile": 1,
            "is_whatsapp": 1,
            "is_viber": 0,
            "is_facebook": 0,
            "show_officephone": 0,
            "top_position": 0,
            "urlkey_details": "brandnew-modern-duplex-2-car-garage-house-and-lot-for-sale-in-betterliving-md.html",
            "bathrooms": 3,
            "bedrooms": 3,
            "building_size": 210,
            "car_spaces": 2,
            "land_size": 150,
            "agency_name": "The City Townhouse",
            "alternate_sku": "39131996",
            "attribute_set_name": "House",
            "currency_code": "PHP",
            "listing_start": "2021-02-09 11:26:05",
            "name": "Brandnew Modern Duplex 2 Car Garage House and Lot for Sale in Betterliving-MD",
            "price": 11300000,
            "product_owner": 558921,
            "product_owner_name": "The City Townhouse",
            "product_owner_url_key": "miyabi-realty-agn-8",
            "root_category": 15,
            "sku": "HO602200CD8819DPH",
            "status": "active",
            "status_supplier_config": "active",
            "subcategory": "Townhouse",
            "subcategory_id": 19,
            "offer_type_id": 2,
            "location_latitude": "14.482705",
            "location_longitude": "121.024909",
            "listing_region": "Metro Manila",
            "offer_type": "Buy",
            "listing_area": "Don Bosco",
            "listing_city": "Para\u00f1aque",
            "image_url": "https://static-ph.lamudi.com/static/media/bm9uZS9ub25l/2x2x5x880x396/ac7e9e4327f459.jpg"
        },
        "country": "ph",
        "description": {
            "characters": 438,
            "text": "Duplex 2 Storey Townhouse3 Bedrooms3 Toilet &amp; BathMaids RoomLiving RoomDinning RoomKitchen AreaBalconyMaster Bedrooms w/ walk in closetSELLING PRICE:11.3MLot Area:150 sqmFloor Area:210sqmTerms Of Payment:400K Reservation20% Downpayment80% Bank Finance",
            "words": 31
        },
        "device_agent": "",
        "device_type": "desktop",
        "images": 15,
        "language": "en",
        "location": {
            "area": "Don Bosco",
            "city": "Para\u00f1aque",
            "region": "Metro Manila"
        },
        "login_state": false,
        "number_of_product_attributes": 49,
        "number_of_product_features": 3,
        "sku": "HO602200CD8819DPH",
        "title": "Brandnew Modern Duplex 2 Car Garage House and Lot for Sale in Betterliving-MD",
        "page_type": "product"
    }
]

A: If it's valid JSON you can use json built-in module, in particular the json.loads() function which parses strings.
https://docs.python.org/3/library/json.html


text:
Q: Is the least squares solution to an overdetermined system a triangle center? My question relates to a simple case of the least squares problem. For example, take the system of equations
\begin{align*}
2x- y &= 2, \\
x + 2y &= 1, \\
x+y &= 4,
\end{align*}
which is clearly overdetermined. Using a least squares approach, we can solve the system $$A^TA\mathbf{x^*} = A^T\mathbf{b},$$ where $\mathbf{x^*}$ minimises $\|\ A\mathbf{x} -\mathbf{b} \ \|$, and  $$A = \begin{bmatrix} 2 & -1\\ 1 & 2 \\ 1 & 1 \end{bmatrix} \ , \quad  \mathbf{b}=  \begin{bmatrix} 2 \\ 1 \\ 4 \end{bmatrix} \quad \mbox{and} \quad \mathbf{x}=  \begin{bmatrix} x \\ y \end{bmatrix},$$
to obtain an approximation for the solution as $\left(\frac{10}{7}, \frac{3}{7} \right)$.
If you plot the three straight lines that constitute the system of equations, they intersect at three points that form the vertices of a triangle.
My question is - does the solution always fall within this triangle (as in this example), and if so, is this point a (non-traditional) triangle center?

A: As Rahul Narain commented, the precise position of the least-squares solution depends on the scaling of the individual equations: as you scale up an equation, so does the importance of the distance of your solution to the corresponding line, and the least-squares solution will end up closer to that line. You can say that in any case the least-squares solution will lie in the interior of the triangle formed by the three lines, since for a point in any of the other $6$ sectors into which the lines cut up the plane, moving in some direction will decrease the distances to all three lines at the same time, so one can never have a minimum there.
In the spacial case where you scale the equations in such a way that for each of the the sum-of-squares-of-coefficients gives the same value (for instance$~1$), then you can describe the least-square solution as the unique point$~P$ such that the sum of the three vectors from $P$ to its orthogonal projections on the three lines is zero; in other words $P$ is the barycenter of its own pedal triangle (the triangle formed by those projections). That this is so can easily be seen by taking the formula implicit in the comment by @bubba and differentiating it.
Giving a geometric construction of such a point is an interesting problem that probably has been considered by people, but I don't see an easy solution right now, nor do I recall having seen anything directly related. In particular, I am unsure if this point coincides with any one of the many "centers" associated to a triangle; however given that there are so many of them, and the description of the point we are interested is is quite natural, I would bet that it does equal one of those centers.
Indeed, thank you darij grinberg for pointing out that this is the Symmedian Point, the properties listed under the link correspond exactly to what we are after here.


text:
Q: How to implement the authorization through token and roles, in WEB API C #, SOAP architecture, through the use of repositories with stored procedures? How can I implement the authorization through token and roles, in WEB API C #, SOAP architecture, through the use of repositories with stored procedures and dependency injection?
public override void OnAuthorization(HttpActionContext actionContext)
{
    if (actionContext.Request.Headers.Authorization == null)
    {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
    }
    else
    {
        string autenticationToken = actionContext.Request.Headers.Authorization.Parameter;
        string decodeautenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(autenticationToken));
        string[] userNamePassworArray = decodeautenticationToken.Split(':');
        string username = userNamePassworArray[0];
        string password = userNamePassworArray[1];

        LoginModel model = new LoginModel();

        //validate user credentials and obtain user roles (return List Roles)
        model.Roleslist = _serviceUsuario.ObtenerRoles(username, password);

        if (model.Roleslist !=null)
        {
            //this line takes a list of roles and divides them with a comma.
            string ListRoles = string.Join(",", model.Roleslist.Select(x => x.Roles));

            //bacic authentication
            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);

I tried it in the following way, but it does not work
            //ClaimsIdentity oAuthIdentity = await model.Roleslist.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
            //ClaimsIdentity cookiesIdentity = await model.Roleslist.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            //it does not work
            var authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, ListRoles);
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            HttpContext.Current.Request.Cookies.Add(authCookie);

            //  HResult = 0x80004002 Message = You can not convert an object of type 'System.Security.Claims.ClaimsIdentity' to the type 'System.Web.Security.FormsIdentity'.
            FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
            FormsAuthenticationTicket ticket = id.Ticket;
            string userData = ticket.UserData;
            string[] roles = userData.Split(',');
            HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
        }
        else
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "El nombre de usuario o la contraseña no son correctos.");
        }
    }
}

I tried it in the following way, but it does not work
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
        LoginModel model = new LoginModel();
        //validate user credentials //valida las credenciales de usuario
        //model.usuario = _serviceUsuario.Login(context.UserName, context.Password);//bool
        //validate user credentials and obtain user roles //validar las credenciales de usuario y obtener roles de usuario
        model.Roleslist = _serviceUsuario.ObtenerRoles(context.UserName, context.Password);//List

        //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (model.Roleslist == null)
        {
            context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
            return;
        }

A: I managed to implement the authentication with Token without Entity Framework that is with the validation based on a stored procedure and roles.
The code is the following:
public class CredentialsAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    // ...

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        LoginModel model = new LoginModel();

        //validate user credentials and obtain user roles (return List Roles)
        //validar las credenciales de usuario y obtener roles de usuario
        var user = model.User = _serviceUsuario.ObtenerUsuario(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.cod 01");
            return;
        }

        var stringRoles = user.Roles.Replace(" ", "");
        string[] roles = stringRoles.Split(',');
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

        foreach (var Rol in roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, Rol));
        }

        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

        AuthenticationProperties properties = CreateProperties(context.UserName);
        var ticket = new AuthenticationTicket(identity, properties);

        context.Validated(ticket);
    }
}

Configure la aplicación para el flujo basado en OAuth
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    //Provider = new ApplicationOAuthProvider(PublicClientId),
    Provider = new CredentialsAuthorizationServerProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
    // En el modo de producción establezca AllowInsecureHttp = false
    AllowInsecureHttp = true
};

// Permitir que la aplicación use tokens portadores para autenticar usuarios
//app.UseOAuthBearerTokens(OAuthOptions);
app.UseOAuthAuthorizationServer(OAuthOptions);

Startup
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        ConfigureAuth(app);
        var authOptions = new OAuthBearerAuthenticationOptions()
        {
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
        };
        app.UseOAuthBearerAuthentication(authOptions);
        app.UseWebApi(config);
    }
}


text:
Q: How to determine x-path of an element in Javascript? I'm adding some new functionality to a Firefox plugin that is recording actions user does in the browser. The problem is, the click handler is a little bit broken - it doesn't add anything to identify a button if it has "image" type. I want to make it add a relieable piece of data to help identify the exact button user has clicked. To my knownledge, putting its XPath location is the only way to do so. So I'm looking for a way to get such value, hopefully without the need to iterate all over up to the root element.
Upd:
I can't change the source code of the site

A: I think I know what you want now, and I guess you can see how xpather does it, but I am afraid it will do it by going through the tree to the root...


text:
Q: Using Node fs.createWriteStream to produce logs, but it is writing duplicates I am using Node 0.6.19 with express framework.  I am seeing some weird things with my logging.  First, I created a log for (createWriteStream) incoming requests.  I used the express syntax to pipe the requests into the log via:
var logFile = fs.createWriteStream('log.log', {
    "flags": "a"
});

app.configure(function() {
    app.use(express.logger({
      stream: logFile
    }));
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.methodOverride());
    return app.use(app.router);
});

seems to have duplicates of the incoming request when I hit an express route like:
app.get('/', routes.index);

Second, on some of my routes I do a user lookup in the database, and log the user id to another file by the same createWriteStream method.  When I do a
logFile.write(user_id + 'n');

I get duplicate user_id.  Not a problem with the query itself which tells me something is going on with the createWriteStream method.

A: If using a browser to call your app, you are possibly getting the duplicate output as a result of the favicon request. You can easily validate this by intercepting the request using fiddler or some alternative HTTP debugging proxy depending on your OS.


text:
Q: Is there a way to track a GPS device using PHP? In my upcoming project, I need to track GPS device attached to vehicles. Is there any way this is possible through PHP or ASP.Net

A: first this device have to send data somehow, then you need to capture it in some DB then present via PHP, ASP.Net or anything else. there is no such class GPSDevice with method GetPosition that will do all the magic.

A: Although there are "standard" protocols at the hardware level, adherence varies. And AFAIK, as yet there is no kernel support for GPS devices as standard in Linux (I'm not sure that there should be either). However you might find gpsd useful.
C.


text:
Q: Exception In distinct values from Collection - CurrentBSONType is UNDEFINED I am getting "CurrentBSONType is UNDEFINED" exception while making a db call that fetches distinct records from a Mongo collection.
Our Mongo collection looks like this :
    {
    "_id": ObjectId("5672be450d71c945772b8393"),
    "productId": "P-moac-49678195574",
    "title": "Flip Cover Lenovo",
    "description": "Cosmos Flip Cover  ",
    "currency": "INR",
    "productURL": "",
    "sellingPrice": 150,
    "subcategories": [{
        "name": "Mobile Accessories",
        "parent": {
            "name": "Mobile Accessories"
        }
    }],
    "imageURLs": [{
        "imageurl": "",
        "height": 0,
        "width": 0
    }],
    "attributes": [{
        "key": "model",
        "value": "Flip Cover"
    }],
    "created": ISODate("2015-12-17T13:53:09.757Z"),
    "modified": ISODate("2015-12-17T13:53:09.757Z"),
    "merchant": "IB",
    "brand": "Cosmos",
    "reviews": null
}

And java code to get distinct values of subcategories :
    public Map<String, SubCategory> getSubCategories() throws StatementCreationException, SQLException {
        MongoCollection<Document> productsCollection = connectionFactory.getMongoCollection("products");
        DistinctIterable<Document> result = productsCollection.distinct("subcategories", Document.class);
        Map<String, SubCategory> subcategories = new LinkedHashMap<String, SubCategory>();
        for (Iterator<Document> iterator = result.iterator(); iterator.hasNext();) {
            Document subCatDoc = iterator.next();
            String subCatName = subCatDoc.getString("name");
            if (subCatName == null || subCatName.trim().isEmpty()) {
                continue;
            }
            SubCategory subCat = new SubCategoryImpl();
            subCat.setName(subCatName);
            Document categoryDoc = (Document)subCatDoc.get("parent");
            if (categoryDoc != null) {
                Category category = new CategoryImpl();
                category.setName(categoryDoc.getString("name"));
                subCat.setCategory(category);
            }
            subcategories.put(subCatName, subCat);
        }
        return subcategories;
    }

MongoDb throws following exception when the above method is invoked :
Exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is UNDEFINED.

Full stack trace :
Exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is UNDEFINED.
    at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:655)
    at org.bson.AbstractBsonReader.checkPreconditions(AbstractBsonReader.java:687)
    at org.bson.AbstractBsonReader.readStartDocument(AbstractBsonReader.java:421)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:138)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:45)
    at com.mongodb.operation.CommandResultArrayCodec.decode(CommandResultArrayCodec.java:48)
    at com.mongodb.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:53)
    at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:81)
    at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:40)
    at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:122)
    at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:159)
    at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:260)
    at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:147)
    at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:166)
    at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:157)
    at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:82)
    at com.mongodb.operation.DistinctOperation$1.call(DistinctOperation.java:129)
    at com.mongodb.operation.DistinctOperation$1.call(DistinctOperation.java:126)
    at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:196)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:169)
    at com.mongodb.operation.DistinctOperation.execute(DistinctOperation.java:126)
    at com.mongodb.operation.DistinctOperation.execute(DistinctOperation.java:56)
    at com.mongodb.Mongo.execute(Mongo.java:760)
    at com.mongodb.Mongo$2.execute(Mongo.java:747)
    at com.mongodb.OperationIterable.iterator(OperationIterable.java:47)
    at com.mongodb.DistinctIterableImpl.iterator(DistinctIterableImpl.java:80)
    at com.mr10q.parser.dao.service.mongo.impl.MongoDBPersistentServiceImpl.getSubCategories(MongoDBPersistentServiceImpl.java:713)

A: I think the only Problem is that "subcategories" is an Array of Documents.
Hence passing Document[].class as resultClass parameter of the distinct call would do what you want.
E.g.:
DistinctIterable<Document[]> result = productsCollection.distinct("subcategories", Document[].class);


text:
Q: how to draw a grid incrementally in d3? Below is an HTML file that will draw a 10x10 grid of squares alternating light grey and dark grey.  It fills a 2d array called the_grid with 0 or 1; then fills a 1d array called nodes with x, y, and color; then draws nodes with d3.  They all appear.  They look like this:

How do I instead have nodes drawn (i.e. appear) one at a time, in the order given by the nodes array (so I could draw different patterns, say vertical wipe, horizontal wipe, whatever)?
I tried fiddling with the transition function without success.  It just draws the whole grid, and slides it into place.  The squares don't visibly appear one by one.
The code:

A: To stagger the transitions of multiple elements entered at the same time from the same data array you can use transition.delay(), you can specify a constant (which will start all transitions simutaneously) or you can specify a function to base the delay on the datum of each element or its index:
selection.transition()
  .delay(function(d,i) { return i * 100; })
  .attr(...

Above and in the snippet below I've used the index:

function draw_function() {
          var vis = d3.select("#graph")
              .append("svg")
              .attr("width", 200).attr("height", 200);

          // fill the_grid
          var shape=[10,10];
          var the_grid=[];
          for (var idx = 0; idx < shape[0]; idx++) {
              var row = [];
              for (var jdx = 0; jdx < shape[1]; jdx++) {
                  var val = (idx+jdx)/2;
                  row.push(Math.floor(val)==val ? 1 : 0);
              }
              the_grid.push(row);
          }

          // fill nodes
          var rectwidth = 10;
          var nodes = [];
          for (var idx = 0; idx < the_grid.length; idx++) {
              for (var jdx = 0; jdx < the_grid[0].length; jdx++) {
                  var node = {x: idx * (rectwidth+1),
                              y: jdx * (rectwidth+1),
                              color: the_grid[idx][jdx] == 1 ? 'black' : 'lightgrey'};
                  nodes.push(node);
              }
          }

          // draw nodes
          vis.selectAll("rect.nodes")
              .data(nodes)
              .enter()
              .append("svg:rect")
              .attr("x", function(d) { return d.x; })
              .attr("y", function(d) { return d.y; })
              .attr("height", rectwidth)
              .attr("width", rectwidth)
              .attr("fill","white")
              .transition()
              .duration(1000)
              .delay(function(d,i) { return i * 100; })
              .attr("fill", function(d) { return d.color; })
      }

      // function has to execute after dom is loaded
      window.onload = draw_function

And below I've used the datum to create a random transition order:

function draw_function() {
          var vis = d3.select("#graph")
              .append("svg")
              .attr("width", 200).attr("height", 200);

          // fill the_grid
          var shape=[10,10];
          var the_grid=[];
          for (var idx = 0; idx < shape[0]; idx++) {
              var row = [];
              for (var jdx = 0; jdx < shape[1]; jdx++) {
                  var val = (idx+jdx)/2;
                  row.push(Math.floor(val)==val ? 1 : 0);
              }
              the_grid.push(row);
          }

          // fill nodes
          var rectwidth = 10;
          var nodes = [];
          for (var idx = 0; idx < the_grid.length; idx++) {
              for (var jdx = 0; jdx < the_grid[0].length; jdx++) {
                  var node = {
                              delay: Math.random()*2000,
                              x: idx * (rectwidth+1),
                              y: jdx * (rectwidth+1),
                              color: the_grid[idx][jdx] == 1 ? 'black' : 'lightgrey'};
                  nodes.push(node);
              }
          }

          // draw nodes
          vis.selectAll("rect.nodes")
              .data(nodes)
              .enter()
              .append("svg:rect")
              .attr("x", function(d) { return d.x; })
              .attr("y", function(d) { return d.y; })
              .attr("height", rectwidth)
              .attr("width", rectwidth)
              .attr("fill","white")
              .transition()
              .duration(1000)
              .delay(function(d,i) { return d.delay; })
              .attr("fill", function(d) { return d.color; })
      }

      // function has to execute after dom is loaded
      window.onload = draw_function


text:
Q: В БД не добавляются русские символы. Здравствуйте. Поялвилась такая проблема. Есть добавление новостей с помощью AJAX. В ней есть проверка при добавлении на наличие символов. Если пользователь пытается отправить пустой запрос то выводит ошибку. Так вот, при добавлении записи латинскими буквами все нормально добавляестя. А если русскими символами то добавляется пустая новость. Как это понимать? Думаю во всем виновата кодировка, но у меня сайт на utf-8, БД MySql тоже на utf-8. Помогите пожалуйста.
A: Господин @Luntegg, не вводите людей в заблуждение. utf8-general-ci это никакая не кодировка.
@Николай Никонов, исходники приложения должны быть сохранены в кодировке utf-8. Вы говорите, что так и есть. Посмотрите в файл my.ini и в директиве [mysqld] укажите кодировку utf-8. Как это сделать написано например здесь