text:
Q: ASP.NET MVC High latency - Delay between ajax request and action invocation because of large file write Update 2019-04-24
Problem TL;DR one controller call was causing the next few calls to have a ~15s delay before they even reached the controllers.
I've narrowed the cause to a large file write in the request that causes further delay File.WriteAllText(htmlFilePath, reportHTML);
Originial post
The Problem
I have a long running controller request for generating a report. After the report in generated, additional http requests are made to fetch resultant images.
However, the http calls for the images take about 15s between the ajax call in the browser and when the controller action is invoked. After that, the method runs speedily.
Evidence so far
Previously, we used WCF to run the report generation on a separate machine and there was no such delay.
I've tried running both the report generation and image retrieval methods as async calls on their own threads (but on the same machine). However, that still has the delay.
The delay also only happens on the first image request after generating the report. Afterwards, there is no delay.
There is also no session state and disabling session state has no effect
The Ask
Does anyone know what might cause this delay? How can I get better insights into blocks in ASP.NET code or IIS processes?
Other details:
Using CoreHtmlToImage for report generation and azure storage emulator for image storage.
ASP.NET MVC is version 5.2.3 (not core)

A: Turns out that writing to the website's directory causes the webserver to restart the site
Source: Creating temporary files in wwroot folder ASP.Net MVC3
So if you write files using the assembly working directory like
var uriAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
var assemblyPath = new Uri(uriAssemblyPath).LocalPath;
var baseDirectory = System.IO.Path.GetDirectoryName(assemblyPath);

You'll run into this issue.
If you need a consistent directory outside the webroot, you can use the designated temp directory
Path.GetTempPath()
Source: Where can I write a temp file from ASP.NET?


text:
Q: Making call to server when application is in background in Windows Phone 8 I want to make http request to web server periodically say after every 10 secs.
I am using Timer in application which makes http call. Now when application goes to background when user press Windows key.. the timer stops
Can I continue making call to web server?
I referred the VOID chatter box application, but looks like it is for VOIP application only.
Regards,
SRS

A: You have to make a TaskAgent that inherits from ScheduledTaskAgent and override OnInvoke() method. You also need to add the task into WMAppManifest.xml
<Deployment ...>
...
  <App ...>
    ...
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
      <ExtendedTask Name="BackgroundTask">
        <BackgroundServiceAgent Name="YourTaskAgent" Type="YourNameSpace.YourTaskAgent" Source="YourTaskAgent" Specifier="ScheduledTaskAgent" />
      </ExtendedTask>
    </Tasks>
  ...
  </App>
...
</Deployment>

Your main application itself cannot continue to perform HTTP requests when it is suspended. For more info see MSDN on background tasks. However, keep in mind that Background Tasks have limitations in what they can do. Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass Data from a UI Component Form to a Controller? Hey I'm beginner at Magento 2, and i don't know to much about UI component...
I'm creating a register form, and i want to pass Data of a UI Component Form to a Controller.
So i have a Form and i got a Button that i want to use it to get value from a dropdown field(combobox) of the Form.
I made the Block and the Controller, ok, the Block is calling the Controller right. But i don't know how to pass a specific value of the form to the controller. How can i do this?
I tried to use this command:  $this->getRequest()->getParams(); but only returns ID and KEY.
And when i tried this command: $this->getRequest()->getPostValue(); it just returns an empty array...
Any help is appreciated !
DeleteHeader.php (Controller):
 public function execute()
{
    $resultRedirect = $this->resultRedirectFactory->create();

    $id = $this->getRequest()->getParam('id');

    $this->save->getCombo();

    $txt = 'DELETE HEADER : ' .  $id;
    $this->logger->log('DEBUG', $txt);

    return $resultRedirect->setPath('api/data/edit/id/' . $id);
}

DeleteHeader Block (Button):
public function getButtonData()
{
    $url = $this->getUrl("api/data/deleteheader", ['id' => $this->getDataId()]);
    return [
        'label' => __('Delete Header'),
        'class' => 'custom-button-class',
        'data_attribute' => [
            'mage-init' => [
                'button' => ['event' => 'deleteheader'],
            ],
        ],
        'on_click' => "confirmSetLocation(' Certeza ? ','" . $url . " ')",
        'sort_order' => 80,
    ];
}

A: Use This in Your Controller File...
$post = $this->getRequest()->getPost();

Then You Can Use Form value using $post['your_field_name']

A: $getParams = $this->getRequest()->getParam('myparam');

this is fine to use a get params. However your controller has to be a get controller class MyAction extends \Magento\Framework\App\Action\Action implements HttpGetActionInterface if you want to use get parameters.
I wrote a repository for you to take a look:
https://bitbucket.org/magstaging/controllerwithjavascript/src/master/


text:
Q: CloudPanel installation is not successful This is what i am getting when I install CloudPanel on Debian 10.
    cp: cannot create regular file '/usr/sbin/clp-nginx': Text file busy
    dpkg: error processing package cloudpanel (--configure):
     installed cloudpanel package post-installation script subprocess returned error exit status 1
    Errors were encountered while processing:
     cloudpanel
    E: Sub-process /usr/bin/dpkg returned an error code (1)

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The installation of CloudPanel is complete!

    CloudPanel can be accessed now:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It shows as installation completed. But CloudPanel access url does not come.
How I can sort it or remove CloudPanel. [I cannot find a way to uninstall the cloudpanel.]

A: I know it's kind of late but hope this helps.
However,I apoligize because I didn't fully document how I uninstall cloudpanel (I was just trying random things).
---WARNING. READ BEFORE RUNNING STEP 1--- First step could cause more problems and you'll probably get a bunch of errors more.
NOTE: I rebooted many times, maybe rebooting it after every step could help
1 . My first step was to find where cloudpanel was located and then I removed /tmp/cloudpanel and /usr/share/doc/cloudpanel
dpkg -L cloudpanel
sudo rm -rf /tmp/cloudpanel
sudo rm -rf /usr/share/doc/cloudpanel

After that I remember I tried to run sudo apt remove cloudpanel but that just caused more problems and I don't really think this helped me at all but I add this step here just to let you know all what I did.
2 . I moved to /home and remove every possible folder created by cloudpanel
sudo rm -rf /home/clp
sudo rm -rf /home/mysql

3 . After rebooting I deleted the user created by cloudpanel.
sudo userdel clp

In the case that you are not able to delete the user try rebooting again and/or killing all processes by clp.
sudo killall --user clp && sudo userdel clp

4 . Remove cloudpanel from sudoers
sudo rm -rf /etc/sudoers.d/cloudpanel

*Delete cloudpanel's info from dpkg and configure dpkg
sudo rm -rf /var/lib/dpkg/info/cloudpanel
sudo dpkg --configure -a

*Now you should be able to uninstall cloudpanel
sudo apt remove cloudpanel
sudo apt autoremove
I don't know what exactly did it and I don't really think sped 1 is required.
Hope it helps!

A: terminate and relaunch a new blank vm
see here https://discordapp.com/channels/696694788883349574/696697364114702368/975695566744993842
Reply from the sole developer


text:
Q: When routing power how is a safe current-carrying wire configuration determined with multiple wires? I've been looking at a device/power-supply pair I was sent recently for a project.
The device specs say it needs 24V and will draw 10A max.
The power supply provides 24V @ 9A (14A peak).
The power supply has 3 posts for V+ and 3 posts for GND (call them V0, V1, V2, G0, G1, and G2 respectively).
The cable that was supplied bundles 14 24 AWG wires, connected into a molex receptacle such that 2 wires go to V0, 2 to V1, 3 to V2, 2 to G0, 2 to G1, and 3 to G2.
I looked at a load-limit table for 24 AWG wire and it says that for chassis wiring, the wire is rated for 3.5A max and for power transmission 0.577A max.
Since the device can draw up to 10A, clearly a single piece of 24 AWG would be too small to be safe in this configuration.
The only conclusion I can draw from this is that using 7 wires across 3 terminals spreads the current load out such that 24 AWG is safe.
My questions, if you've managed to get this far are:
1) What is the calculation to determine the correct minimum number of smaller gauge wires to use in such a setup (i.e. where you're replacing a single larger wire)?  Is it simply max current draw / number of wires?
2) How is the voltage drop due to the wire length calculated when using multiple wires (I know how to do it with one wire)?
Thank you!

A: *

*Determine the cross-sectional area of the wire being replaced, and then divide that by the cross-sectional area of the smaller wire in order to determine how many smaller wires you'll need to equal the cross-sectional area of the larger wire.  If the quotient isn't an integer, ALWAYS round up to the next largest integer.

*Determine the resistance of one wire as you normally would, and then the resistance of the cable will be that of the resistances of the separate conductors all connected in parallel.  The voltage drop across the cable will then be the product of the current through the cable and its resistance.


text:
Q: useState returns initial value and not updated value I am forcing below code to run through the catch block where it sets getFoodCategoriesFailed to true and after that when it goes to finally block it still shows getFoodCategoriesFailed as false which is its initial value. Can someone point it out what I am doing wrong and help me fix it.
const [getFoodCategoriesFailed, setGetFoodCategoriesFailed] = useState(false);

const getCategories = async (url) => {
  const { request } = await requestor.get({ url });

  request.then((response) => {
    setFoodCategories(response);
    setGetFoodCategoriesFailed(false);
  }).catch(() => {
    setFoodCategories(undefined);
    setGetFoodCategoriesFailed(true);
  }).finally(() => {
    onFoodCategoriesRetrieved(getFoodCategoriesFailed, foodCategories?.food_categories);
  });
};

useEffect(() => {
  const url = "xyz";
  getCategories(url);
}, [foodCategories]);

A: useState does not change synchronously
Is useState synchronous?
If you want to use useState synchronously, use the code below
import { useState, useRef, useEffect } from 'react';

export default function useStateCallback(initialState) {
  const [state, setState] = useState(initialState);
  const cbRef = useRef(null); // mutable ref to store current callback

  // eslint-disable-next-line no-shadow
  const setStateCallback = (state, cb) => {
    cbRef.current = cb; // store passed callback to ref
    setState(state);
  };

  useEffect(() => {
    // cb.current is `null` on initial render, so we only execute cb on state *updates*
    if (cbRef.current) {
      cbRef.current(state);
      cbRef.current = null; // reset callback after execution
    }
  }, [state]);

  return [state, setStateCallback];
}

A: I'm not an expert so apologies if this doesn't help, but ... there's a couple of things I might try:

*

