text:
Q: Why should I NOT update to Mavericks? I'm not really looking for a single correct answer. I'm just looking for some input regarding the inevitable "gotchas" Apple seems to sneak into every major OS X release that screw over a select handful of people before they have time to resolve whatever feature or app got removed in any given release. I want to know about anything at all; I'm a developer, so even lower-level system tweaks and restrictions have an effect on me.

A: You (or anyone else) should not upgrade if you don't have a good backup, a good idea how or why it will make your life easier and you don't have a list of software that you need to work so you can check at your workflow won't get ruined or at lease slowed / disrupted.

A: Afaik. Xcode 5 no longer supports gcc or llvm 4.2
I still need to maintain some apps for 10.6
With xcode 4.x and 10.8 osx I could do this ok because I just symlinked a 10.6 sdk and could still use gcc or llvm 4.2
But upgrading to 10.9 I also upgrade to its xcode 5 so I could use the 10.9 sdk
I found even with the 10.6 sdk there is no ggc and llv 4.2.
Clearly I did not pay attention to the press.
Luckily I still had a xcode 4.x app (using timemachine restore and keep both) that seems to run ok side by side with the xcode 5.


text:
Q: how to set form border thickness I am writing an app using VB.net in VB2013. The Sizeable border is too thick in when displayed on PC's with later versions of Windows7, Windows 8(.1).
Does anyone know how to change the thickness of the window?

A: You don't get to control that. That's part of the user theme, and users can set any theme they want. You'll find it's also a problem on older versions of Windows if users have a theme with a wider border. You'll need to adjust your program's layout to allow for a little less space.

A: The border is drawn by the operating system, but you can create your own custom form, there is a library on CodePlex may help you to do what you need easily.
Drawing Custom Borders in Windows Forms

redpajama_set_name: RedPajamaStackExchange


text:
Q: Email filled PDF with PHP or PHPMailer My company is currently trying to streamline our process for submitting forms.  I have read that what we are trying to do can be done with PHP or PHPMailer but I seem to have hit a roadblock.
What we are trying to do is open a fillable PDF in browser, complete it, and then click a button at the bottom to email it to a designated recipient.
I currently have a PHP script that allows me to email the blank document using PHPMailer and our server email service.
I have tried using the "AddStringAttachment" feature of PHPMailer:
<?php

require("../PHPMailer_5.2.3/class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();  // telling the class to use SMTP
$mail->Host     = "xxx.xxx.org"; // SMTP server

$mail->From     = "xxx@xxx.org";
$mail->AddAddress("xxx@xxx.org");

$mail->Subject  = "Attachment Test";
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->WordWrap = 50;
$mail->AddStringAttachment($string,'filename.pdf');

if(!$mail->Send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}
?>

...but I was unable to find a way to define the string in a way that would send the completed form.  Currently, if I put any data into the "$string" field the email fails.
Is this even possible?  Or am I just spinning my wheels?

A: The problem might be with your mail server. Many servers don't like sending corrupted PDFs, which would be any PDF that doesn't look like a normal PDF - say, a string of English text.
Are you able to send any other kind of attachment, before I get into how to generate a PDF in PHP?


text:
Q: ModelBuilder: Using Parse Path in iterative model to include folder name in output file name I have a simple model in ModelBuilder that does the following:

*

*Iterate through a folder of rasters (these are outputs from Global
Climate Models)

*Clip each raster to a study area (Egypt), using a polygon, and dump outputs into a Geodatabase

*For each clipped raster use the Zonal Statistics as Table tool to calculate some basic statistics (i.e. mean, min, max) and dump the outputs into a folder

Problem: There are many input rasters, each with similar names (i.e. Temp1, Temp2, Precip1, Precip2 etc.). This means that when running the model the outputs are all subsequently named very similarly such that I am unable to know which GCM each output has come from.
What I would like to do: Each input raster is stored in a folder with a name that I would like to retain in the output file names. I would like to include this name in the output of each clipped raster (step 2 above) and in the output of each statistic table (step 3 above).
Current model: Below is a screenshot of my current model. I understand that I need to use the Parse Path and Calculate Value tools to retain the folder name and pass this into the output file names but I do not know how to do this. Help!

Progress:
Thus far I have the below. I can get it to include the originating folder name in the output files in the clipped raster but it's also including part of the parent folder too (i.e. ParentFolderName_FolderName rather than simply FolderName_%Name%_c).

A: A colleague had more success with a simpler model, here's the (working) solution:

Where, 'Parse Path' is used three times to extract two folder levels and the file name; this is then included (using %value(3)%_%name%) in the 'Zonal Statistics as Table' tool to dump the resultant outputs into a folder named in the correct convention.
Also, to speed things up a little, the 'Clip' procedure was removed and incorporated as an Environmental variable (as a Mask) of the 'Zonal Statistics as Table' tool. As there are lots of rasters (hundreds) this sped things up a little.
Finally, outside of ModelBuilder, to combine the resultant .dbf files into a single file Command Prompt was used such that:

*

*Windows Start Button | Run

*Type cmd and hit enter

*Go to the folder with the dbf files

*Type copy *.dbf all.txt and hit enter to copy all data in the files into all.txt.

*Type exit and hit enter to close the DOS window

I hope this helps anybody with the same issue. Shame I couldn't get the Python code working though! Note, you could achieve the latter step (combining multiple dbfs) a number of different ways, including VBA or Python. I've used Command Prompt here only as I'm more familiar with it.

A: This code splits the path at "\".  To return the last x part(s) of the split path, use the following code in 'Calculate Value' as the expression.  Leave the code block blank.  Set output type to string.  To get the last part of the path, change x to 1.  To get the last 2 parts of the path joined with "_", change x to 2.  (e.g. C:\string1\string2\string3 -- x=2  yields "string2_string3" and x=1 yields "string3")
"_".join('\%Value%'.split('\\')[len('\%Value%'.split('\\'))-x:])

To use this in your model, it will look like this:  %output_value_c%_%name%


text:
Q: Couldn't read from socket input stream I'm currently programming a Chat System using ServerSocket and Socket with JFrame UI. But I'm struggling with reading from Socket Stream.
Here is my Server code:
    ServerSocket serverSocket = new ServerSocket(PORT);
    Socket socket;

        systemStatus.append(displayStatus("Server starts on port: ") + serverSocket.getLocalPort() + "\n");
        while (true) {
            socket = serverSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            while (true) {
                String line = in.readLine();
                while (line != null) {
                    line = in.readLine();
                    systemStatus.append(line);
                }
            }

        }

and the send button code at the Client:
    log_regButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String login = log_loginField.getText().trim();
                String pw = log_pwordField.getText().trim();
                out.write(login + "\n" + pw+"\n");
                out.flush();
            }
        });

which systemStatus is a JTextArea. It's suppose to show  text from JTextField at Client Frame. But it doesn't. Could anyone show me what I am doing wrong?


text:
Q: Modify data to reflect another record in same group I have a view which produces data like so:
---ID-------StartDate---EndDate----Endpoint number-------
G002S6YE    01/06/2011  31/05/2013  1012427316307
G002W1AY    27/06/2011  30/09/2012  1012427316307

Endpoint number is usually different for each record. In some cases however where it isn't (such as this example) I need to modify the EndDate of the earlier record to the day before the StartDate on the later record so in this example the data should show as:
---ID-------StartDate---EndDate----Endpoint number-------
G002S6YE    01/06/2011  26/06/2011  1012427316307
G002W1AY    27/06/2011  30/09/2012  1012427316307

This is based purely on the Endpoint number so that the StartDate and EndDate of each record doesn't overlap.
This is a much simplified version of the actual script creating the view, but if you could show a simple way to achieve what I've explained here it would be much appreciated.

A: So, you've got a view V:
SELECT id, startdate, enddate, endpt
  FROM ...

You could modify this to something like:
SELECT id, startdate
     , CASE WHEN nextdt IS NULL THEN enddate ELSE nextdt - 1 END enddate, endpt
  FROM (SELECT id, startdate, enddate, endpt
             , LEAD(startdate) OVER (PARTITION BY endpt ORDER BY startdate) nextdt
          FROM  ...)

A simple example, using a table T instead of a view, with your data plus a third row, to illustrate the case identified by X-Zero's comment. It may not be what you want, so beware. The query will give you the enddate minus one for the next record.
SQL> CREATE TABLE t (ID VARCHAR2(10), sd DATE, ed DATE, ep NUMBER);

Table created
SQL> INSERT INTO t VALUES ('G002S6YE',to_date('01/06/2011','DD/MM/YYYY'), to_date('31/05/2013','DD/MM/YYYY'), 1012427316307);

1 row inserted
SQL> INSERT INTO t VALUES ('G002W1AY',to_date('27/06/2011','DD/MM/YYYY'), to_date('30/09/2012','DD/MM/YYYY'), 1012427316307);

1 row inserted
SQL> INSERT INTO t VALUES ('G002W1AX',to_date('29/06/2011','DD/MM/YYYY'), to_date('30/06/2012','DD/MM/YYYY'), 1012427316307);

1 row inserted

SQL> SELECT id, sd
  2       , CASE WHEN nextdt IS NULL THEN ed ELSE nextdt - 1 END ed, ep
  3    FROM (SELECT id, sd, ed, ep
  4               , LEAD(sd) OVER (PARTITION BY ep ORDER BY sd) nextdt
  5            FROM  t);

ID         SD          ED                  EP
---------- ----------- ----------- ----------
G002S6YE   1/6/2011    26/6/2011   1012427316
G002W1AY   27/6/2011   28/6/2011   1012427316
G002W1AX   29/6/2011   30/6/2012   1012427316


text:
Q: Call methods from delegated class In my LocationController.h
// protocol for sending location updates to another view controller
@protocol LocationControllerDelegate
@required
- (void)locationUpdate:(CLLocation*)location;
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
@end

@interface LocationController : NSObject  {

   CLLocationManager* locationManager;
   CLLocation* location;
   __weak id delegate;
}

@property (nonatomic, strong) CLLocationManager* locationManager;
@property (nonatomic, strong) CLLocation* location;
@property (nonatomic, weak) id  delegate;

+ (LocationController*)sharedLocationController; // Singleton method

@end

In the LocationController.m
static LocationController* sharedCLDelegate = nil;

@implementation LocationController
@synthesize locationManager, location, delegate;

- (id)init
{
  self = [super init];
    if (self != nil) {
       self.locationManager = [[CLLocationManager alloc] init];
       self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
       self.locationManager.distanceFilter = 10.0f;
       self.locationManager.headingFilter = 5;

       [self.locationManager startUpdatingLocation];
 }
  return self;
}

#pragma mark -
#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{

}

- (void)locationManager:(CLLocationManager*)manager
   didFailWithError:(NSError*)error
{

}

#pragma mark - Singleton implementation in ARC
+ (LocationController *)sharedLocationController
{
static LocationController *sharedLocationControllerInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
    sharedLocationControllerInstance = [[self alloc] init];
});
return sharedLocationControllerInstance;
}

+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
    if (sharedCLDelegate == nil) {
        sharedCLDelegate = [super allocWithZone:zone];
        return sharedCLDelegate;  // assignment and return on first allocation
    }
}
return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
return self;
}

I then want to call one of these methods in another ViewController, so in my viewDidLoad I set the delegate [LocationController sharedLocationController].delegate = self; I then want to call a method from the LocationController class
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//How can I call the CLLocation from the LocationController class so I don't have to create a new one
CLLocation *location = [locations lastObject];
}

Also how do I call this method in the viewDidLoad?
So my question is how can I reuse the CLLocation from the LocationController class and how can I then implement the didUpdateLocations method in my ViewController?

A: Suppose if you want to call the
- (void)locationUpdate:(CLLocation*)location;

method from the LocationController, you can use the delegate object.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
   if (self.delegate != nil)
   {
      CLLocation *location = [locations lastObject];
      [self.delegate locationUpdate:location];
   }
}

A: hey didUpdateLocations is a delegate method of CLLocationManager class it called itself for this you have to set CLLocation like this
@interface MapViewController : UIViewController < CLLocationManagerDelegate>


text:
Q: How to assign productIds to websites? Maganto1.x have code below code  to assign multiple productIds to multiple websites.
Mage::getModel('catalog/product_website')->addProducts($websiteIds, $productIds)

In magento2, How do get same result?

A: You can simply set multiple product id to website using magento 2 as below way, Set Magento\Catalog\Model\Product\WebsiteFactory to your construct and set productids.
protected $_productWebsiteFactory;
public function __construct(
    \Magento\Catalog\Model\Product\WebsiteFactory $productWebsiteFactory

) {
    $this->_productWebsiteFactory = $productWebsiteFactory;
}

Use inside function like below,
$this->_productWebsiteFactory->create()->addProducts($websiteIds, $productIds);


text:
Q: js conditional test for utf string of special character Say I have a div with innerHTML set using the HTML code for a rocket: 🚀
How do I do a conditional test for that character in javascript?
E.g. how do I get below to log "rocket"

let rocket = document.getElementById("rocket")

if (rocket.innerHTML == "🚀") console.log("rocket")
else console.log("no rocket");

🚀

A: I tried using charCodeAt(0) to get the unicode character code of the rocket and got 55357 as the result and the code below works.

let rocket = document.getElementById("rocket").innerText

if (rocket.charCodeAt(0) == 55357) console.log("rocket")
else console.log("no rocket");

🚀

Hope this helps until a better answer comes. You can use console.log() to check the character code if you want to have a different item instead of a rocket.

A: I could achieve this way. Note that I've used ".innerText"

var ic = '';
var r = document.getElementById("rocket");

if (r.innerText == ic) console.log("rocket");
else console.log("no rocket");

🚀


text:
Q: Validating Connection Before Handing over to WebApp in ConnectionPooling I have connection pooling implemented in spring using Oracle Data Source. Currently we are facing an issue where connections are becoming invalid after a period of time. (May be Oracle is dropping those idle connections after a while). Here are my questions:

*

*Can Oracle database be configured to drop idle connections automatically after a specific period of time. Since we expect those connections to lie idle for a while; if there is any such configuration; it may be happening.

*In our connection pooling properties in spring we didn't have "validateConnection" property. I understand that it validates the connection before handing it over to web application? But does that mean that if a connection passes validateConnection test then it'll always connect to database correctly. I ask this, as I read following problem here:
http://forum.springsource.org/showthread.php?t=69759

*If suppose validateConnection doesn't do the whole 9 yards of ensuring that connection is valid, is there any other option like "testBeforBorrow" in DBCP , which runs a test query to ensure that connection is active before handing it over to webapp?
I'll be grateful if you could provide answers to one ore more queries listed above.
Cheers

A: You don't say what application server you are using, or how you are configuring the datasource, so I can't give you specific advice.
Connection validation often sounds like a good idea, but you have to be careful with it. For example, we once used it in our JBoss app servers to validate connections in the pool before handing them to the application. This Oracle-proprietary mechanism used the ping() method on the Oracle JDBC driver, which checks that the connection is still alive. It worked fine, but it turns out that ping() executes "select 'x' from dual' on the server, which is a surprisingly expensive query when it's run dozens of times per second.
So the moral is, if you have a high-traffic server, be very careful with connection validation, it can actually bring your database server to its knees.
As for DBCP, that has the ability to validate connections as their borrowed from the pool, as well as returned to the pool, and you can tell it what SQL to send to the database to perform this validation. However, if you're not using DBCP for your connection pooling, then that's not much use to you. C3PO does something similar.
If you're using an app server's data source mechanism, then you have to find out if you can configure that to validate connections, and that's specific to your server.
One last thing: Spring isn't actually involved here. Spring just uses the DataSource that you give it, it's up to the DataSource implementation to perform connection validation.

A: Configuration of data source "was" as follows:
<bean id="datasource2"
 class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
         <value>org.apache.commons.dbcp.BasicDataSource</value>
    </property>
<property name="url">
         <value>ORACLE URL</value>
    </property>
<property name="username">
         <value>user id</value>
    </property>
<property name="password">
         <value>user password</value>
    </property>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>

have changed it to:
<bean id="connectionPool1" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="connectionCachingEnabled" value="true" />
<property name="URL">
         <value>ORACLE URL</value>
    </property>
<property name="user">
         <value>user id</value>
    </property>
<property name="password">
         <value>user password</value>
    </property>
<property name="connectionCacheProperties">
      <value>
        MinLimit:1
        MaxLimit:5
        InitialLimit:1
        ConnectionWaitTimeout:120
        InactivityTimeout:180
        ValidateConnection:true
      </value>
   </property>
</bean>


text:
Q: setState сохраняет значение со второго раза На странице реализована возможность сохранения настроек.
На форме присутствует 3 поля. 1 обычный input и 2 textarea. Использую react-bootstrap.
Описано это следующим образом:
<Form>
                <Form.Group className='col-xs-2'>
                    <Form.Label>Логин:</Form.Label>
                    <Form.Control type='text' name='username' value={this.state.username} onChange={this.handleChange.bind(this)}/>
                </Form.Group>
                <Form.Group>
                    <Form.Label>Список URL для мониторинга:</Form.Label>
                    <Form.Control as='textarea' rows='10' name='featurelist' value={this.state.featurelist} onChange={this.handleChange.bind(this)}/>
                </Form.Group>
                <Form.Group>
                    <Form.Label>Список URL для точечного мониторинга:</Form.Label>
                    <Form.Control as='textarea' rows='10' name='detailedlist' value={this.state.detailedlist} onChange={this.handleChange.bind(this)}/>
                </Form.Group>
                <Button onClick={this.handleSubmit.bind(this)} variant="success">Сохранить</Button>

            </Form>

Значения сохраняются в State следующим образом:
handleChange(event){
    const target = event.target;
    const value = target.value;
    const name = target.name;
    this.setState({[name]: value})
  };

Сохранение реализовано следующим образом:
handleSubmit(){
      if(this.state.username){
        this.setState({savedUsername: this.state.username});
        localStorage.setItem('username', this.state.username);
      }
      if(this.state.featurelist){
        let featurelist = this.state.featurelist.replace(/^\s*[\r\n]/gm, '')
        this.setState({featurelist: featurelist});
        let savedFeatureList = featurelist.split('\n')
        savedFeatureList = savedFeatureList.filter((el)=> el !== '')
        this.setState({savedFeatureList: savedFeatureList});
        this.forceUpdate();
        localStorage.setItem('featurelist', this.state.savedFeatureList);
      }

      if(this.state.detailedlist){
            let detailedlist = this.state.detailedlist.replace(/^\s*[\r\n]/gm, '');
            this.setState({detailedlist: detailedlist});
            let savedDatailedList = detailedlist.split('\n');
            savedDatailedList = savedDatailedList.filter((el)=> el !== '')
            this.setState({savedDatailedList: savedDatailedList});
            localStorage.setItem('detailedlist', savedDatailedList)
      }
      //this.props.handleSave(this.state);
      console.log(this.state);

      NotificationManager.warning('Сохранено');
  }

Основная проблема, что все поля сохраняются с первого раза, а вот в savedFeatureList только со второго, т.е. 2 раза надо нажать кнопку Сохранить.
Как это побороть?

A: Ваш код слишком много обращается в state, это занимает время. Я немного переписал, так как заметил что вы лишний раз используете setState.
let {featurelist} = this.state;
let newFL = featurelist.replace(/^\s*[\r\n]/gm, '').split('\n').filter((el)=> el !=='');
this.setState({savedFeatureList: newFL});
localStorage.setItem('featurelist',newFL);

SetState выполняется асинхронно, для того чтобы убедится что ваш код выполнится сразу после SetState вы можете указать внутри него функцию callback вот так this.setState({Example:111}, ()=>{doSomething()}); В этом случае doSomething() выполнится точно после того как обновится состояние.


text:
Q: Disable internal speaker only on a Dell Optiplex 9020 running Windows 10 I have a Dell Optiplex 9020 I will often use with headphones (so 3.5mm front panel jack), however it seems to share the volume and audio "device" with some internal speaker within the box.
If the headphones/external speaker is removed it switches back to its internal speaker with the same volume level (so terrible if the machine is then left locked and some browser ad, application, etc. decides to make noise).
This is similar to on my phone, etc. only there Android remembers the volumes seperately (so device volume muted, headphones at whatever) which works just as well as disabling.

A: I don't think that you are going to find a setting in the bios for this.. I guess you might.  My Dell does not have this setting.
The easiest way to resolve this is to simply remove/disconnect the speaker.  I bet you can wing the whole operation but if you want specifics, select your correct form factor manual from  here  and look for the section titled "Removing the Speaker."
I believe it is a simple four plug dealy-bob and will take you only a few minutes to do blindfolded.
Good luck!

A: First, try to update your audio drivers. This can happen with some Realtek audio solutions when the Realtek drivers aren't installed.
If that doesn't work you can completely disable the internal speaker in the BIOS. On Win 10 machines you can get into the BIOS starting in Windows.

*

*Open Start Menu

*Navigate to "Settings"

*Select "Update and Security"

*Go to "Recovery"

*Scroll down and select "Restart Now" under the Advanced Startup header.

*Click Troubleshoot

*Click Advanced Options.

*Click UEFI Firmware Settings

*Click Restart

BIOS menus vary widely from computer to computer so I can't give a walkthrough of where to find the setting to disable the internal speaker, you'll have to poke around a bit to find that.