*Think about whether it might make sense to move onFoodCategoriesRetrieved into the (or as a new) useEffect call (and add getFoodCategoriesFailed to the dependency list).

*Something like:
const getCategories = async (url) => {
  const { request } = await requestor.get({ url });
  let localFoodCategories = undefined;
  let localGetFoodCategoriesFailed = true;

  request.then((response) => {
    localFoodCategories = response;
    localGetFoodCategoriesFailed = false;
  }).catch(() => {
  }).finally(() => {
    setFoodCategories(localFoodCategories);
    setGetFoodCategoriesFailed(localGetFoodCategoriesFailed);
    onFoodCategoriesRetrieved(localGetFoodCategoriesFailed, localFoodCategories?.food_categories);
  });
};


text:
Q: Optimizing GROUP BY + jsonb_each on large table I am trying to optimize a request over a table using a jsonb field.
Here is my table structure:
CREATE TABLE data_insight (
  uuid UUID PRIMARY KEY NOT NULL,
  name VARCHAR(255),
  meta JSONB,
  data JSONB,
  insight_type_id UUID NOT NULL
);

CREATE INDEX ON data_insight ('insight_type_id');
CREATE INDEX ON data_insight ('meta');

In the meta column, I have filtering informations for the data in this table ; those filtering informations are unknown when I write my code and can vary from one insight to the other (depending on the insight_type_id).
What I need to get is the list of (key, values) from this meta column in order to let my user choose between them (with some filters applied). Currently, my request look like this:
SELECT "key", "value" FROM "data_insight"
LEFT JOIN jsonb_each("data_insight"."meta") ON TRUE
WHERE  "data_insight"."insight_type_id" = '64ff223c-be7d-435c-b83b-3649fa017f17'
GROUP BY "value", "key";

This request take up to 30 seconds to execute (there are around 4 million rows in the table, and a little less than 1 million of them are a part of the insight_type_id of my test request). Here is a result of an EXPLAIN ANALYZE query for it:
Group  (cost=934323.86..934373.75 rows=100 width=64) (actual time=5403.970..5472.750 rows=435 loops=1)
  Group Key: jsonb_each.value, jsonb_each.key
  ->  Gather Merge  (cost=934323.86..934371.75 rows=400 width=64) (actual time=5403.968..5470.881 rows=1938 loops=1)
        Workers Planned: 4
        Workers Launched: 4
        ->  Sort  (cost=933323.80..933324.05 rows=100 width=64) (actual time=5190.508..5190.543 rows=388 loops=5)
              Sort Key: jsonb_each.value, jsonb_each.key
              Sort Method: quicksort  Memory: 60kB
              Worker 0:  Sort Method: quicksort  Memory: 57kB
              Worker 1:  Sort Method: quicksort  Memory: 61kB
              Worker 2:  Sort Method: quicksort  Memory: 58kB
              Worker 3:  Sort Method: quicksort  Memory: 58kB
              ->  Partial HashAggregate  (cost=933319.48..933320.48 rows=100 width=64) (actual time=5186.490..5186.782 rows=388 loops=5)
                    Group Key: jsonb_each.value, jsonb_each.key
                    ->  Nested Loop Left Join  (cost=0.81..823353.86 rows=21993125 width=64) (actual time=69.452..2962.023 rows=1399327 loops=5)
                          ->  Parallel Index Only Scan using data_insight_meta_insight_type_id_c54dbada_uniq on data_insight  (cost=0.81..383491.85 rows=219931 width=276) (actual time=69.278..751.725 rows=176904 loops=5)
                                Index Cond: (insight_type_id = '64ff223c-be7d-435c-b83b-3649fa017f17'::uuid)
                                Heap Fetches: 35500
                          ->  Function Scan on jsonb_each  (cost=0.00..1.00 rows=100 width=64) (actual time=0.008..0.009 rows=8 loops=884519)

My questions:
1/ The time vary a lot in this request: sometimes it take 5-4 seconds, sometimes it take 30+ seconds. Is there something I should check to understand why?
2/ How could I make this request faster? I cannot remove the jsonb itself ; however, I thought about creating a MATERIALIZED VIEW to store the result of the jsonb_each (well, multiple of them actually, one per insight_type_id), would that help? Or would a simple VIEW be better?
Thank you

A: You are querying a large amount of data to get a small result.  That is never going to be blazing fast.  If you really need to do this, a materialized view is probably the best.  But you want to materialize after the group-by has massively deduplicated the data.
create materialized view insight_type_choices as
SELECT "data_insight"."insight_type_id", "key", "value" FROM "data_insight"
LEFT JOIN jsonb_each("data_insight"."meta") ON TRUE
GROUP BY "data_insight"."insight_type_id", "value", "key";

It seems unlikely that you actually do want that join to really be a LEFT JOIN, but I left it that way since that is how you wrote it.  I would throw a count column on there as well, because it would basically be free and if it ever generates thousands of options, you will probably want a way to rank them.


text:
Q: SQL Replication in C# mobile device application I have a mobile application (CE) running on a Motorola Symbol 3090 which should allow for scanning  of inventory items and changing their properties on our SQL server (The table has existed on the server for years and now they want a way to use mobile devices to update).
Here is the problem I am facing which needs addressing.

*

*Our warehouse is very large and spans over multiple locations so inevitably we have dead zones in the warehouse so having a constant connection is not possible. What I have proposed is a way to go in offline mode and have an up to date copy of our inventory on local device. This would allow all transactions to be found and recorded locally. When the device is returned to cradle or back to wifi it updates the database. With this proposal i'm not sure if SQL Replication is the best way to handle this type of application.

Was hoping some more experienced mobile device developers had any input into the design scheme.
I have only been developing on these types of systems (Motorola symbol 3090) for about 2 months now and have no background knowledge in SQL Replication. I understand the basics of what replication is doing but that is about the extent of my knowledge on the subject.

A: As ErikEJ points out in the comment above, Merge Replication would work well for this scenario.  Here are some resources to get you started:

*

*MSDN's 'explanation'

*Rob Tiffany's Book

*Chris Fairbairn's blog

*Erik's Library


text:
Q: Replace selected drop down list option with corresponding code onEdit at Google sheets I have a file with several worksheets. In the "J4:BA1000" of some of these sheets are drop down options where the user can select letters from A to I. What I'm trying to achieve is that upon selection, the selected option is replaced by its corresponding code: 1 to 9. With this, I tried out the code below, which is also something I saw from stack overflow. However, it's not working and I'm not sure why. I believe the logic is correct, the sheet names are exact and the conditions are there.
Likewise, I believe there's an improvement on how I do the checking of sheet names to avoid the multiple || (or), and as well the changing of values to avoid the multiple ifs.
function onEdit(e) {
  var SS = SpreadsheetApp.getActiveSpreadsheet();
  var ss = SS.getActiveSheet();
  var sheetName = ss.getName();
  var range = e.getRange;
  var targetrange = ss.getRange("J4:BA1000");
  var cell = range.getValue();

  if ( sheetName == "Kalos" || sheetName == "Logos" || sheetName == "Atos" || sheetName == "Manos" || sheetName == "Sodos" || sheetName == "Antos" || sheetName == "Minos" || sheetName == "Ambos" ) {
    if (Checkkk(targetrange,range)){
      if(cell == 'A'){range.setValue("1");}
      if(cell == 'B'){range.setValue("2");}
      if(cell == 'C'){range.setValue("3");}
      if(cell == 'D'){range.setValue("4");}
      if(cell == 'E'){range.setValue("5");}
      if(cell == 'F'){range.setValue("6");}
      if(cell == 'G'){range.setValue("7");}
      if(cell == 'H'){range.setValue("8");}
      if(cell == 'I'){range.setValue("9");}
    }
  }
}

function Checkkk(R1, R2) {

  var LR1 = R1.getLastRow();
  var Ro2 = R2.getRow();
  if (LR1 < Ro2) return false;

  var LR2 = R2.getLastRow();
  var Ro1 = R1.getRow();
  if (LR2 < Ro1) return false;

  var LC1 = R1.getLastColumn();
  var C2 = R2.getColumn();
  if (LC1 < C2) return false;

  var LC2 = R2.getLastColumn();
  var C1 = R1.getColumn();
  if (LC2 < C1) return false;

return true;

}

So just to explain the logic, when I perform an edit, it checks if the edited cell is within the several sheets inf the first IF. If TRUE, it then checks using the Checkkk function if the edited cell is within J4:BA1000. If TRUE, it then checks if the selected value is within A to I. If TRUE it replaces that letter with its corresponding code, which is from 1 to 9. Again, I think the code is logically correct; I'm just not sure where's the mistake here.

A: Answer:
To get the range of an event object you need to use e.range, not e.getRange.
Code:
I also changed your initial Sheet name checking condition to make it slightly more efficient, and removed the need for multiple ifs in the block by changing subsequent if blocks to else ifs:
function onEdit(e) {
  var sheetNames = ["Kalos", "Logos", "Atos", "Manos", "Sodos", "Antos", "Minos", "Ambos"];
  var SS = SpreadsheetApp.getActiveSpreadsheet();
  var ss = SS.getActiveSheet();
  var sheetName = ss.getName();

  if (!(sheetNames.indexOf(sheetName) > -1)) {
    return;
  }

  var range = e.range;
  var targetrange = ss.getRange("J4:BA1000");
  var cell = range.getValue();

  if (Checkkk(targetrange, range)){
    if(cell == 'A'){range.setValue("1");}
    else if(cell == 'B'){range.setValue("2");}
    else if(cell == 'C'){range.setValue("3");}
    else if(cell == 'D'){range.setValue("4");}
    else if(cell == 'E'){range.setValue("5");}
    else if(cell == 'F'){range.setValue("6");}
    else if(cell == 'G'){range.setValue("7");}
    else if(cell == 'H'){range.setValue("8");}
    else if(cell == 'I'){range.setValue("9");}
  }
}

I didn't change your Checkkk function at all.
References:

*

*Event Objects | Apps Script


text:
Q: iOS Swift3 TextView line at wrong position I have a textView which i use as an input field for chatMessages. I want it to expand if there is more text than could fit in one row.
func textViewDidChange(_ textView: UITextView) {
    self.textViewHeight.constant = textView.contentSize.height
}

I set a height constraint programmatically if the user enters something inside the textView.
 <- For one liners it looks fine.
 <- After you press enter it gets hidden.
 <- The second enter shows it up again.
What am i doing wrong here? I try to recreate the look of whatsapp / imessage, where this hiding does not happen.