text:
Q: El Capitan frozen boot process Just thinking:
I have been reading a "lot" of users who's system just did not starts once it has been turned off or after a restar command.
Some things in common: Virtual machines, Boot camp, multiple partitions, I exactly do not know what could it be. But, behaviour is something about addressing the startup sequence.
At least in my case, my MBP (mid2009, 8GB, 1TB HDD) progress bar just keep static at 0%. The HDD has zero activity. So, it looks like it receives the command to start, but then do not know exactly what to do.
*
Something about the mounting point?
*Something about creating a virtual drive?
*Something about trying to use an already used space?
I will appreciate some help trying to fix it. As you did read, my MBP is pretty old, so battery is an issue. I must keep it fully charged to avoid restart from zero. Each time I must reinstall and it takes 1 hour from pen drive an a lot of network activity. Apart: My MBP is now a lot of times faster than using previous OSX. It has this awful pitfall, but in the other hand is a really excellent work.

A: You can troubleshoot El Capitan the same as any other OS X - boot in verbose mode to see a specific log of what is happening so you now the exact area in the boot process when it's failing.
Or you could install 10.11 on to a fresh, new USB drive and get a test that confirms your hardware isn't the problem since a clean install should boot properly.

*

*https://support.apple.com/en-us/HT201573 - How to start up your Mac in single-user or verbose mode

*https://support.apple.com/en-us/HT201262 - Try safe mode if your Mac doesn't finish starting up

A: The answer sent before … Mmmm... sorry. It did not work.
The verbose mode stopped too.
But yesterday I already solved my problem.
I did the following procedure starting in Recovery mode:
Part 1 of 2:
cd /Volumes/Mac\ Disk\ OSX2/Library/Extensions/; mkdir Unsupported ; mv Net* Unsupported ; mv Sym* Unsupported ; mv hp* Unsupported ; mv ndc* Unsupported ; cd /Volumes/Mac\ Disk\ OSX2/System/Library/Extensions/ ; mkdir Unsupported ; mv Belc* Unsupported ; mv Eltima* Unsupported ; mv hp* Unsupported ; mv Hua* Unsupported ; mv Netg* Unsupported ; mv Remo* Unsupported ; mv RIM* Unsupported ; mv USBEx* Unsupported ;
Part 2 of 2:
rm -Rf /Volumes/Mac\ Disk\ OSX2/Library/Filesystems/fuse ; rm -Rf /Volumes/Mac\ Disk\ OSX2/Library/Application\ Support/Sym* ; rm -Rf /Volumes/Mac\ Disk\ OSX2/var/folders/*
PLEASE READ THIS
You must be carefull about the real drive name.
Watch out: CHANGE THE VOLUME NAME TO YOURS –  and
Do not run Disk Utility
IP: This is not a work of mine. I found it in an apple forum.
Original Post in Apple forum
 Thanks to Bmike for trying to help, and everybody for forgive me because of my no native English.


text:
Q: jquery toggle+paginate+multiple instances I'm a jquery newbie - wanted to ask what might be the best strategy for achieving what I am after as I think it uses a mix of jquery functions :

*

*If list of items exceeds 5 items a 'more' link appears which when toggled will reveal the rest of the items. If items list is 5 or less no 'more' link is shown. Hide button also at bottom of long full revealed list. (perhaps this is toggle+pagination?)

*And then also that this can be used in multiple instances, as it is for multiple category menu's.(to be used in typical indexhibit websites structure like http://mikeyburton.com/)

*

*link 1

*link 2

*link 3

*link 4

*link 5

*link 6

*link 7

*link 8

*more

Any help or links greatly appreciated.

A: This will give you the number of matched elements in a certain class:
$('.element').size();

You can use hide() and show() as mentioned above, or use toggle() to hide and show the extraneous elements.  Or for large lists it might be prudent to load() or get() (ajax) those only when needed.
It looks like you want what's called an "accordion" function.  You can also achieve that effect using jQuery UI's accordion widget.
If you want to not show the "more" control then hide it at the appropriate times:
if ("li.all").size() > 5) {
    $("#toggler").hide();
}

A: This can be done many ways.
The simplest way would be to load all the items and then hide all but the first 5. This can be done via jQuery's show() and hide() methods. link You can also use the size() method to find out how many items of the same class you have.
Or you can use Ajax to load the other items when needed. link


text:
Q: docker swarm throws 404 page not found error while checking node details I'm setting up a swarm cluster. I am able to see the details with docker -H :4000 info. However when i try docker -H :4000 node ls it fails.
OS - RHEL 7
docker version:
$ docker version
Client:
 Version:      1.12.3
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   6b644ec
 Built:
 OS/Arch:      linux/amd64

Server:
 Version:      1.12.3
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   6b644ec
 Built:
 OS/Arch:      linux/amd64

docker info:
$ docker -H :4000 info
Containers: 23
 Running: 23
 Paused: 0
 Stopped: 0
Images: 35
Server Version: swarm/1.2.5
Role: primary
Strategy: spread
Filters: health, port, containerslots, dependency, affinity, constraint
Nodes: 7
...
...
Plugins:
Volume:
Network:
Swarm:
NodeID:
Is Manager: false
Node Address:
Security Options:
Kernel Version: 3.10.0-327.18.2.el7.x86_64
Operating System: linux
Architecture: amd64
CPUs: 28
Total Memory: 114 GiB
Name: c7ef56122f88
Docker Root Dir:
Debug Mode (client): false
Debug Mode (server): false

docker node ls:
docker -H :4000 node ls
*Error response from daemon: 404 page not found*

http-proxy.conf:
[Service]
[Service] Environment="HTTP_PROXY=http://proxy-domain.com:port" "HTTPS_PROXY=https://proxy-domain.com:port"

docker.conf:
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock -g /docker --cluster-store=consul://0.0.0.0:8500 --cluster-advertise eth0:2375

Not sure what I am missing here. My goal here is to apply swarm node label metadata so that I can make different pools as their sizes.
Any help would be appreciated.

PS: I am able run docker -H 4000 pull/start/stop/rmi/rm/network commands without any issue. its the "node" command does not work with swarm cluster.

Thanks in Advance

A: I am currently using docker swarm with service discovery(consul). docker swarm node management is available on new docker swarm mode(natively supported by docker engine 1.12+ - https://docs.docker.com/engine/swarm/). I will update the infrastructure to new swarm mode and will provide my findings here.


text:
Q: How do I escape '+' in data I'm sending via AJAX in Mootools? I was building a simple web based calculator which takes equations from a HTML form, evaluates it on the server using PHP and sends the result back.
I am using Mootools to send the data via the req.send AJAX operation.
But, each time I have a '+' in an equation, it is not seen on the POST data the server gets.
Any ideas why this is happening and how I can work around it?
eg:
10 + 12 in HTML form is seen as 10 12 in the $_POST data.
The Mootools send command I am using is something like this with
<textarea name="equationTextArea">10+12</textarea>

req.send("eqn="+$('equationTextArea').value);

Upon submit, I see $_REQUEST['eqn'] as 10 12.

A: Try using the function encodeURIComponent over your text value. It, well.. uri encodes your text.

A: Set your form's encoding to multipart/form-data - this is an alternative to the default application/x-www-form-urlencoded and doesn't encode a space  into a plus sign +.
Example from the w3.org reference:
<form action="http://example.com/cgi/handle"
   enctype="multipart/form-data"
   method="post">

A: Your text most likely either need to be URLEncoded.


text:
Q: How to run For loop in twig file in php opencart to make the results should be like below Suppose,
$a=1,2,3,4,5,6,7,8,9,10
then

in the for loop, it should run 1,2,3,4

and then 5 then 6,7,8,9 and then 10

then exit the loop.

A: You could use the batch and slice Twig filters for this. If you batch the results by groups of 5, then slice the first 4 and the 5th element you are able to loop through the results in the way you want.
Example code:
{% set items = [1,2,3,4,5,6,7,8,9,10] %}
{% for batch in items|batch(5) %}

item 1 through 4

    {% for item in batch|slice(0, 4) %}
        {{ item }}
    {% endfor %}

5th item

    {% for item in batch|slice(4, 1) %}
        {{ item }}
    {% endfor %}
{% endfor %}


text:
Q: Why does sshd ask for a host service principal when authenticating a user via pam or KerberosAuthentication I've setup Ubuntu for testing purposes.
-Installed MIT kerberos (latest)
-Installed OpeenSsh(latest)
I've setup and have working both KerberosAuthentication  and pam_krb5 types of authentication as well as GSSAPIAuthentication. All is well there.
When I setup only to use "KerberosAuthentication" or "pam_krb5"  I see requests for host/:
Nov 20 00:09:11 kdcname krb5kdc[12476](info): AS_REQ (2 etypes {16 17}) 192.168.1.104: NEEDED_PREAUTH: user@HELLO.COM for krbtgt/HELLO.COM@HELLO.COM, Additional pre-authentication required
Nov 20 00:09:11 kdcname krb5kdc[12476](info): AS_REQ (2 etypes {16 17}) 192.168.1.104: NEEDED_PREAUTH: user@HELLO.COM for krbtgt/HELLO.COM@HELLO.COM, Additional pre-authentication required
Nov 20 00:09:11 kdcname krb5kdc[12476](info): AS_REQ (2 etypes {16 17}) 192.168.1.104: ISSUE: authtime 1511154551, etypes {rep=17 tkt=18 ses=17}, user@HELLO.COM for krbtgt/HELLO.COM@HELLO.COM
Nov 20 00:09:11 kdcname krb5kdc[12476](info): AS_REQ (2 etypes {16 17}) 192.168.1.104: ISSUE: authtime 1511154551, etypes {rep=17 tkt=18 ses=17}, user@HELLO.COM for krbtgt/HELLO.COM@HELLO.COM
Nov 20 00:09:11 kdcname krb5kdc[12476](info): TGS_REQ (2 etypes {16 17}) 192.168.1.104: ISSUE: authtime 1511154551, etypes {rep=17 tkt=18 ses=17}, user@HELLO.COM for host/sshserver@HELLO.COM
Nov 20 00:09:11 kdcname krb5kdc[12476](info): TGS_REQ (2 etypes {16 17}) 192.168.1.104: ISSUE: authtime 1511154551, etypes {rep=17 tkt=18 ses=17}, user@HELLO.COM for host/sshserver@HELLO.COM

Is the host/ service principal needed for something (TGS_REQ)?
In my mind all you need is AS_REQ to validate the user's password.

A: It's to prevent man in the middle attacks against the KDC.
I found the answer in Google Books:
Pg 108/109 of kerberos the definitive guide seems authoritative.
I will delay in accepting this as an answer. There should be more of a write up here and my intent was not to self promote and copy/pasting more than a sentence or so seems inappropriate.


text:
Q: Why doesn't instagram work with Selenium headless Chrome? I'm trying to build an insta bot that works headless, but it don't seem to find the username, password columns (i.e NoSuchElementException).
I tried to run this code to troubleshoot. (which basicaly opens the ig homepage and screenshots it)
from selenium import webdriver
from time import sleep

options = webdriver.ChromeOptions()
options.headless = True
options.add_argument("--window-size=1920,1080")
browser = webdriver.Chrome(options=options)
browser.get("https://www.instagram.com")
browser.get_screenshot_as_file(f"screenshot.png")

and i got these screenshots basically saying 'error, retry after several minutes' in french
I tried finding the 'connectez-vous' button thru selenium, but every xpath i try doesn't work, and it's impossible to find it thru f12
The bot will be later uploaded to pythonanywhere so i can run it in the cloud (so if you think i might run into some other problems you can let me know)
What do you suggest me to do?

A: from selenium import webdriver
from time import sleep

options = webdriver.ChromeOptions()
#options.headless = True
options.add_argument("--window-size=1920,1080")
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument(
    "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
browser = webdriver.Chrome(options=options)
browser.get("https://www.instagram.com")
sleep(5)
#browser.refresh()
browser.get_screenshot_as_file(f"screenshot.png")

For headless chrome , useragent is set as chromeheadless or something , this makes instagram to detect that you are using headless chrome.
You can vent this by specifying hardcoded useragent,
open a normal chrome , goto network tab , open request header and copy the user agent part and replace in your code
Headless browser detection


text:
Q: Calling an action triggers multiple reducers? I just send one action in LoginAction, but it triggers three reducers. I don't know why...
Version:
"react": "16.9.0",
"react-native": "0.61.2",
"react-redux": "^7.1.1",
"redux": "^4.0.4",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.3.0",

Here is my setting.
App.js:
import React from 'react';
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { compose, createStore, applyMiddleware } from 'redux';
// import { persistStore } from 'redux-persist';
// import { PersistGate } from 'redux-persist/integration/react';
import reducers from './src/reducers';
import AppContainer from './src/navigator' // It is my react-navigation route

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const App: () => React$Node = () => {
  if (!__DEV__) {
    console.log = () => {};
  }

  const store = createStore(reducers, {}, composeEnhancers(applyMiddleware(ReduxThunk)));

  return (
    <Provider store={store}>
      <AppContainer />
    </Provider>
  );
};

export default App;

My LoginAction.js:
export const testAction = () => {
  return (dispatch) => {
    dispatch( { type: 'TEST_ACTION' });
  }
}

My reducer setting:
reducers/index.js
import { combineReducers } from 'redux';
import LoginReducer from './LoginReducer';
import StoreReducer from './StoreReducer';
import ReservationReducer from './ReservationReducer';

export default combineReducers({
  LoginRedux: LoginReducer,
  StoreRedux: StoreReducer,
  ReservationRedux: ReservationReducer
});

My LoginReducer.js: (StoreReducer and ReservationReducer are the same as LoginReducer)
const INITIAL_STATE = {
  ...my state arguments
};

export default (state = INITIAL_STATE, action) => {

  // Here is my issue !
  // StoreReducer is 'StoreReducer reducer =>', action
  // ReservationReducer is 'ReservationReducer reducer =>', action
  console.log('Login reducer =>', action);

  switch (action.type) {
    case 'SOME_ACTION':
      return {
        // state setting from action
      };
    default:
      return state;
    }
};

Call the action component is LoginScreen.js:
import React, { Component } from 'react';
import {
  // some view
} from 'react-native';
import { connect } from 'react-redux';
import { login, closeLoadingCheckModal, testAction } from '../actions';

class LoginScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // some states
    };
  }

  render() {
    return (
      <View>
        <TouchableOpacity onPress={() => { this.props.testAction() }>
          <Text>Press Test Action</Text>
        </TouchableOpacity>
      </View>
    );
  }
const mapStateToProps = (state) => {
  const { ...some store value  } = state.LoginRedux;

  return { ...some store value  };
};

}

export default connect(mapStateToProps, { login, closeLoadingCheckModal, testAction })(LoginScreen);

When I trigger the action, all of the reducers will be triggered.
It should only console log Login reducer =>
Anyone knows what is my problem?

A: If you're using combineReducers, all your slice reducers will run for every dispatched action.  It's a question of whether a given reducer actually calculates new state or not.
See the Redux FAQ entry on "is there a 1:1 mapping between reducers and actions?" for more details.

A: An action can indeed end update multiple reducers, if multiple reducers are implementing the same action type. In your case all three reducers listen for actions of type TEST_ACTION. If you don't want this behaviour you should make sure action types are unique throughout your app, for example by prefixing actions based on reducer.
export const testAction = () => {
  return (dispatch) => {
    dispatch( { type: 'LOGIN_TEST_ACTION' });
  }
}


text:
Q: static link pthread on ubuntu causes uninitialised value jumps (valgrind) When im statically linking the pthread library on ubuntu 20.04, using the gcc 11.1  compiler, during its runtime, my program works exactly as expected. However when i tried to run it in a debug mode and check with valgrind for any problems, i quickly discovered that linking the pthread library causes a lot of warnings to pop up. Why is that and is it something i should be worried about? (both std::thread and std::jthread display the same errors).
If i don't link the library statically, there are no errors or warnings.
main.cpp:
#include <iostream>
#include <thread>

void foo() {
    std::cout << "Hello world" << std::endl;
}

int main() {
    std::jthread t(foo);
    return 0;
}

Compile:
g++ main.cpp -std=c++20 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

The way im linking the pthread lib i took from here. Otherwise i'd get a segfault.
Sample of the errors i'm getting:
==9674== Syscall param set_robust_list(head) points to uninitialised byte(s)
==9674==    at 0x404E65: __pthread_initialize_minimal (nptl-init.c:272)
==9674==    by 0x4B858E: (below main) (in /home/example)
==9674==  Address 0x4000bf0 is in the brk data segment 0x4000000-0x400123f
==9674==
==9674== Conditional jump or move depends on uninitialised value(s)
==9674==    at 0x4F5780: __register_atfork (in /home/example)
==9674==    by 0x4F574C: __libc_pthread_init (in /home/example)
==9674==    by 0x405056: __pthread_initialize_minimal (nptl-init.c:368)
==9674==    by 0x4B858E: (below main) (in /home/example)
==9674==
==9674== Conditional jump or move depends on uninitialised value(s)
==9674==    at 0x4F5804: __register_atfork (in /home/example)
==9674==    by 0x4F574C: __libc_pthread_init (in /home/example)
==9674==    by 0x405056: __pthread_initialize_minimal (nptl-init.c:368)
==9674==    by 0x4B858E: (below main) (in /home/example)
==9674==
==9674== Conditional jump or move depends on uninitialised value(s)
==9674==    at 0x4FA870: malloc_hook_ini (in /home/example)
==9674==    by 0x5759DA: _dl_get_origin (in /home/example)
==9674==    by 0x5495F4: _dl_non_dynamic_init (in /home/example)
==9674==    by 0x54BF45: __libc_init_first (in /home/example)
==9674==    by 0x4B85C8: (below main) (in /home/example)

and it goes on and on about uninitialised values.

A:
If i don't link the library statically, there are no errors or warnings.

Linking libpthread or libc on Linux statically is almost always the wrong thing to do. Your executable may be broken in many subtle ways, if not now then in the future.
That said, the reason you get Valgrind errors is explained here.


text:
Q: how to calculate hysteresis resistor value TL431 I'm creating a small ESP32 based robot controller board. Partially as a self learning experience (mech engineer, self taught on eletrical front but this is for hobby use :P) and partially because it needs to a fairly bespoke collection of motor, servo and ESC outputs.
On the power mangement front I will be using a 2S lipo battery. The intent of the circuitry below is to provide a physical method to turn power on/off (SW1), provide a low battery power cutoff circuit (using TL431 and Q1) and to provide 5v supply for the servos and the controller.
My main questions are around the low voltage cutoff circuit but i've included the rest for context and in case you fancy letting me know i've done something wrong there also!
So for the battery cutoff circuit I have done the voltage divider calculations such that at the cutoff voltage (7.4v for a 2s lipo is the lower limit of safe discharge based on my research) the reference voltage entering the TL431 is 2.5v in line with it's internal voltage reference. I've simulated this on circuit lab and it seems to work well. My issue is that in the real world there will be some hystersis issues around the 7.4v value - I have found that you can add a feedback resistor (R4) around the TL431 but I can't for the life of my find a guided explanation of how to calculate that value such that i have a lower cutoff limit of 7.3 and a higher cutoff limit of 7.4 creating an effective band to prevent the circuit from flipflopping due to some noise or minor fluctuation in battery voltage.

edit 1 - first attempt at re-drawing the schematic for the TL431 to make it easier to read. bit confused by V+ and Vout in diagram provided in comments. In my head the Vout side should come from the battery so that the voltage divider always provides a reference to the TL431 but Vout notation to me sounds like that should be the voltage out of the IC? Also i swapped it to a P type transistor as per diagram - think the original schematic used an N type and a pull up resistor to reduce current drain?

Edit 2 - Took advice and instead of copying the circuit i tried to re-draw my original one. added some notes to help show my understanding of what each bit is doing. I'm a bit confused how the feedback resistor R8 works and doesn't just allow reduced flow through the circuit? I guess the super high resistance value (just used what was on an example i found online - here) causes a big voltage drop.

Edit 3 -
Hi all - I think i got my head round it this morning. here are the calcs i did to set the resistor values!

A: Big thank you to all those who helped me get to the answer (See comments under the question)
Firstly as per recommendation the schematic was re-drawn to make it easier to read. There is a bit of an industry standard for this style of circuit I wasn't aware of.

To calculate the value R8 should be it was pointed out that it functions as part of the voltage divider and this divider value is different depending on the condition because R8 is either 0 or Bat+. Therefore the trigger voltage for Bat+ ends up being different for turning on the circuit and turning it off. Calcs to achieve values for a 2S lipo shown below.


text:
Q: How do I build a hello-world console app to run on the .NET CoreCLR? I'd like to run a hello-world console app using the .NET CoreCLR.
So far, my code is as follows.
// Program.cs

using System;

namespace Study
{
    public class Program
    {
        public void Main()
        {
            Console.WriteLine("Hello world!");
        }
    }
}

// project.json

{
  "frameworks": {
    "dnxcore50": { }
  }
}

I'm attempting to run this project using the commands:
dnvm use 1.0.0-beta8 -r coreclr
dnx run

However this yields the following error:
Microsoft.Dnx.Compilation.CSharp.RoslynCompilationException: warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
(1,11): DNXCore,Version=v5.0 error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
(2,11): DNXCore,Version=v5.0 error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
(3,11): DNXCore,Version=v5.0 error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
(1,58): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
(2,54): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
(3,67): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
d:\rp\study\004dnxCoreHelloWorld\Program.cs(1,7): DNXCore,Version=v5.0 error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
d:\rp\study\004dnxCoreHelloWorld\Program.cs(5,18): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Object' is not defined or imported
d:\rp\study\004dnxCoreHelloWorld\Program.cs(7,16): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Void' is not defined or imported
d:\rp\study\004dnxCoreHelloWorld\Program.cs(9,31): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
d:\rp\study\004dnxCoreHelloWorld\Program.cs(9,13): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Object' is not defined or imported
d:\rp\study\004dnxCoreHelloWorld\Program.cs(9,13): DNXCore,Version=v5.0 error CS0103: The name 'Console' does not exist in the current context
d:\rp\study\004dnxCoreHelloWorld\Program.cs(5,18): DNXCore,Version=v5.0 error CS1729: 'object' does not contain a constructor that takes 0 arguments
   at Microsoft.Dnx.Compilation.CSharp.RoslynProjectReference.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)

...et cetera...

A: Project is missing System.Console dependency
This is how frameworks/dependencies sections may look like:
"dependencies": {
},

"frameworks": {
  "dnxcore50": {
    "dependencies": {
      "System.Console": "4.0.0-beta-*"
    }
  }
}

This is I think a minimal set.
to run use:
dnvm use 1.0.0-beta8 -r coreclr
dnu restore
dnx run

A: For CoreCLR, you need a reference to System.Runtime either directly or transitively.
So your project.json file should be:
{
    "frameworks": {
        "dnxcore50": {
            "System.Runtime": "4.0.21-beta-*",
            "System.Runtime.Extensions": "4.0.11-beta-*"
        }
    }
}


text:
Q: PyTorch's FFT not preserving Linearity I'm not sure if this is a bug or I'm misunderstanding something about the indexing/shifting. When I try to calculate the difference in the Fourier domain, something is going wrong in the calculation. For a simple case, consider a identity kernel K, such that for any signal X it follows that X - K*X = 0. Further, x - k o x = 0. However, when I compute the residual in the Fourier domain using pytorch, I don't get a numerically 0 solution.
import torch
from torch.fft import rfftn, irfftn
from PIL import Image
from torchvision.transforms import ToTensor
from torch.nn.functional import pad
from matplotlib import pyplot as plt

# Let X be an input image.
with Image.open("barbara.png") as im:
    X = ToTensor()(im)[0,...]

# Let K be a convolutional identity kernel.
K = torch.zeros((3,3))
K[1,1] = 1.0

# Full convolution shape.
cnvShape = (X.shape[0] + K.shape[0] - 1, X.shape[1] + K.shape[1] - 1)

# Apply DFT. Uncentered zero-padding to full shape.
Xhat = rfftn(X, s=cnvShape, dim=(0,1))
Khat = rfftn(K, s=cnvShape, dim=(0,1))

# Calculate convolution via Fourier domain.
XKhat = Xhat * Khat
XK = irfftn(XKhat, s=cnvShape)[1:-1,1:-1]
# Difference in spatial domain. Is numerically close to 0.
R = X - XK

# Difference in Fourier domain. This should be numerically close to 0.
Shat = Xhat - XKhat
S = irfftn(Shat)

plt.subplot(1,2,1)
plt.imshow(R)
plt.colorbar()
plt.subplot(1,2,2)
plt.imshow(S)
plt.colorbar()
plt.show()

# Center zeropad image FFT, produces numerically 0 solution.
That = rfftn(pad(X, (1,1)*2), s=cnvShape) - XKhat
T = irfftn(That)
plt.imshow(T)
plt.colorbar()
plt.show()

This results in

So from the last plot, I can see there's some sort of shifting going on with operations in the Fourier domain, but it's not intuitive what. I'd also like to figure out how to implement consistent operations in the Fourier domain, as this is just a small sample of what I need to compute. I'm aware of fftshift, but that doesn't seem to be appropriate here, as the shift doesn't seem to be with negative and positive frequencies. So, what is going on in the indexing?


text:
Q: Django the fastest way to do Query get list of items in row from table In my app I need to do fast Query but I don't know which is faster
materials = Material.objects.only('name')

Or do filter this in view
materials = Material.objects.all()

And then use for loop to show list of items from 'name' row
I think that first is better or there is better way to do this?
It cant be done with filter() because it need to show all of fields in this row.

A: If you only want the names, you can use a .values_list(..):
materials = list(Material.objects.values_list('name', flat=True))
This will avoid wrapping the records in Material objects. That being said, unless some of the columns contain (very) large amounts of data, using .only(..) will not significantly speed up the process. Furthermore software design-wise it is often better to fetch Material objects, since that means that you can define behavior in your Material model.


text:
Q: Which keyserver to use for Verifying signatures with GnuPG for YubiHSM SDK signature verification from the following URL I have downloaded the YubiHSM SDK https://developers.yubico.com/YubiHSM2/Releases/.
However the other URL says we need to validate the package by downloading the keys which is specified from the following URL:https://developers.yubico.com/Software_Projects/Software_Signing.html
However what is the keyserver do we need to use to download a key?
I will be using the following command to receive a key:
gpg --keyserver pgp.mit.edu --recv-keys 70D7145F2F35C4745501829A1B21578FC4686BFE
And the command output is as following:
gpg: keyserver receive failed: Server indicated a failure
Regards,
Sudheer

A: PGP key servers synchronise their keys so it shouldn't matter which one you use. Also, your system should be configured already to use a pool of key servers, so the --keyserver option is not required.
Try without the --keyserver option.
If that doesn't work, try with an alternative key server. For instance keyserver.ubuntu.com, sks.pgpkeys.eu, or keys.openpgp.org.


text:
Q: Uncaught ReferenceError: y (var) is not defined that's a real quick problem that I want to share with you all.. I'm not sure why.. but Chrome and Opera - I haven't tested on Firefox - just don't want to assume the value of my var (y), and it just doesn't happen on Edge and Explorer..
The objetive o the code is depending of the option o select the var y get a diferente value and consequently the var Uf too..
I started studying JavaScript a week ago.. so I'm really sorry for bothering you all! :)

function uf(x){
  if ( x == null) { y = 1;}
  if ( x == 1 ) { y = 1200; }
  if ( x == 2 ) { y = 1550; }
  if ( x == 3 ) { y = 1500; }
  if ( x == 4 ) { y = 1550; }

  var Uf = y;
}

  <select required>
    <option onclick="uf(null)">UF</option>
    <option onclick="uf(1)">RS</option>
    <option onclick="uf(2)">RJ</option>
    <option onclick="uf(3)">SP</option>
    <option onclick="uf(4)">MG</option>
  </select>

ERROR
Uncaught ReferenceError: y is not defined
at uf (JS.js:19)
at HTMLInputElement.onclick (Index.html:88)

A: function uf(x){
var y;
if ( x == null) { y = 1;}
if ( x == 1 ) { y = 1200; }
if ( x == 2 ) { y = 1550; }
if ( x == 3 ) { y = 1500; }
if ( x == 4 ) { y = 1550; }

var Uf = y;
}

A: I ended up doing this:

HTML

      <select id="selection" required>
        <option value="value1">UF</option>
        <option value="value2">RS</option>
        <option value="value3">RJ</option>
        <option value="value4">SP</option>
        <option value="value5">MG</option>
      </select>

JavaScript
var y = document.getElementById("selection").value;

var Uf = y;

Thanks for the help guys!


text:
Q: How to get a String data array from firebase on flutter? They're trying to get the fix and their positions from flutter but what I get is a string with all the data and not with their positions, i'm using BLoC
Firebase:
As you can see in firebase I have a data array

cloud_firestore_api.dart:
 Future<QuerySnapshot> getCites() async {
return await _db
    .collection('type_cites').getDocuments();
 }

cloud_firestore_repository.dart:
 Future<QuerySnapshot>getCites() => _cloudfireStoreAPI.getCites();

user_bloc.dart:
Future<QuerySnapshot>getCites()=> _cloudFirestoreRepository.getCites();

and here's where I send to call my function and what I get instead of an array is a string:
 import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:generic_bloc_provider/generic_bloc_provider.dart';
import 'package:/User/bloc/userbloc.dart';

class DatePickerScreen extends StatefulWidget {
  UserBloc userBloc;
  QuerySnapshot snapshot;

  @override
  State<StatefulWidget> createState() {
    return _DatePickerScreen();
  }
}

class _DatePickerScreen extends State<DatePickerScreen> {

  @override
  Widget build(BuildContext context) {
    widget.userBloc = BlocProvider.of<UserBloc>(context);
    widget.userBloc.getCites().then((result) {
      widget.snapshot = result;

    });
    return  RaisedButton(
          onPressed: () {
            print( widget.snapshot.documents[0].data);
          },
        );

  }
}

output:

and if I print the size of what it brings:

when I actually have it in an arrangement that has 3 positions and its size devernial of being 3 and not 1,
Any way to get the fix right from firebase?

A: Use following to print length of cites.
var documents =
    (await Firestore.instance.collection('collection').getDocuments())
        .documents;
print(documents[0].data['cites'].length);

Replace collection with your collection's name.


text:
Q: Allow access to windows service hosted WCF services only to one ASP MVC app in Azure I have:

*

*WCF services hosted in Windows service on my Azure virtual machine.

*ASP MVC web app hosted in Azure App service which connects to my WCF
services.
How can I make WCF services accessible only by ASP MVC app? In other words: only ASP MVC app is allowed to consume my WCF services.
Sorry for not having any code examples but WCF security is a very big topic and most examples I found cover only Windows domain WCF authorization. Nothing specific to my case.
Many thanks

A: I found a workaround to my problem.
In WCF proxy class derived from  ClientBase<T> I overrode base constructor with user credentials in PC where my WCF services are running.
base.ClientCredentials.Windows.ClientCredential.UserName = "localhost\\myUsername";
base.ClientCredentials.Windows.ClientCredential.Password = "myPassword";

in WCF service app.config:
<security mode="Transport">
          <message clientCredentialType="Windows" />
</security>

So now my services require credentials from any consumer.


text:
Q: Replacing cell data There is a table I am accessing from a remote server, and in this table there is a word "Blah blah". How do I get rid of this or replace it?
I tried the codes below but since I don't know if "Blah blah" is in a table cell, a table row, or a header, etc., I can't seem to get rid of it or replace it:
$("tr.header").filter(function(){ return $(this).text() == 'Blah blah';}).text('');
$("td.header").filter(function(){ return $(this).text() == 'Blah blah';}).text('');

"Blah blah" is right in the middle above the table retrieved by document.getElementById("datatable").innerHTML=xmlhttp.responseText;. Please help. Thank you.

A: demo in Fiddle
js:
$("td:contains('Blah blah')").html("HEHE nice");

HTML:

        Blah blah
        I am coll
        Blah blah

         Blah blah
        I am coll
        Blah blah

A: One approach I think should work is iterating over the td's inside your table and setting the text to empty.
$('table td').each(function () {
    $(this).text(function (i, v) {
        return v.replace(/Blah blah/g, '');
    });
});

Check Fiddle


text:
Q: Jacobian of the Product of Two Functions
Question: Let $f: U \to \mathbb{R}$ and $g: V \to \mathbb{R}$, where $U \subset \mathbb{R}^n$ and $V \subset \mathbb{R}^n$ both open.
  Now suppose we take the product of these two functions, i.e. formally
  the product rule
$$\mathbf{D}(fg)(a) = g\mathbf{D}f(a) + f\mathbf{D}g(a)$$

How would we construct a formula for the Jacobian of $f \cdot g$?
What I have so far is that
$$
\begin{align*}
g\mathbf{D}f(a) + f\mathbf{D}g(a) &= g\mathbf{D}
\begin{pmatrix}
f_1(\mathbf{a}) \\
\vdots \\
f_n(\mathbf{a})
\end{pmatrix}
+
f\mathbf{D}
\begin{pmatrix}
g_1(\mathbf{a}) \\
\vdots \\
g_n(\mathbf{a})
\end{pmatrix} \\
&= g
\begin{pmatrix}
\frac{\partial f_1}{\partial a_1} & \dots & \frac{\partial f_1}{\partial a_n} \\
\vdots & \ddots & \vdots \\
\frac{\partial f_n}{a_1} & \dots & \frac{\partial f_n}{\partial a_n}
\end{pmatrix}
+ f
\begin{pmatrix}
\frac{\partial g_1}{\partial a_1} & \dots & \frac{\partial g_1}{\partial a_n} \\
\vdots & \ddots & \vdots \\
\frac{\partial g_n}{a_1} & \dots & \frac{\partial g_n}{\partial a_n}
\end{pmatrix}.
\end{align*}$$
Do we simply multiply through $g$ and $f$ and add the two?


text:
Q: Marklogic : Score Calculation I have following xml file :
<?xml version="1.0" encoding="UTF-8"?>
<data>
<text>We are a doing nothing here you can say it time pass. what are you doing doing doing doing doing time?</text>
<text>We are a doing nothing here you can say it time pass. what are you doing doing doing doing doing time?</text>
</data>

Now i executed following query :
let $hits :=
let $terms :=
let $node := xdmp:document-filter(doc("/content/C/Documents and Settings/vimleshm/Desktop/abc.xml"))
return
(cts:distinctive-terms($node,
<options xmlns="cts:distinctive-terms"
xmlns:db="http://marklogic.com/xdmp/database">
<use-db-config>false</use-db-config>
<score>logtf</score>
<max-terms>100</max-terms>
<db:word-searches>true</db:word-searches>
<db:stemmed-searches>off</db:stemmed-searches>
<db:fast-phrase-searches>false</db:fast-phrase-searches>
<db:fast-element-word-searches>false</db:fast-element-word-searches>
<db:fast-element-phrase-searches>false</db:fast-element-phrase-searches>
</options>)//cts:term)
for $wq in $terms
where $wq/cts:word-query
return element word {
attribute score {                               $wq/@score},
$wq/cts:word-query/cts:text/string() }
return

let $x:=
for $hit in $hits

return $hit
return $x

It gives me following response  :
<?xml version="1.0" encoding="UTF-8"?>
<results warning="more than one root item">
  <word score="36864">doing</word>
  <word score="26624">text</word>
  <word score="26624">you</word>
  <word score="26624">time</word>
  <word score="26624">are</word>
  <word score="22528">a</word>
  <word score="22528">we</word>
  <word score="22528">it</word>
  <word score="22528">data</word>
  <word score="22528">can</word>
  <word score="22528">pass</word>
  <word score="22528">here</word>
  <word score="22528">nothing</word>
  <word score="22528">what</word>
  <word score="22528">say</word>
</results>

will anybody tell me how this score [log(term frequency)] actually calculated? Example in above case term "doing" 12 times out of total 42 words.
following are total terms and frequency[given in bracket] for above file
doing [12]
you [4]
time [4]
are [4]
a [2]
We [2]
nothing [2]
here [2]
can  [2]
say [2]
it [2]
pass [2]
what [2]

A: http://docs.marklogic.com/guide/search-dev/relevance#chapter is certainly the best place to start.
There's more going on here than logTF. There's also:

*

*IDF - how common are those words across the database?

*document length normalization - longer documents tend to have a word more ties than shorter documents, so the score gets scaled for document length

*and logTF is actually the natural log of a stepped TF function (for speed)

All these things work together to make score accurate but fast.


text:
Q: Blazor WASM calling Web API Core method to get the windows user name I am new to Blazor applications. My scenario is, I have to get back the Windows logged user name from the hosted Blazor WASM application on IIS.
Below are the steps I followed.

*

*Created a ASP.Net Web API Core project and decorated it with  [ApiController]. In the launchsettings.json file changed the following attributes.

"windowsAuthentication": true,
"anonymousAuthentication": false,

*Enabled Windows and disabled Anonymous authentication in the IIS where my Web API is hosted.

*In the Startup.cs file of the WebAPI configured the below

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

*In the controller method, added a property
private readonly IHttpContextAccessor _httpContextAccessor;
and initialized it in the constructor as below.
public UsersController(IUsersRepository usersRepository,

        IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor)

    {            _usersRepository = usersRepository;

            _webHostEnvironment = webHostEnvironment;

            _httpContextAccessor = httpContextAccessor;

    }

*Finally in the API method
[HttpGet("getusername")]
public string GetUserByName()
  {
         var principal=_httpContextAccessor.HttpContext.User;

         return  principal.Identity.Name;
 }

When I browse the above Web API from IIS and call the above API method, I get the proper user name with domain/username.
Everything looks good so far, the actual issue is with the Blazor Webassembly project which invokes the above Web API method. When the Blazor WASM is hosted on the IIS( the same server as the above Web API) and calls the API method to get the user name I always get a null value. I made similar changes as Web API to launchsettings.json file and in IIS Authentication( Enabled Windows and disabled Anonymous authentication) in Blazor WASM.
I am invoking the API as below
public async Task<string> GetUserName()
    {
        return await JsonSerializer.DeserializeAsync<string>
            (await _httpClient.GetStreamAsync($"api/users/getusername"), new
        JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
    }

Since this is going to be a intranet site, we did not want to do any authentication by having the user to login through a Login page. The site address is set to auto login in the Chrome browser settings.
Could you guide me in the right direction, not sure what I am missing.


text:
Q: How do you write a contour in polar coordinates that covers all and only $z \in \{\Re(z) \in [c-a, c+a] \}$, but $ \Im(z) \in [-b,b] $? I'm trying to do contour integration, but I need it over a specific subset of complex numbers $z$. Specifically, I need a contour that, for real numbers $a$, $b$, and $c$, it covers all and only $z \in \{ \Re(z) \in [c-a, c+a] \}$, but for all $z$ in the contour, $\Im(z) \in [-b,b] $. I also need it to be in polar form, that is, all points on $r(\theta)$, with $0 \le \theta \le 2\pi$, describe the boundary of the contour.
I'm basically asking for an ellipse that has radius $a$ on the real line, radius $b$ on the imaginary line and the center at $c+0i$.

A: In Cartesian coordinates:
$$\frac{(x-c)^2}{a^2}+\frac{y^2}{b^2}=1$$
Substitute $(x,y)=r(\cos \theta,\sin \theta)$ and solve $r$,
$$r_{\pm}(\theta)=
\frac{b^2 c\cos \theta \pm
      ab\sqrt{(a^2-c^2) \sin^2 \theta+b^2\cos^2 \theta}}
     {a^2\sin^2 \theta+b^2\cos^2 \theta}$$
A plot of $r$ vs $\theta$ when $(a,b,c)=(5,4,3)$ such that $a>c>0$

and the corresponding ellipse:

A plot of $r$ vs $\theta$ when $(a,b,c)=(3,4,5)$ such that $c>a>0$

and the corresponding ellipse:

Further points to be noticed:
Given $\theta \in [0, 2\pi]$, the contour with continuous $\theta$ should enclose the origin.  In this case, the mapping $\theta \mapsto r$ is surjective.
Now $0\in [c-a,c+a]$,
$$a> |c| \ge 0$$
See also another post of mine.
In particular, $c$ is the linear eccentricity, that is
$$a=\frac{b}{\sqrt{1-e^2}}=\frac{c}{e}=\sqrt{b^2+c^2}$$
Then
$$r(\theta)=\frac{b^2}{a-c\cos \theta}$$


text:
Q: Properly process nested array structure I am trying to process the below array using javascript. I need to loop through each group and its children and do something with the final result. I need to maintain a relationship from the parent to all of its groups/children. I thought I could achieve this using recursion, but I am failing to do so.
const columnGroups = [
  {
    label: "Grand Parent1",
    groupId: "gp1",
    children: [
      {
        label: "Group 1",
        groupId: "group1",
        children: [{ field: "group1_field1" }, { field: "group1_field2" }]
      },
      {
        label: "Group 2",
        groupId: "group2",
        children: [{ field: "group2_field1" }, { field: "group2_field2" }]
      }
    ]
  },
  {
    label: "Grand Parent2",
    groupId: "gp2",
    children: [
      {
        label: "Group 3",
        groupId: "group3",
        children: [
          {
            label: "Group 4",
            groupId: "group4",
            children: [{ field: "group4_field1" }]
          }
        ]
      }
    ]
  }
];

I have created a stackblitz to show what I have done so far:
https://stackblitz.com/edit/typescript-g37a33?file=index.ts
More clarification
As I loop through the groups, I need to create columns and add the children to the column to form a group.
For example the first item in the array with the groupId gp1: When I get to that item, I need to create a column with that id. Then I can see that it has children, which are also groups, so I create another column with the id group1 and add that as a child to gp1. I do the same with group2. Essentially I need to re-create the structure of columnGroups.

A: You'd have something like this:
You data structure is like:
An array of object, which may have a children property, which is in turn of an array of object (recursion). But each item in the children array might just have a field that is of interest, which can be processed or printed out in this case.

function processItems(arr, level = 0) {
  for (const e of arr) {
    if (e.label || e.groupId) console.log(`${" ".repeat(level * 4)}For ${e.label} ${e.groupId}`);
    if (e.field) console.log(`${" ".repeat(level * 4)}${e.field}`);
    if (e.children)
      processItems(e.children, level + 1);
  }
}

const columnGroups = [{
    label: "Grand Parent1",
    groupId: "gp1",
    children: [{
        label: "Group 1",
        groupId: "group1",
        children: [{
          field: "group1_field1"
        }, {
          field: "group1_field2"
        }]
      },
      {
        label: "Group 2",
        groupId: "group2",
        children: [{
          field: "group2_field1"
        }, {
          field: "group2_field2"
        }]
      }
    ]
  },
  {
    label: "Grand Parent2",
    groupId: "gp2",
    children: [{
      label: "Group 3",
      groupId: "group3",
      children: [{
        label: "Group 4",
        groupId: "group4",
        children: [{
          field: "group4_field1"
        }]
      }]
    }]
  }
];

processItems(columnGroups)


text:
Q: Trouble understanding meaning of "driver" in nodejs I am having trouble trying to understand what is meant by a MongoDB driver for nodejs. Is driver another way to say a module or a library?

A: At the end of the day- yes.
The term comes from os drivers which allow the os to communicate with different hardware.
The mongo driver for node allows node to communicate with an external entity (mongo in this case) using js api inside the node application.


text:
Q: update a row if already exists else insert CREATE TABLE bonuses (employee_id NUMBER, bonus NUMBER DEFAULT 100);

This create table query.
Datas to insert:
INSERT INTO bonuses (employee_id) VALUES(111)
INSERT INTO bonuses (employee_id) VALUES(112)
INSERT INTO bonuses (employee_id) VALUES(113)
INSERT INTO bonuses (employee_id) VALUES(114)
INSERT INTO bonuses (employee_id) VALUES(115)

Trying into use merge query for either insert or update
merge into bonuses
using( SELECT * FROM bonuses)s ON s.employee_id = 111
WHEN MATCHED THEN update set bonus='555'
WHEN NOT MATCHED THEN insert insert into BONUSES (employee_id) values(116)

It should modify value of bonus where employee_id=111
I'm getting an error while executing this.
This is just sample table, I have created to test the merge exec.

A: This looks very wrong. The USING clause is supposed to specify the source for the update/insert. So you are mainly saying "I want to update my bonuses with the data from my bonuses table". Accordingly for every record in the table you check whether to insert or update.
Use a dummy single source record instead. (And the ON clause in a MERGE requires parantheses.)
MERGE INTO bonuses
USING (SELECT * FROM dual) s ON (bonuses.employee_id = 111)
WHEN MATCHED THEN UPDATE SET bonus = '555'
WHEN NOT MATCHED THEN INSERT (employee_id) VALUES (116);

It's surprising though, that you don't set the bonus in the insert. (And it's also a rare case to check for one employee ID and if not present insert another.)
Here is a more typical query, but this only affects employee ID 111:
MERGE INTO bonuses
USING (SELECT 111 as employee_id, 555 as bonus FROM dual) src
   ON (bonuses.employee_id = src.employee_id)
WHEN MATCHED THEN UPDATE SET bonus = src.bonus
WHEN NOT MATCHED THEN INSERT (employee_id, bonus) VALUES (src.employee_id, src.bonus);


text:
Q: Can AJAX use protocols other than HTTP or HTTPS? I wonder if AJAX can use protocols other than HTTP or HTTPS.

A: Ajax means XMLHttpRequest. Just as you don't have to use XML with XHR, you also don't have to use HTTP.

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).

From the W3C XMLHttpRequest spec (emphasis added):

The XMLHttpRequest object implements an interface exposed by a scripting engine that allows scripts to perform HTTP client functionality, such as submitting form data or loading data from a server. It is the ECMAScript HTTP API.
The name of the object is XMLHttpRequest for compatibility with the Web, though each component of this name is potentially misleading. First, the object supports any text based format, including XML. Second, it can be used to make requests over both HTTP and HTTPS (some implementations support protocols in addition to HTTP and HTTPS, but that functionality is not covered by this specification). Finally, it supports "requests" in a broad sense of the term as it pertains to HTTP; namely all activity involved with HTTP requests or responses for the defined HTTP methods.

The available protocols beyond HTTP and HTTPS are non-standardized, so they depend on the specific environment1 you're using. That is, all compliant XHR implementations must support HTTP and HTTPS, but are not required to support any other specific protocols. That means that you might find that Internet Explorer supports

1Such as, which version of which browser (Safari vs Firefox vs Chrome vs IE vs Opera vs...), or which server-side implementation (V8 vs Rhino vs...)

A: XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script.
from wikipedia


text:
Q: How to chose a value of a constant type based on an unrelated type? Ok, so I got the following simplified working example before the change I want to make:
data D = D
data C = C

class T a where
  t :: a

instance T D where
  t = D

instance T C where
  t = C

g :: T a => IO a
g = do
  return t

main = (g :: IO D) >> return ()

So the problem is that, inside g, I want values of types unrelated a to be chosen based on a. In other words, I want to express that if a is C then some value of yet unmentioned type e will be chosen and if it's not then another value of type e will be chosen. It's basically conditionalizing on arbitrary type equality, like pseudocode if a ~ Bool then "foo" else "bar". I tried this like so (using String for the type e in this example):
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
import Data.Proxy

class F sub1 sub2 where
  f :: Proxy (sub1, sub2) -> String

instance {-# OVERLAPPABLE #-} F a b where
  f _ = "did not match types"

instance {-# OVERLAPPING #-} F a a where
  f _ = "matched types"

data D = D
data C = C

class T a where
  t :: a

instance T D where
  t = D

instance T C where
  t = C

g :: forall a b. (T a, F b a) => IO a
g = do
  putStrLn $ f (Proxy :: Proxy (D, a))
  putStrLn $ f (Proxy :: Proxy (C, a))
  return t

main = (g :: IO D) >> return ()

I get the following errors, though:
y.hs:30:14: error:
    • Overlapping instances for F D a arising from a use of 'f'
      Matching instances:
        instance [overlappable] F a b -- Defined at y.hs:10:31
        instance [overlapping] F a a -- Defined at y.hs:13:30
      (The choice depends on the instantiation of 'a'
       To pick the first instance above, use IncoherentInstances
       when compiling the other instance declarations)
    • In the second argument of '($)', namely
        'f (Proxy :: Proxy (D, a))'
      In a stmt of a 'do' block: putStrLn $ f (Proxy :: Proxy (D, a))
      In the expression:
        do putStrLn $ f (Proxy :: Proxy (D, a))
           putStrLn $ f (Proxy :: Proxy (C, a))
           return t
   |
30 |   putStrLn $ f (Proxy :: Proxy (D, a))
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^

y.hs:31:14: error:
    • Overlapping instances for F C a arising from a use of 'f'
      Matching instances:
        instance [overlappable] F a b -- Defined at y.hs:10:31
        instance [overlapping] F a a -- Defined at y.hs:13:30
      (The choice depends on the instantiation of 'a'
       To pick the first instance above, use IncoherentInstances
       when compiling the other instance declarations)
    • In the second argument of '($)', namely
        'f (Proxy :: Proxy (C, a))'
      In a stmt of a 'do' block: putStrLn $ f (Proxy :: Proxy (C, a))
      In the expression:
        do putStrLn $ f (Proxy :: Proxy (D, a))
           putStrLn $ f (Proxy :: Proxy (C, a))
           return t
   |
31 |   putStrLn $ f (Proxy :: Proxy (C, a))
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^

y.hs:34:9: error:
    • Overlapping instances for F b0 D arising from a use of 'g'
      Matching instances:
        instance [overlappable] F a b -- Defined at y.hs:10:31
        instance [overlapping] F a a -- Defined at y.hs:13:30
      (The choice depends on the instantiation of 'b0'
       To pick the first instance above, use IncoherentInstances
       when compiling the other instance declarations)
    • In the first argument of '(>>)', namely '(g :: IO D)'
      In the expression: (g :: IO D) >> return ()
      In an equation for 'main': main = (g :: IO D) >> return ()
   |
34 | main = (g :: IO D) >> return ()
   |         ^

The errors suggest IncoherentInstances but it doesn't seem like it would chose the correct instance. I've yet to come up with something new to try.
EDIT: Just for the sake of seeing what would happen, I activated IncoherentInstances, but it results in the same errors.
EDIT 2: I'll explain how the example is linked to my practical, actual scenario. g represents an HTML form. This form can return different types represented by T. These different types use different subsets of the fields in the form. The lines in g that have putStrLn and f represent the definitions of the fields in the form. f represents deciding whether or not to validate a field depending on if the form is returning a type that depends on it.
As an example, the form might return a type DocSectionA or DocSectionB. A field might be type Text, and we want to express that a particular field should only be validated when the form is returning a DocSectionA, and another field should only be validated when the form is returning a DocSectionB.
I hope this helps.

A: I don't understand what your T class is for. It doesn't appear to actually be used in an interesting/relevant way. But your f can be implemented using equality checks on TypeReps. For example:
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

import Data.Type.Equality
import Type.Reflection

data C = C
data D = D

f :: forall a b. (Typeable a, Typeable b) => String
f = case testEquality (typeRep @a) (typeRep @b) of
    Just Refl -> "matched"
    _ -> "didn't match"

g :: forall a. Typeable a => IO ()
g = do
    putStrLn (f @C @a)
    putStrLn (f @D @a)

main = g @D

You can of course use proxies in the usual way to avoid ScopedTypeVariables and AllowAmbiguousTypes if that's your preferred way. I've used the new fancy-typed version of Typeable: although we didn't use it above, in the "matched" branch of f, not just us but also the typechecker knows that a ~ b.

A: Here's how we'd do it nowadays with ambiguous types and type applications. Ambiguous types allow you to have class members that don't mention the class parameters (otherwise you can use proxies).
Here c is 0 if a ~ T, or 1 if a ~ U:
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications #-}

data T
data U

class C a where
  c :: Int

instance C T where
  c = 0

instance C U where
  c = 1

main :: IO ()
main = print (c @T) >> print (c @U)

If you really want to match any type in the event that a is not T (why would you though), you can use overlapping instances (and the GHC manual is the best reference about how they work):
{-# LANGUAGE FlexibleInstances #-} -- in addition to the above

instance {-# OVERLAPPABLE #-} C a where
  c = 0

main = print (c @String)


text:
Q: Live Video on website, conferencing A friend of mine, an author, wants to do on-line book readings.
We have a very simple setup and would like to stream live Video through her web site.
Her client PC runs on Windows XP, has a standard Webcam and is connected to the Internet through a DSL Line.
Her web site runs on shared hosting, PHP available, no video streaming server available but plenty of space (8GB)
Does anybody have ideas how to:

*

*Transmit video live from her computer/webcam input onto a video embed on her web site (Proprietary plugins are an option)

*Share a video conference conducted through any free or reasonable priced video messaging solution onto a video embed on her web site?
While a free/open source solution would be preferred, a modestly priced commercial solution would also be an option.
Your input is much appreciated.

A: USTREAM seems to be a good fit for this. It allows you to transmit live from your webcam, and they even provide you with embed codes for your website:

Stickam also has the ability to do live broadcasts, they also provide embed codes for your website.

A: If you don't mind coding your own solution a bit, the new webcam features in Silverlight 4 could probably be used to create a free solution for yourself.  It's still beta at the moment, but in the videos and demos I've seen so far looks to be very promising and could be applied for just this type of situation.

A: Ustream worked really well for me.
I had to set up a live stream of a funeral at the last minute, and it took me under 20 minutes to write a webpage from scratch, drop in the Ustream embed code, and run a test from my iPad. This is the only time in my life that I've seen technology work flawlessly and effortlessly.
Use Ustream.


text:
Q: Question about Munkres' proof that the fundamental group of $S^1$ is isomorphic to the integers I have one quick question about the proof that the fundamental group of $S^1$ is isomorphic $\mathbb{Z}$. I think that I understand the proof, but there is just one detail that I wanna clarify. At some point, Munkres wrote that:

Given $[f]$ and $[g]$ in $\pi_1(B, b0)$, let $\tilde{f}$ and $\tilde{g}$ be their respective liftings to paths on $\mathbb{R}$ beginning at $0$.

The thing that causes me some problem is that Munkres seems to state that there is one lifting to  path on $\mathbb{R}$ for each path-homotopy equivalence class. However, I thought that there was a lifting to path for each $f$ of $[f]$, but that they were all homotopic, i.e. $[\tilde{f}]$ is the path-homotopy equivalence class containing each of the lifting to path of elements of $[f]$. So my question is, is there one unique lifting to path beginning at one defined point for each path-homotopy equivalence class ?
In the context of the proof, this is not really important because what matters is the end of the lifting to paths.
Thanks !

A: Let $u, v : X \to S^1$ be maps having lifts $\tilde u, \tilde v : X\to \mathbb R$. Of course a neccessary condition for $\tilde u = \tilde v$ is $u = v$.
Thus there does not exist a common lift for all representatives of an element of $\pi_1(S^1,b_0)$. I therefore think that Munkres' formulation is a bit misleading. Actually he considers $a, b \in  \pi_1(S^1,b_0)$, chooses representatives $f \in a$ and $g \in b$ and lifts them to paths $\tilde f, \tilde g$ both beginning at $0$. For his further considerations only the endpoints of $\tilde f, \tilde g$ are relevant, and these only depend on the path homotopy classes $a, b$. The purpose of the paths $\tilde f, \tilde g$ is to find a lift of the product path $f * g$ which represents $a * b$.


text:
Q: At the point $\sqrt{2}$ in the real line, does *every* n-ball around that point contain a rational? Is it trivial to prove?
Obviously a ball of some radius will contain a rational number, but what about for all $\varepsilon > 0$ ?

A: Yes, this is because your open ball is going to contain at least two different real numbers, between any two real numbers there is a rational number.

A: Yes. An easy way of seeing is take the (infinite) decimal expansion of $\sqrt2$ (or for that matter any real number, rational or not).
Given an $\varepsilon>0$, we look for a number of the form $1/10^m$ that is less than that. Now take a number $x$ that agrees with $\sqrt2$ in the first $m$  (or $m+1$, to be safe) places after decimal point and then has only zeros in all the remaining positions: this $x$ is a rational number within $\varepsilon$ distance of $\sqrt2$.

A: Try to think of it this way.  Let $I$ be an open interval of length $\epsilon>0$.  Then there is a natural number $n$ such that $\frac1n<\epsilon/2$.  Now start at the origin and start walking along the real line taking steps of size $\frac1n$.  You cannot completely straddle the interval $I$ taking steps of that size, so one of the steps must land within $I$.  Say it's the $m$-th step.  Then $\frac mn\in I$.  And $\frac mn\in\mathbb Q$.


text:
Q: Append protobuf repeated field message ColectionData
{
   repeated collection1 = 1;
   repeated collection2 = 2;
}

I am retrieving the data from message like,
auto collection = collectionData.collection1();

Now, I need to append this collection with collectionData.collection2()

A: This can be achieved by collection.MergeFrom()


text:
Q: Python. converting 2 lists into one dictionary object
Possible Duplicate:
Map two lists into a dictionary in Python

I have 2 lists like this:
['one', 'two', 'three']
and
[1, 2, 3]
I want to turn it into a dictionary like this
{'one':1, 'two':2, 'three':3}
The catch is that i have to use comprehension.
Thanks.

A: keys = ['one', 'two', 'three']
values = [1, 2, 3]
dict(zip(keys, values))

this is already the most pythonic way.
You can use a dict comprehension, if you really must:
{k: v for k,v in zip(keys, values)}

A: keys=['one', 'two', 'three']
values= [1, 2, 3]
dictionary = dict(zip(keys, values))

>>> print dictionary
{'one': 1, 'two': 2, 'three': 3}

Take a look at builtin functions, they often become handy. You can use dict comprehensions from Python 2.7 up, but the they should not be the way to do it:
{k: v for k, v in zip(keys, values)}

A: dict(zip(list1, list2))

is probably the best way to do it. Don't use comprehensions, that's a silly requirement.

A: Well, if you must:
keys = ['one', 'two', 'three']
values = [1,2,3]
d = {a:b for a,b in zip(keys,values)}

But seriously, just use dict(zip(keys, values))


text:
Q: How to make RecyclerView header not sticky? i have the following layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.mkallingal.freakingnav.CardsListFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/darktext"
        android:layout_marginBottom="6dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Cards Listing" />

    <android.support.v7.widget.RecyclerView android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/rvCardsList"
        android:scrollbars="vertical" tools:listitem="@layout/recycler_item_layout">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

the problem is that the TextView is always sticky on the top, while RecyclerView takes the remaining space on the screen. I can horizontal scroll the recyclerview, but the TextView just stay there. How do i resolve this?

A: You can add the Header View/TextView at the 0th element of the recyclerView.
Here is the good example describing the same.
Is there an addHeaderView equivalent for RecyclerView?
Edit (Copying the source from the link mentioned)
:-
There isn't an easy way like listview.addHeaderView() but you can achieve this by adding a type to your adapter for header.
Here is an example
public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    String[] data;

    public HeaderAdapter(String[] data) {
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new VHItem(null);
       } else if (viewType == TYPE_HEADER) {
           //inflate your layout and pass it to view holder
           return new VHHeader(null);
       }

        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VHItem) {
            String dataItem = getItem(position);
            //cast holder to VHItem and set data
        } else if (holder instanceof VHHeader) {
           //cast holder to VHHeader and set data for header.
       }
   }

   @Override
    public int getItemCount() {
       return data.length + 1;
    }

    @Override
    public int getItemViewType(int position) {
       if (isPositionHeader(position))
           return TYPE_HEADER;

       return TYPE_ITEM;
   }

   private boolean isPositionHeader(int position) {
       return position == 0;
   }

   private String getItem(int position) {
       return data[position - 1];
   }

    class VHItem extends RecyclerView.ViewHolder {
        TextView title;

       public VHItem(View itemView) {
           super(itemView);
        }
    }

   class VHHeader extends RecyclerView.ViewHolder {
       Button button;

       public VHHeader(View itemView) {
           super(itemView);
       }
   }
}

A: Its also worth checking out, XRecyclerView, it supports  pullrefresh , loadingmore and header featrues.


text:
Q: Why doesn't `use std::{ self, ... };` compile? I have no idea why this code can't be compiled with Rust 1.27.0.
This is test.rs as it is on my hard drive:
use std::{
  self,
  io::prelude::*,
  net::{ TcpListener, TcpStream },
};

fn main() {}

Output when trying to compile it with rustc test.rs:
error[E0254]: the name `std` is defined multiple times
 --> test.rs:2:5
  |
2 |     self,
  |     ^^^^ `std` reimported here
  |
  = note: `std` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
  |
2 |     self as other_std,
  |     ^^^^^^^^^^^^^^^^^

warning: unused imports: `TcpListener`, `TcpStream`, `io::prelude::*`, `self`
 --> test.rs:2:5
  |
2 |     self,
  |     ^^^^
3 |     io::prelude::*,
  |     ^^^^^^^^^^^^^^
4 |     net::{TcpListener, TcpStream},
  |           ^^^^^^^^^^^  ^^^^^^^^^
  |
  = note: #[warn(unused_imports)] on by default

A: This works fine in Rust 2018. You probably just want to update by adding edition = "2018" to your Cargo.toml or --edition=2018 to your rustc invocation. Below is the answer for why this doesn't work in Rust 2015.

From the std::prelude documentation:

On a technical level, Rust inserts
extern crate std;

into the crate root of every crate, and
use std::prelude::v1::*;

into every module.

You can also see that in action when looking at your code after macro expansion (e.g. via cargo-expand). For your code this results in:
#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std;
// No external crates imports or anything else.

use std::{
    self,
    net::{TcpListener, TcpStream},
};

fn main() {
    // Empty.
}

As you can see, std is already in scope due to the extern crate std; statement. Thus, importing it another time results in this error.


text:
Q: ¿Cómo calcular un cuartil bajo ciertas condiciones en R? explicaré lo que intento hacer:
Necesito obtener el cuartil inferior (percentil 25) de la variable PU, sin embargo ese cuartil debe ser construido a partir de todos los valores de la variable Codigo que sean iguales a A11
Nombre          Estado  Codigo    PU
   <chr>           <chr>   <chr>  <dbl>
 1 independiente1  Tercero A12       30
 2 independiente2  Tercero A11       20
 3 independiente3  Tercero A12       18
 4 independiente4  Tercero A11       16
 5 independiente5  Tercero A12       44
 6 independiente6  Tercero A11       30
 7 independiente7  Tercero A12       23
 8 independiente8  Tercero A11       45
 9 independiente9  Tercero A12       23
10 independiente10 Tercero A11       19

Estoy aprendiendo R, agradezco todo tipo de sugerencias, ya que he buscado como aplicar dichas condiciones sin éxito alguno.

A: Una forma de resolverlo utilizando tidyverse es:
df = df %>%
  group_by(Codigo) %>%
  mutate(per25 = ifelse(Codigo == "A11", quantile(PU, 0.25), NA))

Agrupar por Codigo para cuando calculemos el percentil 25 lo calcule para cada grupo, finalmente con el mutate creamos la variable bajo la condicion que solo lo calcule para los codigos A11 y cuando no sea el caso lo deje como NA