A: This is because you are changing the size in the wrong delegate function. The delegate textViewDidChange is called after you finished editing (resignFirstResponder gets called).
You should put your code to change the height in this function instead:
optional func textView(_ textView: UITextView,
    shouldChangeTextIn range: NSRange,
       replacementText text: String) -> Bool

So this will change the height of the UITextView as you type not after you finished typing.


text:
Q: Python set variable in switch statement i try to set variables dependend on the type with an switch case statement.
I have a class rule with looks as following:
class rule:

    def __init__(self):
        name = ""
        src = ""

    def setName(self, name):
        self.__name = name

    def getName(self):
        return self.__name
    name = property(getName, setName)

    def setSrc(self, src):
        self.__src = src

    def getSrc(self):
        return self.__src
    src = property(getSrc, setSrc)

and a text file as following
option <type> <value>
option name myname
option src anysrc

I search for the string option and get the secound and third string. as far as good.
e.g. (qick and dirty):
with open("file") as f:
    for line in f:
        if line.find('option') != -1:
            type(line.split(' ')[1], line.split(' ')[2])

Now I have write a switch case statement to set variable in object rule.
def type(option, value):
    switcher = {
        "name": rule.name = value,
        "src": rule.src = value,
    }
    switcher.get(option, lambda: "Invalid Option")

But this will not work, I face following:
  File "./read.py", line 112
    "name": rule.name = value,
                      ^
SyntaxError: invalid syntax

I have no idea how to solve this issue or how to solve this by an other way.
Any idea how to solve this issue?

A: Python has no switch statement. The common replacement - as you already seem to know - is using a dictionary to dispatch different behaviors. With that being the case however, the syntax you're trying to use simply isn't allowed for dictionaries. Dictionary key values should be expressions. You can work around this by using anonymous functions and setattr. Here's a self-contained example:
>>> class Dummy:
        pass

>>> dummy = Dummy()
>>> dic = {
    'a': lambda: setattr(dummy, 'a', 0),
    'b': lambda: setattr(dummy, 'b', 0)
}
>>> dic.get('a', lambda: print("Invalid Option"))()
>>> dummy.a
0
>>> dic.get('b', lambda: print("Invalid Option"))()
>>> dummy.b
0
>>> dic.get('x', lambda: print("Invalid Option"))()
Invalid Option
>>>

A: you are actually not defining a switch statement up there:
switcher = {
    "name": rule.name = value,
    "src": rule.src = value,
}

This is a dictionary, and the interpreter is complaining about the statements as value there.
You could just reference your methods like this:
def type(option, value):
    switcher = {
        "name": rule.setName,
        "src": rule.setSrc
    }

    method = switcher.get(option, lambda: "Invalid Option")
    method(rule, value)

Another idea
Here is another aproach. Maybe something like this is helpful:
def type(rule, option, value):
    if hasattr(rule, option):
        setattr(rule, option, value)
    else:
        print("Invalid Option") # Some error handling

Explicitly checking the option name
@PaulPanzer pointed out, that it is maybe in your intention to explicitly check weather options are correct. So here is a more secure version of the typefunction:
def type(rule, option, value):
    if option in ["name", "src"]:
        setattr(rule, option, value)
    else:
        print("Invalid Option") # Some error handling

This implies that you have to change the code in two different places, whenever you extend your file format. But this is a question of how defensive you want to be, how often the rules get extended and how much flexibility you need.


text:
Q: LDAP search query (using or) not returning values I am using the following query in LDAP:
ldapsearch -D "uid=test,cn=Users,cn=accounts,dc=earthlinktele,dc=com" -w dsaasddsa -b "cn=accounts,dc=earthlinktele,dc=com" "(&(|(objectcategory=person)(objectClass=account)(objectClass=posixAccount)(objectClass=inetOrgPerson)(objectClass=user)(objectClass=userProxy))(|(samaccountname=test)(displayName=test)(userprincipalname=test)(uid=test)))"

but it doesn't return any results, although the (uid=test) and (objectClass=posixAccount) are TRUE and they are preceded by the OR operator. To check if the user have a permissionto search LDAP I used the following filter which successfully returned the desired results:
(&(objectClass=posixAccount)(uid=test))

I also tried using the admin user as "BindDN" which returned the results.
ldapsearch -D "uid=admin,cn=Users,cn=accounts,dc=earthlinktele,dc=com" -W -b "cn=accounts,dc=earthlinktele,dc=com" "(&(|(objectcategory=person)(objectClass=account)(objectClass=posixAccount)(objectClass=inetOrgPerson)(objectClass=user)(objectClass=userProxy))(|(samaccountname=test)(displayName=test)(userprincipalname=test)(uid=test)))"

Why is the first search not working?? do I have to give the "test" user any permissions??


text:
Q: Typo correction in IntelliJ I've moved from Eclipse to IntelliJ, and I love it!
One thing I miss though, is the suggestions to correct typos of fields and the like.
For example:
int myfield = 5;
myField++;

This would give me a lightbulb quick fix to Change to 'myfield'.
In IntelliJ, the closest I've come to this functionality is the Rename Refererence suggestion, which isn't quite as quick, especially in classes with many other fields.
Is there a way to achieve this behaviour in IntelliJ?

A: In IntelliJ 13.x, go to Settings > IDE Settings > Editor > Code Completion. Make sure Autopopup Code Completion is checked. This will auto suggest myfield when you start typing myField, and you can select with cntl-space (or the mouse).
It will even correct it automatically if you just type a space in myField if you have Insert selected variant by typing dot, space, etc. checked. Also check out Auto-insert when only one choice
IntelliJ settings docs


text:
Q: Is there a way to configure Alamofire to not dispatch results to the main queue? I am building with an iOS application framework that is already opinionated about how the output of effects (such as network calls) should be dispatched back to the main queue.
Ergo, using my application framework and Alamofire in stock configuration, I believe Alamofire is dispatching my result to the main queue, and then my application framework is re-dispatching the result to the main queue. This is not a show-stopping problem, but it is a small performance penalty that I do not need to pay, if I could configure Alamofire to not perform that final dispatch back to the main queue.
Basically, I would like to configure Alamofire to behave like vanilla URLSession, where it is the caller's responsibility to dispatch back to the main queue.
I have read the Alamofire docs describing the handful of queues you can pass in to an Alamofire Session to configure where different parts of the Alamofire pipeline happen, but I can't quite figure out if there a configuration I can set up to effectively opt out of that last dispatch for the response handler.
Thanks for any thoughts.

A: All of Alamofire's features that dispatch to the main queue can take a specific queue instead, but you can't set a default for all of them at once. For instance, if you want your response handlers to be called on a specific queue, pass that queue to the response handler: responseDecodable(queue: someQueue). Otherwise all of Alamofire's internal events happen on a specific set of queues, such as the Session's rootQueue, which you can also use for the other features.


text:
Q: how to divide a series by a series type using np.arange I am wanting to do what the png illustration I've uploaded has, mainly have two columns with numbers in them. The code with the asterisk gets me the class and the 'SquareMiles'. The percentage column is more difficult to get. I am dividing an array of series numbers by the total series for that column with no success. How can this division go to completion?
Total = ca_land.get("SquareMiles")
Total1 = Total.sum()

percent = np.arange(Total/Total1)

* ca_classess = ca_land.groupby('Class').sum()

ca_classes = ca_classess.assign(
    Percentage = percent

)

Sample Data:
{'Class': {52: 'Forest & Woodland',   126: 'Forest & Woodland',   128: 'Forest & Woodland',   131: 'Forest & Woodland',   133: 'Forest & Woodland'},  'EcologicalSystem': {52: 'East Gulf Coastal Plain Near-Coast Pine Flatwoods - Open Understory Modifier',   126: 'California Central Valley Mixed Oak Savanna',   128: 'California Coastal Closed-Cone Conifer Forest and Woodland',   131: 'California Coastal Live Oak Woodland and Savanna',   133: 'California Lower Montane Blue Oak-Foothill Pine Woodland and Savanna'},  'SquareMiles': {52: 0.03266424261286,   126: 4350.262402786333,   128:
85.94309723386156,   131: 1726.1481557315549,   133: 6587.099312156705}}

A: I think here is necessary divide SquareMiles column after aggregating sum:
d = {'Class': {52: 'Forest & Woodland1', 126: 'Forest & Woodland1', 128: 'Forest & Woodland1', 131: 'Forest & Woodland', 133: 'Forest & Woodland'}, 'EcologicalSystem': {52: 'East Gulf Coastal Plain Near-Coast Pine Flatwoods - Open Understory Modifier', 126: 'California Central Valley Mixed Oak Savanna', 128: 'California Coastal Closed-Cone Conifer Forest and Woodland', 131: 'California Coastal Live Oak Woodland and Savanna', 133: 'California Lower Montane Blue Oak-Foothill Pine Woodland and Savanna'}, 'SquareMiles': {52: 0.03266424261286, 126: 4350.262402786333, 128: 85.94309723386156, 131: 1726.1481557315549, 133: 6587.099312156705}}
ca_land = pd.DataFrame(d)

Total1 = ca_land['SquareMiles'].sum()
ca_classes = (ca_land.groupby('Class').sum()
                     .assign(Percentage=lambda x: x['SquareMiles'] / Total1))
print (ca_classes)
                    SquareMiles  Percentage
Class
Forest & Woodland   8313.247468    0.652046
Forest & Woodland1  4436.238164    0.347954

Or solution without assign is better readable:
ca_classes = ca_land.groupby('Class').sum()
ca_classes['Percentage'] =  ca_classes['SquareMiles'] / ca_land['SquareMiles'].sum()
print (ca_classes)
                    SquareMiles  Percentage
Class
Forest & Woodland   8313.247468    0.652046
Forest & Woodland1  4436.238164    0.347954


text:
Q: Some rounding algorithms support in .NET I need to use some rounding algorithms, from my c# application:
systematic:

random:

and controlled:

Does .NET Framework provide math support for this algorithms (maybe there any free libraries available for c#) or I need to implement this functions on my own ? How can I check correctness of the algorithms if I implement them, to be sure they are right ? Does anyone have sample input and output data for it ? Are there any free applications I can compare my calculated results for sample input with ?

A: Perhaps these articles can serve as a starting point?

*

*Adventures in .NET Rounding Part 1: The Mystery of Math.Round

*Adventures in .NET Rounding Part 2: Exotic Rounding Algorithms

*Adventures in .NET Rounding Part 3: Rounding in Action


text:
Q: how do I make my script HTML 5 compliant I am an middle school student learning web programming . I am finding it tough to understand how my browser can understand if my code is HTML or HTML 5 . For example how do I know if my code is HTML or HTML 5 , will any HTML code with the addition of HTML 5 attributes become HTML 5 or is there something to do with the doctype declarations ? I understand this question may be vague or downright stupid but I would appreciate any help.

A: If you're trying to distinguish between a HTML5 document from an older version of HTML, I'd suggest looking at the DOCTYPE, which is perhaps the easiest way. If it looks like
<!DOCTYPE html>

it means that it is HTML5. Aditionally, if any new HTML5 elements are present in the document.
For further reading on the subject.


text:
Q: mongoid association reference to an embedded model I have following setup
Class Country
  include Mongoid::Document

  field :name
  field :code

  has_many :locations
end

Class Location
  include Mongoid::Document

  field :country
  field :region
  field :city

  has_many :locations
  embedded_in :company
end

Class Company
  include Mongoid::Document

  field :name

  embeds_one :location
  accepts_nested_attributes_for :location
end

Countries model is seeded with all the countries.
Countries get stored with their 2-letter shortcode in Location model through a nested form. For example "US".
Now I want to call @company.location.country.name in the the View to get "United States", however I'm getting an error
undefined method `name' for nil:NilClass

How do I go about doing this?
What's the best way?
I'm new to MongoDB so I apologize if this is a stupid question

A: I think your problem is related to the reverse relation you are defining on Country. Yes, a Location can have a Country but the Country can't link to the Location as it's an embedded document.
Try removing the has_many :locations in the Country class. This should solve it. Don't define a reverse relation if you don't need it.
If you need the reverse relation you probably don't want it as an embedded document.

A: This won't work for the given reasons (embedded & relations).
On an other side, for your issue, you shouldn't store the full name of countries in your db.
Indeed this is a "fixed" list, and to be precise, it is ISO-3166-1. Embrace the standards when there is one (rare!). A good way is to use locales (and you spare the seeding, syncing, updating parts).
Considering the file config/locales/iso-3166-1/en.yml :
en:
  countries:
    AD: "Andorra"
    AE: "United Arab Emirates"
    AF: "Afghanistan"
    AG: "Antigua and Barbuda"
    ...

Now, you can use I18n.t(@mylocation.country, :scope => :countries).
Bonus, it is i18n / l10n ready: config/locales/iso-3166-1/fr.yml :
fr:
  countries:
    AD: "Andorre"
    AE: "Émirats arabes unis"
    AF: "Afghanistan"
    AG: "Antigua-et-Barbuda"
    ...


text:
Q: Size of the embeded PDF document in Rmarkdown I'm trying to embed a pdf document in a Rmarkdown document generated by KnitR using \includepdf. It works but included documents are very small:

The reproducible example below:
---
output: pdf_document
header-includes:
- \usepackage{pdfpages}
---
```{r, echo=FALSE}
url = 'https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf'
download.file(url, 'gg.pdf')
```
\includepdf[pages=-]{gg.pdf}

Is there a way to resize the inserted document to its original size?
I've found a possible solution but I don't know how to implement it in KnitR:
https://tex.stackexchange.com/questions/264383/pdfpages-does-not-correctly-scale-inserted-pdf-pages


text:
Q: Bug with recursive functions? I'm trying recursive functions in z3, and I'm curious if there's a bug with model construction. Consider:
(define-fun-rec f ((x Int)) Int
                  (ite (> x 1)
                       (f (- x 1))
                       1))
(check-sat)
(get-value ((f 0)))

Here f is actually the constant function 1, just defined in a silly way. For this input, z3 prints:
sat
(((f 0) 0))

This seems incorrect, since f 0 should equal 1.
What's interesting is if I assert what z3 proposes as the result, then I get the correct unsat answer:
(define-fun-rec f ((x Int)) Int
                  (ite (> x 1)
                       (f (- x 1))
                       1))
(assert (= (f 0) 0))
(check-sat)

I get:
unsat

So, it looks like z3 actually does now that f 0 cannot be 0; even though it produced that very model in the previous case.
Taking this one step further, if I issue:
(define-fun-rec f ((x Int)) Int
                  (ite (> x 1)
                       (f (- x 1))
                       1))
(assert (= (f 0) 1))
(check-sat)
(get-model)

Then z3 responds:
sat
(model
  (define-fun f ((x!0 Int)) Int
    1)
)

which is indeed a reasonable answer.
So, it seems perhaps there's a bug with recursive function models under certain conditions?

A: The models used not to reflect the graph of recursive function definitions.
So when evaluating recursive functions on values that had not been seen during solving it could produce arbitrary results. This behavior is now changed as the recursive definitions are included in models.


text:
Q: How to speed up nested for-loop logic in Python with Product? I would like to check out whether the field of table TestProjectcontains the parameter from the Client-side passed, nested for loop is ugly, is there any efficient and easy way to realize it? Thanks so much for any advice.
def test(parameter_a: list, parameter_c: str, parameter_b: list=None) -> bool:
    """
      If project_code contains parameter_a and product_code contains
      parameter_b, product_code must contains parameter_c """
    project_code = TestProject.project_code
    product_code = TestProduct.product_code

    for pj_code in project_code:
        for param in parameter_a:
            if pj_code[:len(param)] == param:
                for pd_code in product_code:
                    for p in parameter_b:
                        if (pd_code[:len(p)] == p):
                            for pc in parameter_c:
                                if pd_code[:len(pc)] == pc:
                                    return True
                            return False
    return True

According to Sayandip Dutta's answer to this speed up nested for-loop logic in Python with itertools.product and all
Can I change my original code to this? I have no data to test, I have to ensure my logic is correct. Is the below code right? If correct, is it really faster than my original code? if not correct, is there anyone who can tell me how to realize it? Thanks so much for any advice.
from itertools import product

def test(parameter_a: list, parameter_c: str, parameter_b: list=None) -> bool:
    project_code = TestProject.project_code
    product_code = TestProduct.product_code

    return (
        all(code.startswith(p) for code, p in product(project_code, parameter_a))
        and all(code.startswith(p) for code, p in product(product_code, parameter_b))
        and all(code.startswith(p) for code, p in product(product_code, parameter_c))
    )


text:
Q: jQuery on click have to click twice for modal dialog to appear Im using Dialog. When I click to open Dialog, I always have to click twice. I have tried many many solutions but Its not working.
jQuery(result).on('click', function() {
  jQuery(why).dialog({
    create: function (event, ui) {
      jQuery(".ui-corner-all").css('border-radius','0px !important');
    },
    autoOpen: true,
    title: "Whois Info",
    width: 1170,
    height: 600,
    modal: true,
    buttons: {
      Close: function() {jQuery(this).dialog("close");return false;}
    }
   });
 });

A: you don't need to initialize the dialog each and every time on the button click. Move the initialization part into document.ready function. Then inside the click function just write code to make the dialog visible.
something like:
$( function() {
jQuery("#id").dialog({
    create: function (event, ui) {
      jQuery(".ui-corner-all").css('border-radius','0px !important');
    },
    autoOpen: true,
    title: "Whois Info",
    width: 1170,
    height: 600,
    modal: true,
    buttons: {
      Close: function() {jQuery(this).dialog("close");return false;}
    }
   });

jQuery(result).on('click', function() {
   jQuery("#id).dialog('open');
});

});


text:
Q: há algum erro nesse código que eu fiz, "deixando a página para cima" o código em si, está certo, mas quando eu o coloco em um , parece que o conteudo fica para cima, deixando os componentes seguintes para cima
preciso descobrir o erro:
.thumb {
    width:33%;
    height:auto;
    text-align:center;
    float:left;
}
@media screen and (max-width:800px) {
    .thumb {
        float: none;
        text-align:center;
        vertical-align:middle;
        width: 100%;
        width:auto;
    }
}

e eu uso dessa forma para manter alinhado:

TESTE

TESTE

aí está o jsFiddle como solicitado:
novo jsFiddle
no primeiro momento parece estar tudo certo, porém quando você redimensiona a tela do jsFiddle, consegue ver o erro
preciso muito descobrir isso!!
alguem pode me ajudar??

A: Em vez de float: left; e float: none; podes usar display: block; e display: inline-block; e evitas os efeitos colaterais que o float gera.
Ficaria assim: https://jsfiddle.net/4rsr99sj/
.thumb {
    width: 33%;
    height: auto;
    text-align: center;
    float: left;
}

@media screen and (max-width:800px) {
    .thumb {
        float: none;
        text-align: center;
        vertical-align: middle;
        width: 100%;
        width: auto;
    }
}


text:
Q: How to make table truncation query as dynamic SQL I would like to make the below query as dynamic SQL .
Query 1 : Table Truncation
select 'Truncate Table '+''+ name from sys.tables where name like '%RND%'

Query 2 :
select 'Insert into  '+''+ name +'Select * from '+'.'+''+ name from sys.tables where name like '%RND%'

A: By using the following dynamic query you can truncate the required tables:
DECLARE @DynamicSQL AS VARCHAR(MAX) = '';

SELECT @DynamicSQL = @DynamicSQL + 'TRUNCATE TABLE ' + QUOTENAME(NAME) + '; '
FROM sys.tables
WHERE NAME LIKE '%RND%';

--PRINT @DynamicSQL
EXEC (@DynamicSQL)

For the second query the dynamic query is :
DECLARE @DynamicSQL1 AS VARCHAR(MAX) = '';

SELECT @DynamicSQL1 = @DynamicSQL1 + 'INSERT INTO ' + QUOTENAME(NAME) + ' SELECT * FROM ' + QUOTENAME(NAME) + '; '
FROM sys.tables
WHERE NAME LIKE '%RND%';

--PRINT @DynamicSQL1
EXEC (@DynamicSQL1)

A: This might be what you are looking for
All statements are collected in a table, ordered by their point of insert (id is IDENTITY). It will be - for sure - no problem for you to build your second statement in the same way...
DECLARE @cmdTbl TABLE(id INT IDENTITY,cmd NVARCHAR(MAX));

INSERT INTO @cmdTbl(cmd)
SELECT 'TRUNCATE TABLE ' + QUOTENAME(t.TABLE_CATALOG) + '.' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME) + ';'
FROM INFORMATION_SCHEMA.TABLES  AS t
WHERE t.TABLE_NAME LIKE '%RND%'

--After collecting all statements I use a CURSOR to execute them one after the other.
DECLARE @cmd VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT cmd FROM @cmdTbl ORDER BY id;
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd;
    --EXEC(@cmd); --For syntax check you start without EXEC...
    FETCH NEXT FROM cur INTO @cmd;
END
CLOSE cur;
DEALLOCATE cur;

A: Step 1:
vi truncate_count.sql
use dbname
go
---generate truncate table statements
select 'Truncate Table '+''+convert(varchar(30),o.name)+'
go' as table_name
from sysobjects o
where type = 'U'
order by table_name
go

---check the table count
select 'select count(1) from  '+''+convert(varchar(30),o.name)+'
go' AS table_name
from sysobjects o
where type = 'U'
order by table_name
go

Step 2:
isql -U<USER> -S<server> -P<pwd> -w999 -D<dbname> -e -itruncate_count.sql  -otruncate_count1.sql

Step 3:
Add the below lines at the starting of the file truncate_count1.sql
use dbname
go

isql -U<USER> -S<server> -P<pwd> -w999 -D<dbname> -e -itruncate_count1.sql  -otruncate_count1.log


text:
Q: Device: /dev/sda [SAT], 1 Currently unreadable (pending) sectors I have a software RAID 1 array on RHEL.  I am getting this error emailed to me each morning:  Device: /dev/sda [SAT], 1 Currently unreadable (pending) sectors
When I run a test on sda (or sdb) everything appears to pass.  Am I missing something?

mdstat shows the RAID array is fine:
# cat /proc/mdstat
Personalities : [raid1]
md5 : active raid1 sdb5[1] sda5[0]
      108026816 blocks [2/2] [UU]

md1 : active raid1 sdb1[1] sda1[0]
      511936 blocks [2/2] [UU]

md2 : active raid1 sda2[0] sdb2[1]
      805306304 blocks [2/2] [UU]

md3 : active raid1 sda3[0] sdb3[1]
      62914496 blocks [2/2] [UU]

unused devices: <none>

Here is the output of:  # smartctl -q noserial -a /dev/sda
I have also tried running: # smartctl -t long /dev/sda

smartctl 5.43 2012-06-30 r3573 [x86_64-linux-2.6.32-279.9.1.el6.x86_64] (local build)
Copyright (C) 2002-12 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF INFORMATION SECTION ===
Model Family:     Hitachi Ultrastar A7K1000
Device Model:     Hitachi HUA721010KLA330
Firmware Version: GKAOAB0A
User Capacity:    1,000,204,886,016 bytes [1.00 TB]
Sector Size:      512 bytes logical/physical
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   7
ATA Standard is:  ATA/ATAPI-7 T13 1532D revision 1
Local Time is:    Sun May 21 17:51:42 2017 CDT
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x84) Offline data collection activity
                    was suspended by an interrupting command from host.
                    Auto Offline Data Collection: Enabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        (15354) seconds.
Offline data collection
capabilities:            (0x5b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    No Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   1) minutes.
Extended self-test routine
recommended polling time:    ( 255) minutes.
SCT capabilities:          (0x003f) SCT Status supported.
                    SCT Error Recovery Control supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000b   098   098   016    Pre-fail  Always       -       4
  2 Throughput_Performance  0x0005   100   100   054    Pre-fail  Offline      -       0
  3 Spin_Up_Time            0x0007   122   122   024    Pre-fail  Always       -       550 (Average 591)
  4 Start_Stop_Count        0x0012   100   100   000    Old_age   Always       -       68
  5 Reallocated_Sector_Ct   0x0033   100   100   005    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x000b   100   100   067    Pre-fail  Always       -       0
  8 Seek_Time_Performance   0x0005   100   100   020    Pre-fail  Offline      -       0
  9 Power_On_Hours          0x0012   094   094   000    Old_age   Always       -       43202
 10 Spin_Retry_Count        0x0013   100   100   060    Pre-fail  Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       68
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       751
193 Load_Cycle_Count        0x0012   100   100   000    Old_age   Always       -       751
194 Temperature_Celsius     0x0002   090   090   000    Old_age   Always       -       66 (Min/Max 17/72)
196 Reallocated_Event_Count 0x0032   100   100   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0022   100   100   000    Old_age   Always       -       1
198 Offline_Uncorrectable   0x0008   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x000a   200   200   000    Old_age   Always       -       0

SMART Error Log Version: 1
No Errors Logged

SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Short offline       Completed without error       00%     43186         -
# 2  Extended offline    Completed without error       00%     43170         -
# 3  Short offline       Completed without error       00%     43162         -
# 4  Short offline       Completed without error       00%     43138         -
# 5  Short offline       Completed without error       00%     43114         -
# 6  Short offline       Completed without error       00%     43090         -
# 7  Short offline       Completed without error       00%     43066         -
# 8  Short offline       Completed without error       00%     43042         -
# 9  Extended offline    Completed without error       00%     43031         -
#10  Short offline       Completed without error       00%     43024         -
#11  Short offline       Completed without error       00%     43018         -
#12  Extended offline    Completed without error       00%     43002         -
#13  Short offline       Completed without error       00%     42994         -
#14  Short offline       Completed without error       00%     42970         -
#15  Short offline       Completed without error       00%     42946         -
#16  Short offline       Completed without error       00%     42922         -
#17  Short offline       Completed without error       00%     42898         -
#18  Short offline       Completed without error       00%     42874         -
#19  Short offline       Completed without error       00%     42850         -
#20  Extended offline    Completed without error       00%     42833         -
#21  Short offline       Completed without error       00%     42826         -

SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

A: I believe the "197 Current_Pending_Sector" count is is a count of sectors that have failed to read. This does kind of imply that the drive is starting to fail, but it doesn't necessarily mean the drive is bad. If those sectors are re-written the drive firmware can re-map them away and the drive could be fine.
Searching around also finds discussions that suggest some models of SSD drives regularly toggle this to 1 and back, and it might be a mostly harmless firmware bug in the SMART reporting.
So you could just ignore it, and provided your filesystem can handle the occasional bad block read (ie, does some kind of robust raid/redundancy under the hood), it might slowly clear itself as the filesystem overwrites those blocks. If your filesystem cannot handle bad block reads, you could get IO errors every time something tries to read whatever is in that block. You might still be able to recover by finding and deleting that file, and the filesystem will eventually re-write over that sector.
You can also clear the Current_Pending_Sector count by explicitly overwriting those sectors. THIS WILL DESTROY DATA ON THE DISK! This could corrupt the filesystem in ways that could loose all the data on the disk, not just what is lost in the bad sector. So only do this if you can afford to loose all the data on the disk.
You can find the bad sector by running a smart long test;
# smartctl -t long /dev/sda

You can then check the status of the long test to see if its finished, and the LBA of the first error it encountered;
# smartctl -l selftest /dev/sda
smartctl 7.1 2019-12-30 r5022 [x86_64-linux-5.7.0-1-amd64] (local build)
Copyright (C) 2002-19, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF READ SMART DATA SECTION ===
SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Extended offline    Completed without error       00%     17711         12345
# 2  Short offline       Completed without error       00%     17709         -
# 3  Short captive       Interrupted (host reset)      10%       450         -
# 4  Short captive       Interrupted (host reset)      10%       228         -

You can then overwrite the bad sector using dd;
# dd if=/dev/zero of=/dev/sda seek=12345 count=1

Though note that the default bs=512 blocksize might be smaller than the physical sector size on the drive, so you may need to write up to count=8 to wipe it completely. You can then rinse-and repeat the test/overwrite cycle until all the bad sectors are overwritten. Finally, you can check that the count has been zeroed;
$ sudo smartctl -A /dev/sdc | grep Current_Pending_Sector
197 Current_Pending_Sector  0x0012   200   200   000    Old_age   Always       -       0

I experienced this on an old WD 200G HDD that had some kind of hickup that may have been caused by poor hotplug connections that resulted in a Current_Pending_Sector count of 26. When I ran the long test, it passed without finding any bad sectors, but the count was still at 26. I was able to zero the counter it by zeroing out the whole drive with dd;
dd if=/dev/zero of=/dev/sda bs=1M status=progress

Note the bs=1M makes it go much faster, but it's not the 512 sector size so there will be a partial block at the end. Subsequent smartctl long and short tests have all reported the drive as fine.

A: Your SMART Current Pending Sector has value 1. This means that there is a bad sector on the disk and the drive firmware is unable to reallocate it, but you still have zero reallocated sectors count so it probably recoverable even though your drive have been running for 5 years in not very healthy environment - temperatures are up to 72 C°.
You can try finding this bad sector with dd if=/dev/sda of=/dev/null and then you'll need to remap this sector by overwriting it.

A: This just means that you have one bad sector on one drive in your RAID array. There is nothing to worry about at the moment, unless you start getting a lot more bad sectors on that disk. You should NOT try to manually fix the error...that will be done automatically on the first of each month by the raid-check command, which is run from /etc/cron.d/raid-check. You can check that command and run it manually to immediately reallocate the bad sector on the disk:
[root@server]# more /etc/cron.d/raid-check

0 1 * * Sun root /usr/sbin/raid-check

[root@server]# /usr/sbin/raid-check

This will force mdraid to copy the bad block from the other disk in the RAID array, and it will mark the bad block as unusable.

A: FYI, in my case I got the error about 8 invalid sectors and that did last for a while.
Then I saw this message in my syslog:

Nov 13 06:57:35 monster smartd[3359]: Device: /dev/sdf [SAT], No more Currently unreadable (pending) sectors, warning condition reset after 1 email

So I guess it should fix itself and if not the drive should probably be replaced ASAP.
The first message I can find in my syslog happened on Nov 12 at 06:57:35

Nov 12 06:57:35 monster smartd[3359]: Device: /dev/sdf [SAT], 8 Currently unreadable (pending) sectors

So it looks like it repeated the message until 1 day later and checked the drive again and did not find the errors anymore.
I'm still thinking that I'll get a new hard drive. I can get a 12Tb and have 3 drives in my RAID. So if one dies, I still have 2... It's way more trouble to not have a backup.
My existing drive highest temp. is 48°C. So relatively good. Also the drive ran for only 9599 hours (~400 days) so still very young.

A: Now You have Current Pending Sector on the sda hard disk. This disk is used in software RAID. There is a start of death. You need to replace this disk.
This disk is designed for desktop PC. It tries to recovery itself (not via RAID). It reads bad sector every several seconds until checksum of bad sector will be good (disk's performance will drop dramatically), then the disk will write the read data to a new reserved sector. But the read data from rescued sector may be wrong often. CRC32 checksum can only indicate first error and it doesn't usable for recovering data (by example - XOR on RAID-5 can used for recovering data). When RAID will have read these data from the bad drive it will give different data, which will be read OK. This situation will produce kernel panic on the system if  bad block has important system data. That is why You need to replace bad disk.


text:
Q: Unable to show spinning icon when button is clicked The below code gets the data from back end and displays it on the browser on page load. When user clicks on Reload data button , again it has to get the data from backend and display on the browser. The issue is that when user clicks on Reload data button, I need to show the spinning icon and once the data is loaded it will be replaced with the data. With the below code spinning icon is showing but somewhere down the page, it is still occupying the space of $scope.html with the old data but showing blank and after the blank space it is displaying spinner.How can I show the spinner as soon as user hits the Reload data button?

 <button type="button" ng-click="loadData()">Reload data</button>

 Loading...

         <object-reloadable></object-reloadable>

js code:
app.directive('objectReloadable', function() {
var link = function(scope, element, attrs) {
var currentElement = element;

scope.$watch('pdfName', function(newValue, oldValue) {
 if (newValue !== oldValue) {
     scope.loading = false;
     scope.pdfName = newValue;
      if(scope.pdfName.filePath == "undefined" ||  scope.pdfName.filePath==null){
scope.loading=true;
} else {
alert("in else");
scope.html = '<object style="width: 100%; height: 1200px;overflow-y: hidden; cursor:pointer;" type="application/pdf" data="' + scope.pdfName.filePath + '" ></object>';
/* scope.pdfName = newValue;*/
scope.loading=false;

}var replacementElement = angular.element(scope.html);
    currentElement.replaceWith(replacementElement);
    currentElement = replacementElement;
}
});
};
return {
restrict: 'E',
scope: false,
link: link
};
})

myApp.controller('loadingSampleCtrl', function ($scope, FilesService) {
$scope.loadData = function () {
$scope.loading = true;
$scope.html='';
FilesService.fileRead().then(
function (response) {
     $scope.filePathAndName = response;
       if(window.navigator.msSaveOrOpenBlob){
    $scope.IEBrowser = true;
    $timeout(function() {
        $scope.pdfName = response;
       }, 0);
    } else {
    $scope.IEBrowser = false;
    $scope.filePathAndName = response;
     $scope.loading = false;
     }
},
function (errResponse) {
    $rootScope.showError("Internal error" + errResponse);
});

}
$scope.loadData();
});
//service call
_myFileServiceFactory.fileRead= function(){
var deferred = $q.defer();
var repUrl = appURL+'/myFilesData/generateDefectsSummaryPDF.form';
$http.get(repUrl).then(
    function (response) {
        deferred.resolve(response.data);
    },
    function(errResponse){
        console.error('Error ' + errResponse);
        deferred.reject(errResponse);
    }
);
return deferred.promise;
}

PS: I have assigned scope.html='' wherever required but still when user clicks on Reload button it is still showing blank space and then down somewhere showing the spinning icon.


text:
Q: Android: change app name in home screen My app displays the name of its starting activity on the Home screen.  I've tried to change the name by setting the android:label attribute in the manifest, under <application> to no avail.  What is the correct way to accomplish this?

A: Any activity with an intent filter for android.intent.category.Launcher will show up in the app drawer. You have to set a label for the activity as well as the application, the label for the activity (android:label="@string/title_activity_main") is what will show up in the app drawer.
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden"
        android:label="@string/title_activity_main"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

A: Why don't you change the name in your manifest, so it represents what you would like it to read.
In your manifest, use the element where you define your Activity, to have the following:
<activity android:name=".YourActivity" android:label="whatever you want"/>

A: FYI, The above works for fresh copies being installed on your phone. If the old copy is copied over sometimes the change in name doesn't work. Uninstall previous version, with previous name if the name isn't updated.

A: Change the name of the launcher activity using android:label. Seems to do the trick for me.


text:
Q: IF statement in loop throwing syntax error I'm creating a small batch script that loops over lines in documents then selects the correct condition and print out related message.
This is what I have tried.
...
set /p action=enter action(send,receive)

FOR /F %%j IN (countryList.txt) DO (
 For /F %%k IN (ports.txt) DO (
     IF "%action%" == "send"( ECHO Script will run as send for %%j country on %%k port)
     ELSE IF "%action%" == "receive"( ECHO Script will run as receive for %%j country on %%k port)
)
)
echo END

I am using ELSE IF, because in real case there are more conditions than just send and receive.
I am expecting simple message out of ECHO.

A: Your issue is with basic syntax; enter if /? at the Command Prompt for its usage information.
        If /I "%action%" == "send" (
            Echo Script will run as send for %%j country on %%k port
        ) Else (
            Echo Script will run as receive for %%j country on %%k port
        )


text:
Q: RESTful design - requesting multiple records by passing a list I am currently writing a RESTful service for a client who wants to pull stock records (free stock quantity) out of there accounts system and display them on the web.
I have the current endpoints :
GET /stockitems - returns free stock for all stock items
GET /stockitems/STOCKCODE - returns a single free stock record for the STOCKCODE
The requirements from the customer states "It will be possible to return the details of specific stock items only by passing in a list of stock codes."
How would I accomplish this in a RESTful way? Is it even possible?

A: You could call the GET /stockitems and filter accordingly at the consumer.
or
You could call the GET /stockitems/STOCKCODE  for each product code.


text:
Q: Swift: Cannot convert value of type 'String' to expected argument type '@noescape (AnyObject) throws -> Bool' I know this is a simple question, yet i am having problem finding the solutions.
In Swift 2.2, I am getting this error.

Cannot convert value of type 'String' to expected argument type
  '@noescape (AnyObject) throws -> Bool'

Here is the code.
var tableDataSectionsDict: CHOrderedDictionary?
if !tableDataSectionsDict!.allKeys.contains("Yesterday") {
   tableDataSectionsDict!.insertObject(YesterdayArray, forKey: "Yesterday", atIndex: count)
}

What i am missing here ? Can anybody shade some light on it ?

A: I'm assuming that CHOrderedDictionary is this CHOrderedDictionary. If that's the case, it is an Objective-C type that you have bridged to Swift (please correct me if I'm wrong).
There are two contains functions available:
extension SequenceType where Generator.Element : Equatable {
    /// Returns `true` iff `element` is in `self`.
    @warn_unused_result
    public func contains(element: Self.Generator.Element) -> Bool
}

extension SequenceType {
    /// Returns `true` iff an element in `self` satisfies `predicate`.
    @warn_unused_result
    public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
}

CHOrderedDictionary's keys and values are converted from id in Objective-C to AnyObject in Swift. AnyObject does not conform to Equatable, so you cannot use the first contains function. You could proabably write a wrapper around CHOrderedDictionary to allow some Equatable element types if you really wanted to.
The fastest solution here will be to use the more generic version of contains (the second contains). In code, it would look something like this:
// contains will iterate over the entire allKeys array. $0 is the key at each iteration.
let containsKey = tableDataSectionsDict!.allKeys.contains { return $0 as? String == "Yesterday" }
if !containsKey {
    //...
}


text:
Q: What does equal to operator in ="XXXX" do in SSIS derived column when exporting into CSV file I received an SSIS package that was built by someone else. In one of the control folow that gets the data from oledb data source and puts it into a csv file. Their is a derived column between the oledb data source task and the flat file destination task.

The derived data flow task creates some new columns with some of the expression having an equal to sign.

These columns are then redirected to CSV file. This file is again read by another data flow task that reads this created CSV file. If I remove the = sign from the derived column it gives me an error while reading the flat file.

[Flat File Source 2] Error: The column delimiter for column "CompanyCode" was not found.

The data type of column company code is varchar.
My Question:
What is the = sign in the derived column task used for?

A: The error message you provided

[Flat File Source 2] Error: The column delimiter for column "CompanyCode" was not found.

Is showing that it has no relation with the derived column transformation, it is thrown by [Flat File Source 2] and it occur when the flat file used doesn't matches the settings used in the Flat File Connection manager, check that this file does not contains rows with a corrupted structure.
And about the equal sign (=) (like @TabAlleman said)
The equals sign is a string literal in the expression.

A: The equals sign is a string literal in the expression.
If your data had a row where the value of CompanyCode was

ABC

Then the derived column CompanyCodeWithZero would contain

="ABC"

I can't surmise why removing the equal sign results in the error you are getting since it seems to be coming from some other part of the package not described in your question (Flat File Source 2).


text:
Q: Library for canonicalizing (normalizing but NOT just cleansing) email addresses There are multiple ways to produce email address Strings that differ with straight String comparison (see below), but are logically equivalent (i.e. mail sent to both goes to same mail box).
This often allows users to give seemingly unique email addresses, even if strict equality was disallowed.
I was hoping to find a library that would try to do normalization, to allow for finding some of duplicates from large sets of email addresses. Goal here is to find as many duplicates as possible.
Given how useful this is for multiple purposes (in my case it is simple abuse detection, as abuse accounts tend to (try to) just reuse certain accounts), I am thinking there might be existing solutions.
So what kind of things can vary? I know of at least things like:

*

*domain name part is case-insensitive (as per DNS); but local part may or may not be, this depends on mail provider (for example, Gmail considers it case-insensitive)

*many domains have aliases (googlemail.com is equivalent to gmail.com)

*some email providers allow other variations that they ignore (gmail, for example, ignores any dots in email address!)

Ideally this would be in Java, although scripting languages would also work (command-line tool)

A: I've been using Apache James Mime4J for parsing email addresses.

*

*It handles (comments) properly and removes them from the localPart and domainPart

*It handles "spaced and quoted" and +tagged localParts correctly.

*It has getLocalPart() and getDomainPart() methods.

*Doesn't normalize gmail localParts though.

A: I could find a few bits off code on Google by searching for "normalize email address", but nothing nearly thorough enough.  I'm afraid you would have to write your own tool.  If I were to write such a tool, here are a few rules I think I would apply:
First the tool would lower the case of the domain name (after the @). It shouldn't be too hard, unless you want to handle emails with international domain names. For example, JoE@caFÉ.fR (note the accent on the E) should first go through the Nameprep algorithm.  This leads to JoE@xn--caf-dma.fr.  I have never seen anyone with such an international email address, but I suspect you might find some in China or Japan, for example.
RFC 5322 states that the local-part of the email (before the @) is case sensitive, but the de facto standard for virtually all providers is to ignore case (I have never seen a case-sensitive email address actually used by a human being, but I suppose there are still some sysadmins out there who use their Un*x email accounts, where case does matter).  I think the tool should have an option to ignore case for a list of domain names (or on the contrary, to be case sensitive only for a list of domain names). So at this point, the email address JoE@caFÉ.fR is now normalized to joe@xn--caf-dma.fr.
Once again, the question of international (aka. non ASCII) email addresses pops up. What if the local-part is non-ASCII ? For example something like 甲斐@黒川.日本 (disclaimer: I don't speak Japanese). RFC 5322 forbids this, but more recent RFCs do support this (see this wikipedia article). A lot of languages have no notion of lower or uppercase. When they do, if you want to change to the lower-case form, make sure to use the appropriate Unicode lower-case algorithms, it's not always trivial. For example, in German, the lower case of the word "Großes" may be either "grosses" or "großes" (disclaimer: I don't speak German either).  So at this point, the email address "Großes@caFÉ.Fr" should have been normalized to "grosses@xn--caf-dma.fr".
I haven't read RFC 5322 in detail but I think there's also a possibility to have comments in an email address, either at the beginning or at the end of the local part, such as (sir)john.lennon@beatles.com or john.lennon(ono)@beatles.com. These comments should be stripped (this would lead to john.lennon@beatles.com.  Stripping the comments is not entirely trivial because I don't know what to do with the nested comments, and also comments enclosed in double-quotes should not be stripped, according to the RFC (unless I am mistaken).  For example, the comment in the following email address should not be stripped, according to the RFC: "john.(ono).lennon"@beatles.com.
Once the email is thus normalized, I would apply the "provider-specific" rules you suggest.  For example stripping the dots in GMail addresses and mixing equivalent domain names (googlemail.com == gmail.com for example).  I think I would keep this really separate from the previous normalization steps.
Note that Gmail also ignores the plus sign (+) and everything after it, for example s.m.i.t.h+hello_world@gmail.com is equivalent to smith@gmail.com.
I'm not aware of other provider rules.  The thing is, these rules may change at any time, you would have to keep track of them all.
I think that's about it.  If you come up with some working code, I would be really interested to see it.
Cheers!


text:
Q: Extracting Strings on Multiline Extracting Strings on Multiline
Please share your ideas on this concern.
how do i extract the string Domain/username field on this multi threaded line.
Name        Username
COMP01-100  Domain\user.one
Name        Username
COMP02-100  Domain\test.user
Name        Username
COMP10-100  Domain\sample.user
--
Note:
I should have searched for COMP02-100 and extract Domain\test.user as result.
I think I should have used the php preg_match_all function but i just can't find the right syntax on this.
Any ideas?

A: If I understand you correctly, you could get the desired result with these lines:
$search_string= 'COMP02-100';
preg_match("/$search_string (\w+\\\\\w+.\w+)/", $multiline, $matches);

preg_match is sufficient if you just want the first match


text:
Q: Azure DevOps Server git clone returns 403 We have a local instance of Azure DevOps Server, I have issues trying to git clone from it using https, but it works fine with ssh (I need https because of git lfs).
I tried all the suggestions I could find, setting the proxy, using the credential manager, nothing works, and at the end I always get:

fatal: unable to access 'https://myserver/org/project/_git/repo/': The requested URL returned error: 403

The credential manager actually never prompts for username and password, even if I deleted everything credential related from my gitconfig and Windows credentials (there was nothing here in any case).
If I try:
GIT_TRACE_CURL=true git clone https://myserver/org/project/_git/repo/

I get:
# logs
Info: Connected to proxy ...
# other logs
Send header: GET /org/project/_git/repo/info/refs?service=git-upload-pack HTTP/1.1
# other logs
Your system policy has denied access to the requested URL..

and naturally the 403.
Do you have any idea about what else I can try?


text:
Q: How to know if the viewport width is greater than its height using a mediaquery is there a way to perform this operation in css ?
@media screen and (min-width < min-height)
I started writting a front-end library and I want "responsive" based on this condition.

A: Check for the orientation
@media all and (orientation: landscape) {
  body:after {
     content: "width is greater than height"
  }
}

@media all and (orientation: portrait) {
  body:after {
     content: "height is greater than width"
  }
}


text:
Q: if image url contains character like "+" can't save image I'm trying to save images when an user posts an image url.
I'm doing this with this code:
        $pic = $Db->escape($_POST['form_pic']); // (escape is a function to mysql_real_escape_string)
        $time = strtotime("now");
        $filename = $item_id.'_'.$time.'.'.$ext;
        $item_pic = 'img/ads/'.$filename;

        $contents = file_get_contents($pic);
        file_put_contents('../img/ads/'. $filename, $contents);

This works in most of the cases. But when the url contains a strange character like a "+", then the above code isn't working. He doesn't save the image then.
 An example url: http://2.bp.blogspot.com/-ubBMWObG6u0/T-m3zYIq3CI/AAAAAAAABxU/Z8aa1Dgny9c/s1600/Grown+sunglasses.jpg

How can I save every image file, even if the url contains "strange" characters?
Update: I've echoed my $_POST['form_pic'] and it seems like that when I post the url after submit that the "+" character is replaced by a space?

A: Use this,
$pic = str_replace("+","_",$pic);


text:
Q: If there are many clients to the server is it posible the last incremented ID get messed up with another insertion? My question is, if this is a busy server and many people are placing orders, meaning inserting to the order table, is it posible, that someone get the last auto-incremented id number from another client, which will mess up the order? (using PHP and MySQL)

A: If you use the PDO functions you can use the function PDO->lastInsertId(); which will return the last id that was inserted by this instance of the PDO class.
Since the other user will use a different instance of this class it is not possible to get the ids mixed up.
Reference:
http://php.net/manual/en/pdo.lastinsertid.php


text:
Q: How can block container establish both block and inline formatting contexts at the same time? From the CSS Display Module Level 3 specs there is a note about block container that says:

Note: A block container box can both establish a block formatting
  context and an inline formatting context simultaneously.

How is this possible conceptually?
And how are children boxes laid out then? For example, if we have both inline-level and block-level boxes inside block container, which formatting context is used in that case? Are both formatting contexts used at the same time or one of them "wins" and the other one is put aside?

A: It's entirely possible, and even necessary for certain CSS rules. The easiest way to understand this is with an example of such a box.

hello world

Here we have an element with display:block (by default for div elements) and overflow:auto. This is one way that an element's rendered box will establish a block formatting context. This affects, for example, how the box's location and dimensions are affected by the presence of floats.
Compare these two examples:

.formatting.contexts {
  overflow:visible;
}

.container {
  width:70px;
}

img {
  float:left;
  margin-right:3px;
}

hello world

.formatting.contexts {
  overflow:auto;
}

.container {
  width:70px;
}

img {
  float:left;
  margin-right:3px;
}

hello world

In the first example, the text wraps underneath the image. That's because the div with class "formatting contexts" has overflow:visible, so it doesn't form a block formatting context.
However, it contains only inline boxes - formed by the text content. So by the CSS rules, it establishes an inline formatting context. The text content can therefore be laid out horizontally in line boxes within this context. It is the first line box which is shrunk to avoid overlapping with the float.
In the second example, the text does not wrap underneath the image. That's because the div with class "formatting contexts" now has overflow:auto which means that it establishes a block formatting context, and it is the block box that is shrunk to avoid it overlapping the float. But its contents are just the same, just inline boxes, so it also establishes an inline formatting context.


text:
Q: Removing 1 of 2 Exchange servers I'm new in a company and I'm still learning exchange as this is the first time, I'm managing a system. I have been tasked to remove one of two 2010 exchange servers from my environment which are both running on Windows 2008r2 and are virtual servers. Lets call them EXVM01 and EXVM02.
I do not know the technical name of how the exchange servers are setup, I believe it is in a HA (High availability). The servers work independently as they both have their own mail databases.
I have done extensive research and I have migrated all the users from databases on EXVM02 to databases on EXVM01. My boss then shutdown EXVM02 however when I browse EXVM01 I can see there are still some connections to EXVM02.
My questions is how can I remove all EXVM02 configurations on EXVM01 and what is the correct way of removing the exchange server?

A: There are a number of considerations that are beyond the scope of your question (making sure there are no orphaned public folders, for example) but, ultimately, you need to be doing a clean and orderly uninstall of Exchange from the EXVM02 server computer. Hopefully your boss didn't delete the VM but, rather, just powered it off.


text: Q: Is there any new features in log4j 2.0 or logback that can seperate logger level into thread basis? My class has a logger, and the class is used by many threads. Besides using thread-local technology, is there a native feature in log4j 2.0 or logback or even other logging technology that can change the logger level for a special thread and leave the logger level for other threads unchanged?


text:
Q: url captured regex (\w+) not matching certain urls The two lines of the urls.py config file for my_app are shown below. They're almost the same, only the second has a uuid4 appended to it
# preview views to allow us to preview stuff
url(r'^(?P<hash>\w+)/preview/$', Start.as_view(), {'preview':True}, name='preview'),
url(r'^(?P<hash>\w+)/preview/(?P<uuid>[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12})/$', PreviewController.as_view(), name='previewcontroller'),

The following urls work without error:

*

*http://example.com/my_app/2307099758/preview/

*http://example.com/my_app/2660962971/preview/

*http://example.com/my_app/475966143/preview/
The following urls yield the below error (all hash values are valid, but that shouldn't affect the url resolution):

*

*http://example.com/my_app/841211121/preview/

*http://example.com/my_app/2398929036/preview/

Internal Server Error: /my_app/841211121/preview/
NoReverseMatch at /my_app/841211121/preview/ Reverse for
  'previewcontroller' with arguments '()' and keyword arguments
  '{'uuid': None, 'hash': '841211121'}' not found. 1 pattern(s)
  tried:
  ['my_app/(?P\w+)/preview/(?P[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12})/$']
Request Method: GET Request URL:
  http://example.com/my_app/841211121/preview/
  Django Version: 1.10...

Regex101.com says that the url should match (with escaped slashes, of course). Why on earth are the second group of urls not matching the preview url, and what is provoking the url resolver to attempt to match them to previewcontroller when there is no uuid string appended to the url?

A: Django is correctly resolving the /my_app/841211121/preview/ and running the correct view.
The problem is occurring when Django runs the Start view. It looks like a reverse() call or {% url %} template tag is failing.


text:
Q: Meteor serve remote video files as a reverse proxy A bit of a weird question :) I have a video at https://s3.amazonaws.com/mybucket/myvideo.mp4 and I would like my Meteor server to respond to http://mywebsite.com/myvideo.mp4 exactly as if the video from s3 was living there. So that I can stream, seek etc ie that
<video><source src="http://mywebsite.com/myvideo.mp4" type="video/mp4"></video>

would behave exactly like
<video><source src="https://s3.amazonaws.com/mybucket/myvideo.mp4" type="video/mp4"></video>

while not hosting anything on my server.
This doesn't do the job: it seems to download everything (my server went out of memory...)
The reason of this weird request is that Safari is not doing a great job with CORS (see here and here) and I can't paint to a canvas a video from a different domain... setting crossOrigin and configuring CORS correctly in AWS doesn't solve it.
And just to check: there is no simpler way to set AWS config to make things as if the content was coming from http://mywebsite.com right?

A: Lots going on here. You're on the right track with reverse proxy, as that's the only way you'll change the outbound source of the files. But for a hosted Meteor app, that is still being developed for AWS integration, so people end up using a reverse proxy like Nginx, which is most popular now for Meteor devs.
The SO question you posted is directions for how to go directly from the S3 bucket, but it looks like what you want to do is serve the content from the bucket (that you own?) and have it's source by your website. In and of itself not hard, you will need to configure your AWS setup so that the content is streamed from your S3 then to your hosted space, and through to the app. Cloudfront is a service they have that can start the process for you, but without knowing more about your server / host setup its hard to troubleshoot. You'll have to specify an origin domain name when delivering content through AWS CF, but you'll surely be able to figure out how to get this to be www.yourwebsite.com, particularly if you're already hosting on AWS and use Nginx.
https://aws.amazon.com/blogs/aws/using-amazon-cloudfront-for-video-streaming/
https://www.jwplayer.com/blog/delivering-hls-with-amazon-cloudfront/


text:
Q: AutoComplete on a TextBox ignoring accentuation I have a custom TextBox control (It is a custom one instead of a regular one to be able to have hint text on top of it), in which I have an AutoComplete that gets it's data from my DB using a DataSet like this
string[] postSource = aux.Tables[0].AsEnumerable().Select<System.Data.DataRow, String>(x => x.Field<String>("nm_industria")).ToArray();
            var source = new AutoCompleteStringCollection();
            source.AddRange(postSource);

txb_regClientData.AutoCompleteCustomSource = source;
            txb_regClientData.AutoCompleteMode = AutoCompleteMode.Suggest;
            txb_regClientData.AutoCompleteSource = AutoCompleteSource.CustomSource;

It gives me this result
Image if I type "João" it will give me the correct result, but if I type "Joao" it will not show up, from some reading on the matter I know that theres nothing in the AutoComplete to automatically ignore accentuation, so I will need to code it myself. My question is, where do I begin with this? My ideal solution would be to override something in the AutoComplete code of my custom control, I gave a read on the documentation for TextBox and couldn't find anything, so if anyone can show me the right direction so I can read and learn how to do this, would be highly appreciated.

A: There's still improvements to be done, but this code implements the solution for this, it "appends" a listBox to the textBox, there will be issues when multiple of these exist due to naming, but this should be a good starting point/reference for someone looking for something similar.
public class ExTextBox : TextBox
{
    private bool alreadyRun = false;
    ListBox suggestions = new ListBox();
    int maxSize = 10;
    string[] source;
    public string Hint

    public int MaxSuggestionBoxSize
    {
        get { return maxSize; }
        set { maxSize = value; this.Invalidate(); }
    }

    protected override void OnCreateControl()
    {
        if (alreadyRun == false) // This is only supposed to be run once, but in some situations depending on the design of the main form,
        {// this might need to be somewhere that gets called multiple times, this variable makes so this code is only run once even in those situations
            suggestions.Name = "suggList_" + this.Name;
            suggestions.Location = new Point(this.Location.X, (this.Location.Y + this.Size.Height));
            suggestions.Size = new Size(this.Size.Width, this.Size.Height);
            this.Parent.Controls.Add(suggestions);
            this.Parent.Controls["suggList_" + this.Name].MouseDoubleClick += suggList_MouseDoubleClick;
            this.Parent.Controls["suggList_" + this.Name].Hide();
            alreadyRun = true;
        }
        base.OnCreateControl();
    }

    private void suggList_MouseDoubleClick(object sender, System.EventArgs e)
    {
        this.Text = this.Parent.Controls["suggList_" + this.Name].Text;
    }

    protected override void OnLeave(EventArgs e)
    {
        base.OnLeave(e);
        if(source != null) // Makes sure this code is only executed when the suggestion box is being used, by checking the existance of the source
        {
            try
            {
                if (this.Parent.Controls["suggList_" + this.Name].Focused == false)
                {
                    this.Parent.Controls["suggList_" + this.Name].Hide();
                }
            }
            catch
            {

            }
        }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        AutoCompleteSmart();
    }

    public void AutoCompleteSmart()
    {
        if (source != null)
        {
            suggestions.Items.Clear();
            if (this.Text != "")
            {
                foreach (string a in source)
                {
                    if (RemoveDiacritics(a.ToLower()).Contains(RemoveDiacritics(this.Text.ToLower())))
                    {
                        suggestions.Items.Add(a);
                    }
                }
                this.Parent.Controls.Remove(suggestions);
                if (suggestions.Items.Count < maxSize) // Optional code, defines a limit size for the suggestion box
                {
                    suggestions.Size = new Size(this.Size.Width, ((suggestions.ItemHeight * suggestions.Items.Count) + suggestions.ItemHeight));
                }
                else
                {
                    suggestions.Size = new Size(this.Size.Width, ((suggestions.ItemHeight * maxSize) + suggestions.ItemHeight));
                }

                this.Parent.Controls.Add(suggestions);
                this.Parent.Controls["suggList_" + this.Name].BringToFront();
                this.Parent.Controls["suggList_" + this.Name].Show();
            }
            else
            {
                this.Parent.Controls["suggList_" + this.Name].Hide();
            }
        }
    }

    public void AutoCompleteSmartSource(string[] _source)
    {
        source = _source;
    }

    private static string RemoveDiacritics(string text)
    {
        var normalizedString = text.Normalize(NormalizationForm.FormD);
        var stringBuilder = new StringBuilder();

        foreach (var c in normalizedString)
        {
            var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
            if (unicodeCategory != UnicodeCategory.NonSpacingMark)
            {
                stringBuilder.Append(c);
            }
        }

        return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
    }
}


text:
Q: Input type date ng-model does not allow date data From the server response, i want to map the date to my scope variable which type is 'date' in angular, as i do the same, am not able to map it as am getting the following error
angular.js:12798 Error: [ngModel:datefmt] Expected `2016-09-22T18:30:00.000Z` to be a date
http://errors.angularjs.org/1.4.12/ngModel/datefmt?p0=2016-09-22T18%3A30%3A00.0

Note: am mapping through $operatingDetails.date as exceptions array already in the ng-repeat loop
Any help please would be appreciated...
Html

             <input id="date2" type="date" ng-model="operatingDetails.date" style="" ng-change="customOPHchangeExpDateValid(operatingDetails.date, $parent.$parent.$index)"/>

Js(Angular)
$scope.opertingHours.date

Server response
{
                "name" : "Custom Operation Hours1",
                "exceptions" : [{
                        "date" : "2016-09-15T18:30:00.000Z",
                        "starttime" : "10:02AM",
                        "endtime" : "10:02PM",
                        "_id" : "57de44c54feb409c2e13ff40",
                        "$$hashKey" : "object:207"
                    }
                ],
                "businesshour" : {
                    "sat" : {
                        "starttime" : "8:00AM",
                        "endtime" : "5:00PM"
                    },
                    "fri" : {

A: I guess you are getting this error, as "date" ("date" : "2016-09-15T18:30:00.000Z",) is a string.So convert it to date from string.
So try this,

$scope.opertingHours.date = new Date(exceptions[0].date); //Converting string to date

Hope,it wll work for u.

A: your operatingDetails is getting confused as you are using it in the $scope and in ng-repeat so try using another one as below

                 <input id="date2" type="date" ng-model="convertDate(oD.date)" style="" ng-change="customOPHchangeExpDateValid(oD.date, $parent.$parent.$index)"/>

Also add the following function to your controller
$scope.convertDate=function(inputDate){
return new Date(inputDate);
}


text:
Q: Graph does not support transactions I've tried two transactional cases on gremlin-java.
First case:
@Bean
public Cluster gremlinCluster()
{
    return Cluster.build()
            .addContactPoint(GREMLIN_ENDPOINT)
            .port(GREMLIN_PORT)
            .enableSsl(GREMLIN_SSL_ENABLED)
            .create();
}
...
@Bean
public GraphTraversalSource gremlinGraph(Cluster gremlinCluster)
{
    return traversal().withRemote(DriverRemoteConnection.using(gremlinCluster, "g"));
}
...
GraphTraversalSource graph;
...

final Transaction tx = graph.tx();
...

It gives error: java.lang.UnsupportedOperationException: Graph does not support transactions
Second Case:
    String sessionId = UUID.randomUUID().toString();
    Client client = cluster.connect(sessionId);
    client.submit("g.addV('App').property('appId', 1)");
    client.submit("graph error query");
    client.close();
    ...
    graph.V().has("App", "appId", 1).next(); => It gives value

In second case, Expected situation is:

*

*rollback will work.

*return no-result from graph.V().has("App", "appId", 1).next();.

However, rollback doesn't work.
Is there any suggestion? How can I achieve transaction on gremlin-java?

A: Regarding your first case, I would ask, what graph database are you using? For example, if graph is a TinkerGraph then you can expect that error as it simply doesn't support them:
gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> graph.features().graph().supportsTransactions()
==>false
gremlin> g = traversal().withRemote(DriverRemoteConnection.using("localhost",8182,"g"))
==>graphtraversalsource[emptygraph[empty], standard]
gremlin> g.graph
==>emptygraph[empty]
gremlin> g.graph.features().graph().supportsTransactions()
==>false

For your second case, you are sending scripts in a session. If you are using a graph that doesn't support transactions (i.e. the same graph that is giving you the error in the first case) then I would suspect that your change was effectively committed on execution of the first request as there is no transaction to open or close. Of course, it is worth noting that for graphs that do support transactions, you can have per-request auto-commit functionality with session-managed transactions described in this section.
You might find this entire section of the Reference Documentation helpful in understanding the various modes of transactions in different usage contexts.