text:
Q: error in sqlite3_exe() sir i have working with db connectivity i have written all code and i imported the header file also.but its showing the error in the line of sqlite3_exe symbol not found in architecture
help me to clear...!!!!
 NSFileManager *filemgr=[NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath]==NO)
{
    const char *dbpath=[databasePath UTF8String];
    if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
    {
        char *errorMsg;
        const char *sql_stmt="CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT,  NAME TEXT, ADDRESS TEXT, PHONE NUMERIC)";
        if (sqlite3_exe(contactDB, sql_stmt, NULL,NULL, &errorMsg)!=SQLITE_OK)
        {
            status.text=@"Failed to crate table";
        }
        sqlite3_close(contactDB);
    }else {
        status.text=@"Faild to open/create database";
    }
}

the error line is
if (sqlite3_exe(contactDB, sql_stmt, NULL,NULL, &errorMsg)!=SQLITE_OK)

warning is the implicit declaration of function "sqlite3_exe" is invalid in c99.
error is Undefined symbols for architecture i386:
 "_sqlite3_exe", referenced from:
  -[DatabaseViewController viewDidLoad] in DatabaseViewController.o

ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: It is sqlite3_exec. Not sqlite3_exe.
Please check.
"C" is missing in exe.

A: Here is the sample code for the same. You can record the audio here. you can
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

    - (void) startRecording{

    UIBarButtonItem *stopButton = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStyleBordered  target:self action:@selector(stopRecording)];
    self.navigationItem.rightBarButtonItem = stopButton;
    [stopButton release];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }

    recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    [recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

    // Create a new dated file
    NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *caldate = [now description];
    recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];

    NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
    err = nil;
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
    if(!recorder){
        NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: [err localizedDescription]
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }

    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;

    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: @"Audio input hardware not available"
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [cantRecordAlert show];
        [cantRecordAlert release];
        return;
    }

    // start recording
    [recorder recordForDuration:(NSTimeInterval) 10];

    }

    - (void) stopRecording{

    [recorder stop];

    NSURL *url = [NSURL fileURLWithPath: recorderFilePath];
    NSError *err = nil;
    NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
    if(!audioData)
        NSLog(@"audio data: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    [editedObject setValue:[NSData dataWithContentsOfURL:url] forKey:editedFieldKey];

    //[recorder deleteRecording];

    NSFileManager *fm = [NSFileManager defaultManager];

    err = nil;
    [fm removeItemAtPath:[url path] error:&err];
    if(err)
        NSLog(@"File Manager: %@ %d %@", [err domain], [err code], [[err userInfo] description]);

    UIBarButtonItem *startButton = [[UIBarButtonItem alloc] initWithTitle:@"Record" style:UIBarButtonItemStyleBordered  target:self action:@selector(startRecording)];
    self.navigationItem.rightBarButtonItem = startButton;
    [startButton release];

    }

    - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
    {

    NSLog (@"audioRecorderDidFinishRecording:successfully:");
    // your actions here

    }

For Playing You can use these lines in stop recording method:
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                               pathForResource:@"click"
                                               ofType:@"caf"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click play];
    [click release];

Make sure you are passing the correct URL of the recorded sound path into the app. And these lines will play them for you in audio player.


text:
Q: visibility hidden vs -webkit-transform: translate3d() in phonegap application So I am using phonegap to create a hybrid application. Now obviously I have many divs(page size) that I hide and show using css "visibility: hidden and visible" property. I read somewhere that by using -webkit-transform: translate3d() I can hide the divs offscreen and show them again when needed and that this technique is much better. Does anyone know is this really true or not?

A: The main reason why anyone would want to use translations instead of standard visibility or display attributes is perception of performance. One can control exactly how a transition from one state to another state performs. A good example is mobile apps where transitions with animations are very popular.
If you want to use it within your app and do not need third party controls or out of the box MV** support, take a look at the Famo.us framework (http://famo.us/). While it lucks controls, it is very fast, uses transformations and incapsulates browser details.
Kendo UI Mobile is another good framework. It is a MV** framework, has a reasonable set of controls and ability to control look and feel. While it is a complete framework, one can integrate it with with Knockout and AngularJS.
And of course, give it try to Ionic (http://ionicframework.com/) and see if it is fast enough for you.
In any case, it is the best to use some framework and not use it directly. It is a lot of work to do otherwise correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Seleniumwire dont intercept HTTPS if user-data-dir is defined I try to intercept requests by seleniumwire.
If I dont use option --user-data-dir everything is fine. All requests are showed by driver.requests.
But I need parse some sites with authentication. So I provide in --user-data-dir option profile with remembered accounts. But in this case HTTPS requests not intercepted.
Command driver.requests showes only requests to google-ads and some other trash.
So how to intercept HTTPS requests while providing profile?

A: I should to disable all proxy extensions.
options.add_arguments("--disable-extensions")


text:
Q: Google OAuth access tokens I'm so confused by OAuth and Google. It took me forever to get the refresh_token to create a new access_token. Then to find out the refresh_token expires too?? What is the point of that!!!??
All I need to do is persist a valid access_token for use with legato.
Here is what I manually enter into my terminal to retrieve an OAUTH code:
client = OAuth2::Client.new('GA_CLIENT_ID', 'GA_SECRET_KEY', {
        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
        :token_url => 'https://accounts.google.com/o/oauth2/token'
})
client.auth_code.authorize_url({
       :scope => 'https://www.googleapis.com/auth/analytics.readonly',
       :redirect_uri => 'http://localhost',
       :access_type => 'offline',
       :approval_prompt=> 'force'
})

Then I manually enter the outputted url to in my browser. I export the returned OAUTH code as to an env variable and get the access token:
access_token = client.auth_code.get_token(ENV['GA_OAUTH_CODE'], :redirect_uri => 'http://localhost')

Then I can access the access_token and refresh_token:
   begin
      api_client_obj = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {:site => 'https://www.googleapis.com'})
      api_access_token_obj = OAuth2::AccessToken.new(api_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'])
      self.user = Legato::User.new(api_access_token_obj)
      self.user.web_properties.first # this tests the access code and throws an exception if invalid
    rescue Exception => e
      refresh_token
    end

  end

  def refresh_token
    refresh_client_obj =  OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
            :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
            :token_url => 'https://accounts.google.com/o/oauth2/token'
        })
    refresh_access_token_obj = OAuth2::AccessToken.new(refresh_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'], {refresh_token: ENV['GA_OAUTH_REFRESH_TOKEN']})
    refresh_access_token_obj.refresh!
    self.user = Legato::User.new(refresh_access_token_obj)
  end

After an hour, my tokens expire and I have to manually start the process over again from the browser! How can I replicate this in code??

A: Here you go, made a little something just for you :)
It's a simple implementation, specifically to ease the pain of renewing tokens.
Just be sure to:

*

*Put in your own APP_ID and APP_SECRET.

*Either only save your refresh_token and call refresh_token() every time before you use it, or use refresh_token_if_needed() every time, and re-save the token and expires_at (preferred obviously , since you'll only refresh when needed).

*Let me know how it worked out.

.
require 'gmail'
require 'gmail_xoauth'
require 'httparty'

class GmailManager
  APP_ID      = "DDDDDDDDDDDD-SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.apps.googleusercontent.com"
  APP_SECRET  = "SSSSSS-SSSSSSSSSSSSSSSSS"

  def refresh_token(refresh_token)
    Rails.logger.info "[GmailManager:refresh_token] refreshing using this refresh_token: #{refresh_token}"
    # Refresh auth token from google_oauth2 and then requeue the job.
    options = {
      body: {
        client_id:     APP_ID,
        client_secret: APP_SECRET,
        refresh_token: refresh_token,
        grant_type:    'refresh_token'
      },
      headers: {
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    }
    response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options)
    if response.code == 200
      token = response.parsed_response['access_token']
      expires_in = DateTime.now + response.parsed_response['expires_in'].seconds
      Rails.logger.info "Success! token: #{token}, expires_in #{expires_in}"
      return token, expires_in
    else
      Rails.logger.error "Unable to refresh google_oauth2 authentication token."
      Rails.logger.error "Refresh token response body: #{response.body}"
    end
    return nil, nil
  end

  def refresh_token_if_needed(token, expires_on, refresh_token)
    if token.nil? or expires_on.nil? or Time.now >= expires_on
      Rails.logger.info "[GmailManager:refresh_token_if_needed] refreshing using this refresh_token: #{refresh_token}"
      new_token, new_expires_on = self.refresh_token(refresh_token)
      if !new_token.nil? and !new_expires_on.nil?
        return new_token, new_expires_on
      end
    else
      Rails.logger.info "[GmailManager:refresh_token_if_needed] not refreshing. using this token: #{token}"
    end
    return token, expires_on
  end
end


text:
Q: Upgrading Zend Framework Advise I am using 'MJS_Controller_PathRouter' in any ancient Zend Framework version 0.6 and PHP 5.1.6. When I run this in a newer php version e.g. 5.2.x or 5.3.x, it is throwing this error:

Declaration of
  MJS_Controller_Router_PathRoute::__construct()
  must be compatible with that of
  Zend_Controller_Router_Route_Interface::__construct() in
  /opt/ezxwebadmin-versions/ezxwebadmin_2.11.5/Library/MJS/Controller/Router/PathRoute.php
  on line 34

I would like to remove this enhanced rewrite router and upgrade our application to use a newer Zend Framework version. Our web application doesn't use any of the classes provided by Zend and we are only utilizing the MVC architecture and rewrite functionality from Zend framework.
Now could any one advise which Zend Framework version would be best for us to upgrade to?

A: The error you are getting is actually a PHP strict coding standards error and should be fairly easy to fix. Just open up Zend_Controller_Router_Route_Interface and MJS_Controller_Router_PathRoute and compare the parameters for the __construct method. They need to be the same, so change your class to match the parameters in the interface.
Zend Framework requires PHP 5.2.4. ZF2 will require PHP 5.3+. PHP 5.1.6 is almost 5 years old so you really should be upgrading (or planning to). If you are using something like CentOS with really ancient PHP packages, you might want to consider switching to Zend Server community edition (which is free). This can be installed with Yum and will give you more recent versions of PHP.

A: You should take a close look at the Zend Framework Migration Notes starting at 0.8
Then look through the Zend Framework Download Archives and upgrade your framework version by version (follow the versions listed in the migration notes) to either get to a version that works with the PHP you have or (ideally) the latest version: 1.11.x


text:
Q: What if T is void in Generics? How to omit angle brackets I have a class of this type:
class A<TResult>
{
     public TResult foo();
}

But sometimes I need to use this class as a non generic class, ie the type TResult is void.
I can't instantiate the class in the following way:
var a = new A<void>();

Also, I'd rather not specify the type omitting the angle brackets:
var a = new A();

I don't want re-write the whole class because it does the same thing.

A: The void isn't a real type in C#, even there is a corresponding System.Void struct in FCL. I'm afraid you need a non-generic version here like this:
class A
{
   //non generic implementation
}

class A<T> : A
{
   //generic implementation
}

you can see in FCL there are System.Action/System.Action<T>, instead of System.Action<void>, as well as Task instead of Task<void>.
EDIT From CLI specification(ECMA-335):

The following kinds of type cannot be used as arguments in
instantiations (of generic types or methods):
Byref types (e.g., System.Generic.Collection.List`1<string&> is
invalid)
Value types that contain fields that can point into the CIL evaluation stack (e.g.,List<System.RuntimeArgumentHandle>)
void (e.g.,List<System.Void> is invalid)

A: As I posted in comment you can make it look good by inheriting from generic class:
class A:A<object>
{
}

This clearly hides the generic parameter but be aware that in my experience this is the wrong way to inherit classes and every time I did this I regretted it while my class got more complex.

A: void is simply not a type in C#, so you cannot have it as a type parameter. But nonetheless, there are times you want a functionnality as if it was one.
In this kind of case, you may make use of a simple replacement type, most likely a very small sruct, such as System.Reactive.Unit used in Reactive Extensions.

A: Another Option (which seems to be what falanwe was getting at) is to use the NullObject Design Pattern.
http://sourcemaking.com/design_patterns/null_object


text:
Q: GoKit and generating microservices install protoc error The error shows me this

*

*I already downloaded those packages.

*still show me the error Please install protoc first and than rerun the command

$ kit generate service notifactor -t grpc --dmw
time="2019-03-06T16:35:29+08:00" level=error msg="Please install protoc first and than rerun the command"
time="2019-03-06T16:35:29+08:00" level=info msg="Install proto3.\nhttps://github.com/google/protobuf/releases\nUpdate protoc Go bindings via\n> go get -u github.com/golang/protobuf/proto\n> go get -u github.com/golang/protobuf/protoc-gen-go\n\nSee also\nhttps://github.com/grpc/grpc-go/tree/master/examples"

A: From the go-kit source:

Using gRPC and go-kit together is very simple.
First, define your service using protobuf3. This is explained in gRPC documentation. See add.proto for an example. Make sure the proto definition
  matches your service's go-kit (interface) definition.
Next, get the protoc compiler.
You can download pre-compiled binaries from the protobuf release page. You will unzip a folder called protoc3 with a subdirectory bin containing an executable. Move that executable somewhere in your $PATH and you're good to go!

So just make sure protoc is in your PATH env var.


text:
Q: Why can't there be multi-state in DFA? My question is , can state3 also be named state2, or in general. Why can we name our states with same names.
For the expression ab+a*a
First state takes 'a'.
then it will either go state2/state3.

A: A finite state machine is defined to contain (among other things) a set of states, so it makes sense for each state to be uniquely identified. The naming of states has nothing whatsoever to do with the order they might be hit.
It's not uncommon for an FSM to involve a cycle. An example would be an FSM to accept a binary string with an even number of 0's, represented by the state table below:

Input --> | 0      | 1      |
\/--State |        |        |
----------|--------|--------|
state0    | state1 | state0 |
state1    | state0 | state1 |

States: {state0, state1}
Start state: state0
Accepting states: {state0}

In that case, the machine might move from state0 to state1 and back many times. The machine's complexity would explode to infinity if we had to have a new state every time.

A: you can name your states whatever you want so long as they are uniquely identifiable.
If the states aren't different, than they shouldn't be 2 separate states in the first place

your particular example doesn't have any or-ing, so your regex will never use a DFA that branches like that.
But let's say you had a regex like
a(bb | cc), which can match abb or acc
ab and ac are different states, and they have to be distinguished from one-another and the output from them leads to different conclusions.
If you were at ab and you got a c than you would have to go back to the start, but If you were in the state ac and got c than you would proceed to acc and finish.


text:
Q: java newbie question: richer java subprocesses I would like to spawn a subprocess Java Virtual Machine (through a Java API call) and communicate with it.
Maybe I'm just not searching for the right thing on Google, but I keep getting pointed back to Runtime.exec(), which is not what I want. I know I could connect standard input/output and use various serialization techniques, or use remote method invocation, but these seem to cumbersome/heavyweight. It seems like an API call could be more robust than attempting to call Runtime.exec("/usr/bin/java -cp [system.getclasspath] ...").
The purpose / motivation of this is that dynamically reloading classes with many dependencies seems somewhat tricky (several sites mention reading a .class file and passing it to [ClassLoader].defineClass, but this doesn't handle loading of dependent class files well). If I don't need much communication bandwidth or low latency, I think a new JVM instance would work fine; it's that communicating with it seems cumbersome. In any case this question isn't high priority; I'll probably go the straightforward route and see how I can load dependent class files (e.g. ones for inner classes).

A: As long as the classes you want to load are in a JAR file or a directory tree separate from your main app, using an URLClassLoader and running them in a separate Thread works fine. AFAIK all Java app servers work like this, so it's definitely a proven technique.

A: I would definitely recommend taking a look at the class loader mechanism used by the Tomcat servlet container - they seem to have exactly the same class loading problem and seem to have solved it very well.

A: If you go the communication route you should consider Java RMI.

A: ClassRunner (shown in the listing below) uses ProcessBuilder to run the main function of any available class in your classpath using the same class path and library path as the current JVM.  It will even clone the environment and the working directory of the current JVM.
Caveat: ClassRunner assumes that java is on the PATH of the current JVM.  You may want to put some logic around locating java or java.exe based on System.getProperty("java.home") :)
Listing of ClassRunner.java:
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ClassRunner
{
    private final Class<?> classToRun;

    public ClassRunner(Class<?> classToRun)
    {
        this.classToRun = classToRun;
    }

    public void run(String... args) throws Exception
    {
        String javaCommand = "java";
        String libraryPath = "-Djava.library.path=\"" + System.getProperty("java.library.path") + "\"";
        String classpath = "\"" + System.getProperty("java.class.path") + "\"";
        ProcessBuilder processBuilder = new ProcessBuilder(javaCommand,
                libraryPath,
                "-classpath", classpath,
                classToRun.getCanonicalName());
        processBuilder.redirectErrorStream();

        for (String arg : args) processBuilder.command().add(arg);
        Process process = processBuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) System.out.println(line);
        reader.close();
        process.waitFor();
    }

    public static void main(String[] args) throws Exception
    {
        new ClassRunner(Main.class).run("Hello");
    }
}

Listing of Main.java:
public class Main
{
    public static void main(String... args)
    {
        System.out.println("testing Main");
        for (String arg : args) System.out.println(arg);
    }
}


text:
Q: How to resize QTableWidget on Widget by dragging its corner I want to resize QTableWidget by dragging bottom right corner like following screen shot. How to do this? Here is my code.
code:
from PySide.QtGui import QApplication, QWidget, QTableWidget
week = ["mon", "tue", "wed", "thr", "fri", "sat", "sun"]
app = QApplication([])
mainWidget = QWidget()
tableWidget = QTableWidget(mainWidget)
tableWidget.setRowCount(3)
tableWidget.setColumnCount(7)
tableWidget.setHorizontalHeaderLabels(week)
mainWidget.show()

thanks.

A: One way to do this is using a QSizeGrip in a layout inside the table widget :
tableWidget->setWindowFlags(Qt::SubWindow);

QSizeGrip * sizeGrip = new QSizeGrip(tableWidget);

QGridLayout * layout = new QGridLayout(tableWidget);
layout->addWidget(sizeGrip, 0,0,1,1,Qt::AlignBottom | Qt::AlignRight);

The QSizeGrip class provides a resize handle for resizing top-level windows. When you set the widget flag Qt::SubWindow, then the user can resize it using the size grip.


text:
Q: Setting different context menu actions for each layer type with PyQGIS I want to set different actions(context menu) for vectors,rasters,etc .
class MyMenuProvider(QgsLayerTreeViewMenuProvider):
def __init__(self, view):
    QgsLayerTreeViewMenuProvider.__init__(self)
    self.view = view

  def createContextMenu(self):
    if not self.view.currentLayer():
      return None
    m = QMenu()
    m.addAction("Show Attribute Table", self.openAttributeTable)
    return m

  def openAttributeTable(self):
    #iface1.openFeatureForm(iface1.activeLayer(), feature, False)
    iface1.showAttributeTable(iface1.activeLayer())

then using it as
 view = iface1.layerTreeView()
 provider = MyMenuProvider(view)
 view.setMenuProvider(provider)

But this sets menu provider for all layers , I want to have different actions for different layers

A: You can always have a look at how QGIS does it to get an idea.
In your case, you can use a conditional expression to evaluate the layer type. If current layer is a vector you add certain actions, if not, you add others.
This is a basic example (see the createContextMenu function):
from qgis.PyQt.QtWidgets import QMenu
from qgis.core import QgsVectorLayer, QgsRasterLayer
from qgis.gui import QgsLayerTreeViewMenuProvider

class MyMenuProvider(QgsLayerTreeViewMenuProvider):

    def __init__(self, view):
        QgsLayerTreeViewMenuProvider.__init__(self)
        self.view = view
        self.defaultActions = view.defaultActions()

    def createContextMenu(self):
        if not self.view.currentLayer():
            return None
        m = QMenu()
        m.addAction("Open layer properties", self.openLayerProperties)
        m.addSeparator()

        if type(self.view.currentLayer()) == QgsVectorLayer:
            m.addAction("Show Feature Count", self.featureCount)
            m.addAction("Another vector-specific action", self.vectorAction)
        elif type(self.view.currentLayer()) == QgsRasterLayer:
            m.addAction("Zoom 100%", self.zoom100)
            m.addAction("Another raster-specific action", self.rasterAction)
        return m

    def openLayerProperties(self):
        iface.showLayerProperties(self.view.currentLayer())

    def featureCount(self):
        self.defaultActions.actionShowFeatureCount().trigger()

    def vectorAction(self):
        pass

    def zoom100(self):
        iface.actionZoomActualSize().trigger()

    def rasterAction(self):
        pass

view = iface.layerTreeView()
provider = MyMenuProvider(view)
view.setMenuProvider(provider)

Which produces:


text:
Q: Fetching bit field with mysql_query() Here's my code:
$query = "SELECT Username, EmailVerified, Blocked FROM user";
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);
print_r($row);

Field Username is string and EmailVerified and Blocked are of type bit. The line print_r($row) displays the value of Username field but not the other two. I tried mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_array() also, but same result.
Can't we fetch bit fields with mysql_query()?

A: I think you need to cast the BIT field to an integer ->
SELECT Username, CAST(EmailVerified AS unsigned integer) AS EmailV, CAST(Blocked AS unsigned integer) AS Block FROM User

A: Yes you can but they are retrieved as strings, and most likely end up being unprintable characters. You can get the values as numbers like so:
$query = "SELECT Username, EmailVerified, Blocked FROM user";
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);

$row['EmailVerified'] = ord( $row['EmailVerified'] );
$row['Blocked'] = ord( $row['Blocked'] );
print_r($row);

A: Instead of using BIT and converting it each time you need to use, you can use BOOL (which is already a TINYINT) and store TRUE (1) or FALSE (0) values.


text:
Q: Scala method syntax problem I am learning scala, and meet a little problem. I want to use the String method stripMargin as following. But I can not add parenthesis on this method. I remember that no-argument method's parenthesis is optional, so here why I can not add parenthesis ?
val str=""" hello world
    |" ANd soe"
    |" to world"""

println(str.stripMargin())  // won't compile
println(str.stripMargin)  // compiles successfully

A: If the method without parameters in define with (), then writing () is optional. If the method is defined without (), then adding () is not allowed (or, rather, is interpreted as if you were calling apply() on the returned result).
Good practice recommends that a method without side effects be defined without (), and to keep () both at definition site and call site when it has side effects.


text:
Q: Installing an npm package and using it in TSX files This is my first React/Typescript/ASP.NET Core app, so please forgive my ignorance. I am trying to install a new module from a GitHub repo and it is seeming more complicated than it should, but I can't seem to find a solution.
The problem: I have installed this project from GitHub into my web app (ASP.NET Core 2.0 React app using Typescript). I am now trying to import it, but am finding roadblocks at every turn.
It is similar to others, but the difference is that the others discuss their own components, while this is one from a repo belonging to someone else.
I can understand updating JS/JSX files with exports and such to accommodate issues such as this, but how can this be done when the module is being added from another project where updates may be regular?
Steps:
1. Install. npm install react-super-select --save
2. Add to webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';
const superSelect = require('react-super-select');

module.exports = (env) => {
    const isDevBuild = !(env && env.prod);
    return [{
        stats: { modules: false },
        entry: { 'main': './ClientApp/boot.tsx' },
        resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
        output: {
            path: path.join(__dirname, bundleOutputDir),
            filename: '[name].js',
            publicPath: 'dist/'
        },
        module: {
            rules: [
                { test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
                { test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader?minimize' }) },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [
            new CheckerPlugin(),
            new superSelect(),
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new ExtractTextPlugin('site.css')
        ])
    }];
};

*Import into my .tsx file:
import * as React from 'react';
import { RouteComponentProps, Redirect } from 'react-router';
import { ChangeEvent, Props, Key } from 'react';
import { formatDateInt, formatDatePeriod } from '../Dates';
import 'isomorphic-fetch';
import * as ReactSuperSelect from 'react-super-select';
This is where the errors start. With this setup, I get the following error:
TS7016  (TS) Could not find a declaration file for module 'react-super-select'. 'C:/AzTech/AzTechWebPortal/trunk/AzTechWebPortal/AzTechWebPortal/node_modules/react-super-select/lib/react-super-select.js' implicitly has an 'any' type.
  Try `npm install @types/react-super-select` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-super-select';

There is no @types/react-super-select and while looking into the declaration file error I found that the import can be changed to:
const ReactSuperSelect: any = require('react-super-select');

This raises no errors and I am able to add  to the below component:
class Upload_FieldMapping extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = { items: [], loading: true };
        //PUT AN IF HERE TO HANDLE THIS BEING A SCHEDULE IMPORT
        fetch('api/Upload/FieldMappings')
            .then(response => response.json() as Promise<string[]>)
            .then(data => {
                this.setState({ items: data, loading: false });
            }).then(data => console.log(data));

    }

    public render() {
        type CostMap_Import = typeof CostMap_Import;
        type SchedMap_Import = typeof SchedMap_Import;
        let contents = this.state.loading
            ?
Loading...

            : Upload_FieldMapping.renderMappingsTable(this.state.items, this.props.selected === rdEV || 'undefined' ? CostMap_Import : SchedMap_Import);

        return
{contents}

    }

    private static renderMappingsTable(values: string[], fMaps: any) {
        return

                <ReactSuperSelect />

                {Object.keys(fMaps).map(function (i: Key) {
                    return
{i}

                })}

    }
}

*Run. Here's is what I am unable to get past. When running the app, the Configure method in Startup.cs complains:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// global policy - assign here or on each controller
app.UseCors("CorsPolicy");

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
    {
        HotModuleReplacement = true,
        ReactHotModuleReplacement = true
    });
}

The error:
System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.AspNetCore.Builder.WebpackDevMiddleware.UseWebpackDevMiddleware(IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options)
   at AzTechWebPortal.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\Startup.cs:line 47

Inner Exception 1:
NodeInvocationException: Cannot find module 'classnames'
Error: Cannot find module 'classnames'
    at Function.Module._resolveFilename (module.js:538:15)
    at Function.Module._load (module.js:468:25)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\node_modules\react-super-select\lib\react-super-select.js:1:2323)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)

If I need to create the declaration file, so be it. But will this always be the case for projects without a @types install?
For my sake and for others, what is the simplest way to get this done (that doesn't forego proper conventions)?
UPDATE
Per the comment, I installed classnames & lodash:
npm install classnames --save
npm install lodash --save

And the error has changed to the following:
System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.AspNetCore.Builder.WebpackDevMiddleware.UseWebpackDevMiddleware(IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options)
   at AzTechWebPortal.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\Startup.cs:line 47

Inner Exception 1:
NodeInvocationException: Cannot read property 'controlId' of undefined
TypeError: Cannot read property 'controlId' of undefined
    at new ReactSuperSelect (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\node_modules\react-super-select\lib\react-super-select.js:1:4130)
    at module.exports (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\webpack.config.js:28:13)
    at createWebpackDevServer (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\node_modules\aspnet-webpack\WebpackDevMiddleware.js:194:31)
    at createWebpackDevServer (C:\Users\EL-C\AppData\Local\Temp\emxsocle.wn2:74:50)
    at C:\Users\EL-C\AppData\Local\Temp\0dd3jvzv.ill:114:19
    at IncomingMessage.<anonymous> (C:\Users\EL-C\AppData\Local\Temp\0dd3jvzv.ill:133:38)
    at emitNone (events.js:106:13)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1055:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)

A: The error is saying that you're missing the classnames npm modue. react-super-select has it, along with lodash, in its peerDepedencies so it's not installed automatically. Try installing them manually.
Also I don't think you need to add superSelect to webpack.config.js.


text:
Q: cut append variable bash How can I append a string variable which I got through cut with next variable? In the file application.properties, I have value: myValue=/tmp/user/
I tried:
file=myfile.properties
path=$(cat application.properties | grep myValue=)
path2=$(echo $path | cut -d'=' -f 2- )
pathToFile=$path2$file

But output is only: myfile.properties. I need /tmp/user/myfile.properties
Thank you for your help.

A: Don't use cut for this at all: The shell's built-in string manipulation can do this trimming for you. (And don't use cat: It's more efficient to have grep read straight from the file than to have it reading from a separate process that then writes to a FIFO).
file=myfile.properies
path=$(grep myValue= <application.properties)
pathToFile=${path#*=}${file}


text: Q: Comparability of the dependent variable measure over time I need to estimate the effect of several educational policies that were implemented over 20 years on schools performance. School performance is measured as percentage of pupils who pass the exam at the end of compulsory schooling. However the exam has been changed at several points over time. Is there a way to take that into account in my regression analysis? In the estimated equation I am also including year dummies.


text:
Q: Legendre Transformation of Landau Free Energy I am trying to get an intuition for the Legendre Transformation of a generic Landau free energy, e.g. for the Ising model with magnetization $m$ given by $$F(m) = \frac{a}{2} m^2 + \frac{b}{4} m^4 + \dots$$ Let's assume we have $a> 0, b> 0$, i.e. we are in the paramagnetic phase.
I now want to Legendre transform to $F(h)$ where $F(h) = F(m) - h m$ with $$h = \frac{\partial F(m)}{\partial m} = a m + b m^3 + \dots .$$ I am now inverting the latter equation order-by-order to get $$m = h/a -  b/a (h/a)^3 + \dots$$
Notice the funny minus sign. Plugging everything into $F(h)$, I get $$F(h) = - \frac{h^2}{2a} + \frac{b h^4}{4 a^2}.$$ I am not sure I understand why the coefficients have different signs. I am thinking that $F(m)$ is concave for all $m$, and so should the Legendre transform (or convex, depending on sign conventions). But it looks like $F(h)$ is neither concave or convex in general, but rather has two minima? Why would that be? Is my math wrong here?
The sign of the first term makes sense to me since from $$m = - \partial F(h) / \partial h = h /a - b h^3/a^4$$ we see that the magnetization is proportional to the magnetic field (to first order) which makes sense. But why does the coefficient of $h^3$ have a negative sign? My guess that there are even higher order terms which will have different signs to correct for this but I would still like to understand what is going on.

A: The problem comes from the fact that the computation of $m(h)$ you are doing  is only valid for small values of h. This is clear from the fact that for $h\gg 1$, one has that $m\approx(h/b)^{1/3}$, which is completely different from what comes out of your small $h$ expansion.
A picture being worth 1000 words, here are both your approximate solution (in green) and the true solution (in black, obtained by solving the third degree polynomial equation), both for $a=b=1$:

Seeing this, it is not surprising that injecting your expression into the formula for $F(h)$ yields a function that has bad properties: it only coincides with the true function for small values of $h$!
Again, here's a picture: in green, the convex function $F(m)$, in blue the true function $F(h)$ and in orange the function you obtained for $F(h)$:

As you can see, the true function is concave, as it should be (the Legendre transform of a convex function is always concave with your sign conventions).


text:
Q: winforms - How to create new menu on button click in C# Here is my problem:
I am developing a windows form application.
I am make a simple word process, and im already make open, save and save as menu.
This is my code:
 private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Rich Text Format (*.rtf)|*.rtf";
            if(openFileDialog.ShowDialog() == DialogResult.OK)
            {
                rtbDocument.LoadFile(openFileDialog.FileName, RichTextBoxStreamType.RichText);

                saveFileDialog.FileName = openFileDialog.FileName;
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(saveFileDialog.FileName == "")
            {
                saveFileDialog.FileName = "";
                saveFileDialog.Filter = "Rich Text Format (*.rtf)|*.rtf";
                if(saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    rtbDocument.SaveFile(saveFileDialog.FileName, RichTextBoxStreamType.RichText);
                }
            }

            else
            {
                rtbDocument.SaveFile(saveFileDialog.FileName, RichTextBoxStreamType.RichText);
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            string filename = "";

            // To filter files from SaveFileDialog
            saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf";
            /*saveDlg.DefaultExt = "*.rtf";*/
            /*saveDlg.FilterIndex = 1;*/
            saveDlg.Title = "Save the contents";

            DialogResult retval = saveDlg.ShowDialog();
            if (retval == DialogResult.OK)
                filename = saveDlg.FileName;
            else
                return;

            /*RichTextBoxStreamType stream_type;
            if (saveDlg.FilterIndex == 2)
                stream_type = RichTextBoxStreamType.PlainText;
            else
                stream_type = RichTextBoxStreamType.RichText;*/

            rtbDocument.SaveFile(filename);
            MessageBox.Show("File Saved");
        }

Im already trying this code:
 private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rtbDocument.Text = "";
        }

But this code only make rich textbox empty.
The problem is i want when new menu button is clicked the rich textbox will be empty as well as when doing Save (not Save As) it will reopen a dialog box to give it a name and choose a location file storage.
Can anyone help in this, and give me some sample code?

A: Just also set saveFileDialog.FileName back to a blank string as that is what you check for in the save routine:
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
    rtbDocument.Text = "";
    saveFileDialog.FileName = "";
}


text:
Q: Wifi card limits download speed before router restart I'm having weird problem, when laptop boots, download speed on it is limited to just 0,6MB/s. Once router gets restarted and laptop is on, speed returns to normal. I'm guessing that problem must be in card/os as I'm not having problems with any other device. I'm not really able to currently connect laptop to network via cable, so WIFI is only option. Laptop is set to performance mode and plugged in to power outlet (to not drop performance).
WIFI card: Realtek RTL8821CE 802.11ac PCIe Adapter
OS: Windows 11 (problem was exisiting on Win10 before update)
Router: Alcatel HUB71
I've checked many things on internet but didn't find a solution. Any suggestions?


text:
Q: Android getFileDir Location In android, I am trying to save the XML file locally.
I am using the below syntax to do it
File myFile = new File(getFilesDir()+"/loginUser.xml");
myFile.createNewFile();

It is working fine in emulator as well as device.
Now my question is what is the path this getFilesDir() in System(in Emulator)

A: See http://developer.android.com/guide/topics/data/data-storage.html#filesInternal.
It can depend on the system but generally files are stored somewhere in /data/data.. in separate directories for each app.


text:
Q: Access denied for user 'tt-rss'@'localhost' after installing tt-rss Just installed Tiny Tiny RSS. Accessing http://localhost/tt-rss from the browser brings me the following error:

Unable to connect to database (as tt-rss to , database ttrss): Access
  denied for user 'tt-rss'@'localhost' (using password: YES)

How can I solve the problem?

A: I got this error after installing tt-rss with all the default settings (connecting to the database using unix socket, with "ident" identification).  I was able to fix it by doing the following:

*

*sudo dpkg-reconfigure tt-rss

*During the ncurses install process I selected tcp-ip as the connection method rather than socket and specified "localhost" as the server name.

*Then I told the installer to use password authentication rather than ident
...and it worked!  I am now able to reach the tt-rss web interface.
I looked really closely to the installer output of one of my installation attempts to use ident and saw an error that it is unable to create a local user account, so that's probably why the default options didn't work...
HTH!


text:
Q: Print my sa password I've logged in to my sqlserver with a registred "sa" sql account and
I want to print (not change) my current password. I can change it but I have an application using the current password.
I have done

select * from sys.sql_logins where name ='sa'

but it gives me a hashed password
If it is impossible, how to export my sa connection to another sql server instance?

A:
WARNING - HORRIFIC PRACTICE
Change your application to use a user OTHER THAN sa, and preferably without sysadmin permissions.  Usually database level db_datareader, db_datawriter, and MAYBE db_ddladmin is enough, though it may need a GRANT EXECUTE on the database.
If you can't, then argue some more.  In writing.
If you lose again, go change the sa password to a long, strong, cryptographically random password in concert with the application being updated with a new password.
And make sure that instance is used ONLY for that app, so the risk is limited to that one area.

Recovering the current sa password
First, you are a sysadmin, aren't you?  You should already know the sa password!  If you lost twice, just change the sa password on the other instance to that same one (or, better, change them both to something better), through ALTER LOGIN (below) or the GUI.
Second, realize that EVERY USER OF THAT APPLICATION CAN GET YOUR SA PASSWORD - they can almost certainly extract it right out of the application with a hex editor, looking for the string pwd or pass (either UCS-2 "Unicode" or ASCII).
You have the application, right?  Consult your local security admins, and see if you're allowed to open it up in a hex editor and find the sa password yourself.

Moving the sa password
In general, if you want to move the same password around, you can use
ALTER LOGIN sa PASSWORD = 'hash string' HASHED
to change it.
Do not do this regularly - if someone gets hashes of all your passwords (just like you're getting them), it's better that each one have a unique salt, so the attacker has to spend more work testing against many salts before they start finding passwords.
Do not do this from lower protection to higher protection - SQL Server 2005, 2008, and 2008R2 all use the same algorithm.  SQL Server 2012 and 2014 use the same.  Don't move a 2005/8/8R2 hash to 2012/14; it's significantly weaker (and 2012/14 password hashing is pathetic to begin with).
Thus, you're better off changing the password to what you want in cleartext, so SQL Server generates a new salt.  The password hash is incredibly weak, a single iteration of SHA-1 or SHA-512, so it needs all the help it can get.


text:
Q: button 2 text transition It is possible to have 2 text's on a wpf Button?
Button 1

 <Button>
   <StackPanel Orientation="Vertical">
       <TextBlock FontSize="8" HorizontalAlignment="Right">Secondary</TextBlock>
        <TextBlock>Primary</TextBlock>
   </StackPanel>
</Button>

I have another button
Button2
<Button>Toggle Text</Button>

When this button click's I want to change (toggle) the text  on first button.
Is this possible with WPF ?
 private void Btn_Click(object sender, RoutedEventArgs e)
        {
            var temp = Primary.Text;

            Primary.Text = Secondary.Text;
            Secondary.Text = temp;

        }

A: you can use style and trigger together
<Button HorizontalAlignment="Left" Height="98" Margin="119,83,0,0" VerticalAlignment="Top" Width="327" x:Name="B">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <Grid Width="300" Height="50">
                                <TextBlock Text="secondary" HorizontalAlignment="Right" VerticalAlignment="Top"/>
                                <TextBlock Text="Primary" HorizontalAlignment="Left" VerticalAlignment="Bottom" FontSize="22" />
                            </Grid>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Switch,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Value="true">
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <Grid Width="300" Height="50">
                                        <TextBlock Text="primary" HorizontalAlignment="Right" VerticalAlignment="Top"/>
                                        <TextBlock Text="secondary" HorizontalAlignment="Left" VerticalAlignment="Bottom" FontSize="22" />
                                    </Grid>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>

        </Button.Style>
    </Button>

<Button Content="TestBuuton" HorizontalAlignment="Left" Height="66" Margin="336,330,0,0" VerticalAlignment="Top" Width="222" Command="{Binding TestCommand}" />

and in you viewview model you can switch the value like this
    RelayCommand test;
    public RelayCommand TestCommand
    {
        get
        {
            if (test == null)
            {
                test = new RelayCommand(p => execute(p));
            }
            return test;
        }
    }

void execute(object parameter)
    {
        if (Switch)
        {
            Switch = false;
        }
        else
        {
            Switch = true;
        }
        RaisePropertyChanged("Switch");
    }

 after click

i hope this is you are looking for

A: XAML Code:
<Grid>
    <Button x:Name="MainButton" Height="70" Width="213" Click="MainButton_Click" >
        <Grid Height="{Binding ElementName=MainButton, Path=ActualHeight}" Width="{Binding ElementName=MainButton, Path=ActualWidth}">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="2*"/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="TextOne" Grid.Row="0" HorizontalAlignment="Right" Padding="10 0">Primary</TextBlock>
            <TextBlock x:Name="TextTwo" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">Secondary</TextBlock>
        </Grid>
    </Button>
</Grid>

C# Code-behind:
 public MainWindow()
    {
        InitializeComponent();
    }

    private void MainButton_Click(object sender, RoutedEventArgs e)
    {
        string aux = TextOne.Text;

        TextOne.Text = TextTwo.Text;
        TextTwo.Text = aux;
    }

In the above example i used an ugly button, but its up to you to make it more beautifull. It is also NOT following MVVM pattern. When you feel ready to refactor it to MVVM, just use a Command inspite of the Click event, take off the "X:Names" and take the button texts from variables within your code.
Hope that helps.


text:
Q: How to pass data in conditional unwind segue? I try to build an rss reader. On the "adding feed" page, if I tap the "add" button, I hope to check if the feed is successfully added. If it is added, then trigger the unwind segue, and back to the main page. If it is not added, stay in the current page.
I know I can build an IBAction on the "add" button, and check if the feed is added. However there are two requirements I need to meet in order to add a feed.
First, after I parse the url, I need to know if the parse results can generate a feed. To parse the url, I need to use the method defined in the mainViewController.
Second, I need to check if the feed already exists. If this feed already exists, don't add it. To check this, I need to get the feed data from mainViewController.
Currently I use prepareForSegue to pass the data from main viewController to this view. But for the conditional unwind segue, I don't know how to pass the data and check if the feed already exists. Because prepareForSegue is used only when the segue is going to be triggered. If the segue is not triggered, I can't check the condition.
Besides through segue, is there any other ways to pass data from other view?
I don't know objective-C, so it would be better if you can give me some solutions in swift. :)

A: Like Schemetrical said, using a delegate is an easy way to access the methods in your MainViewController.
Since you tagged this as Swift, I'll also give you a small example of a delegate in Swift.
First you create a protocol:
protocol NameOfDelegate: class {     // ":class" isn't mandatory, but it is when you want to set the delegate property to weak
    func someFunction() -> String    // this function has to be implemented in your MainViewController so it can access the properties and other methods in there
}

In your MainViewController you have to add:
class MainViewController: UIViewController, NameOfDelegate {

    // your code

    @IBAction func button(sender: UIButton) {
        performSegueWithIdentifier("toOtherViewSegue", sender: self)
    }

    fun someFunction() -> String {
        // access the other methods and return it
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toOtherViewSegue" {
            let destination = segue.destinationViewController as! OtherViewController
            destination.delegate = self
        }
    }
}

And the last step, you'll have to add a property of the delegate, so you can "talk" to it. Personally I imagine this property to be a gate of some sort, between the two view controllers so they can talk to each other.
class OtherViewController: UIViewController {

    weak var delegate: NameOfDelegate?

    @IBAction func button(sender: UIButton) {
        if delegate != nil {
            let someString = delegate.someFunction()
        }
    }
}

I assumed you used a segue to access your other ViewController since you mentioned it in your post. This way, you can just "talk" to your MainViewController.
EDIT:
As for the unwind. This also can be done through a segue.

*

*add: @IBAction func unwindToConfigMenu(sender: UIStoryboardSegue) { } to your MainViewController.

*In your storyboard there are 3 icons at the top of your OtherViewController. Click on the round yellow with a square inside to make sure the ViewController is selected and not some elements inside.

*Control drag (or right mouse drag) from the same round yellow with a square inside to the most right red square icon. Doing so pops up a menu where you can select the unwind segue.

*Click on the new segue you just created. Give it an identifier like "backToMain"

*Add something similar as the code below to OtherViewController
It appears i can't post any code anymore? :o will add it later.

A: You can always use delegates.
Set up a delegate in your add feed page and get mainViewController to conform to the delegate. Add a delegate method (- (BOOL)canGenerateFeed:(NSURL *)url) and a delegate property (@property (weak, nonatomic) id <AddFeedControllerDelegate> delegate).
When your add feed page calls [self.delegate canGenerateFeed:url] and your mainViewController conforms to the delegate, the method in mainViewController is called (that should reply BOOL as stated in the method declaration). Then you can reply YES or NO accordingly, which will be sent back through to the add feed page.

A: - (UIViewController*)viewControllerForStoryboardName:(NSString*)storyboardName class:(id)class
{
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    NSString* className = nil;

    if ([class isKindOfClass:[NSString class]])
        className = [NSString stringWithFormat:@"%@", class];
    else
        className = [NSString stringWithFormat:@"%s", class_getName([class class])];

    UIViewController* viewController = [storyboard instantiateViewControllerWithIdentifier:[NSString stringWithFormat:@"%@", className]];
    return viewController;
}

// get the view controller
    ViewController* viewController = (ViewController*)[self viewControllerForStoryboardName:@"MyStoryboard" class:[OtherViewController class]];
    // Pass data here
    viewController.data = myData;

// or you can push it
    [self.navigationController pushViewController:viewController animated:YES];


text:
Q: Can't forward port 443 on C1100T wifi router I have the same problem as outlined in this question:
How to forward port 443 on C1100T wifi router
After making the changes outlined in the answer, I still get that same error message when trying to forward port 443.


text:
Q: Cannot deserialize the JSON object into 'MongoDB.Bson.BsonDocument' type So I have a JSON file that I want to convert to an object that contains a BsonDocument but I get an error.
My JSON file is:
{
  "words": {
    "wordList": {
      "d": "duck",
      "t": "truck",
      "l": "luck",
      "s": "suck"
    }
  }
}

And I want to be able to deserialize it by doing this:
var contentTest = await File.ReadAllTextAsync("Data/TestConfig.json");
var testresult = JsonConvert.DeserializeObject<TestEntity>(contentTest);

But I get the following:

Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'MongoDB.Bson.BsonDocument' because the type requires a JSON
array (e.g. [1,2,3]) to deserialize correctly. To fix this error
either change the JSON to a JSON array (e.g. [1,2,3]) or change the
deserialized type so that it is a normal .NET type (e.g. not a
primitive type like integer, not a collection type like an array or
List) that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to
deserialize from a JSON object. Path 'words.wordList.d', line 4,
position 10.

My class TestEntity looks like this:
public class TestEntity
{
    public IDictionary<string, BsonDocument> Words { get; set; }
}

How can I modify my JSON file in order to be able to deserialize those objects into a BsonDocument?

A: You should use the serializer/deserializer from MongoDB.Bson library instead of Newtonsoft.Json library.
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;

var testresult = BsonSerializer.Deserialize<TestEntity>(contentTest);

public class TestEntity
{
    [BsonElement("words")]
    public IDictionary<string, BsonDocument> Words { get; set; }
}

Demo @ .NET Fiddle


text:
Q: Can you set Page Output Cache by an Individual user? I have a master page which has a rather simple menu system.  The menu items available are based on the logged on user.  However, the database calls to determine this logic are over a second which is probably too long for my liking.
Is there a way to wrap the Menu into a UserControl but along with having a duration to refresh but obviously also the output cache should be on a per user basis?
I know the other solution is to cache the data for each user and then rebuild but I thought the more efficent place to start would be Page Output cache.
Please note also this application does not user Session state.

A: You can look at VaryByParam method of Page Output Caching.
When your user logs in add a query string to your page something like page.aspx?uid=x123
then add the following to your page:
<%@ OutputCache Duration="10800" VaryByParam="uid" %>

This will make it per user cache.
Do remember:
Even if you put your user as a query string, still do the validation, that its the same user who logged in, to avoid users peeking into each other's view by simply changing the query string.


text:
Q: I want to know if my validation script is secure enough against user error or attack I have this as my registration validation code. I want to follow the pattern i used for my javascript on the server side. All i want to know is if my script is enough to counter any user error or attack. Thanks
function regvalidate() {
    var gender = $j("#gen").val();
    var surname = $j("#nsn").val();
    var firstname = $j("#nfn").val();
    var othername = $j("#notn").val();
    var username = $j("#un").val();
    var phone = $j("#tel").val();
    var password = $j("#pw").val();
    var rpassword = $j("#rpw").val();
    var sorigin = $j("#sor").val();
    var age = $j("#age").val();
    var churchname = $j("#cname").val();
    var churchname2 = churchname.replace(/[`~!@#$%^&*()_| \-=?;:'",.<>\{\}\[\]\\\/ ]/gi,'');
    var schoolname = $j("#sn").val();
    var schoolname2 = schoolname.replace(/[`~!@#$%^&*()_| \-=?;:'",.<>\{\}\[\]\\\/ ]/gi,'');
    var secquestion = $j("#sq").val();
    var secanswer = $j("#sqa").val();
    var secanswer2 = secanswer.replace(/\s/g,"");
    var originalcaptcha = $j("#ocaptcha").text();
    var usercaptcha = $j("#ucaptcha").val();
    var chkb = $j("#chkb").prop("checked");

    if (gender!='female' && gender!='male') {
        alert("please select a valid gender");
    } else if (!surname.match(/^[a-zA-Z]{2,50}$/)) {
        alert("please enter a valid surname. Alphabets only and no space.");
    } else if (!firstname.match(/^[a-zA-Z]{2,50}$/)) {
        alert("please enter a valid firstname. Alphabets only and no space.");
    } else if (!othername.match(/^[a-zA-Z]{2,50}$/)) {
        alert("please enter a valid other name. Alphabets only and no space.");
    } else if (!username.match(/^[a-zA-Z0-9]{4,20}$/)) {
        alert("enter a valid username please. Alphanumeric supported only. Min: 4 Max: 20");
    } else if (!password.match(/^[a-zA-Z0-9]{5,20}$/)) {
        alert("password should only contain alphabets or numbers. Min: 5 Max: 20");
    } else if (pw!=rpassword) {
        alert("password is not the same");
    } else if (!phone.match(/^[0-9]{11,13}$/)) {
        alert("please enter a valid phone number");
    } else if (!sorigin.match(/^[a-zA-Z.]{3,15}$/)||sorigin.length<3) {
        alert("select your state");
    } else if (!age.match(/^[0-9]{2}$/)) {
        alert("input your correct age. Atleast Ten years of age");
    } else if (!churchname.match(/^[a-zA-Z0-9',.\-_\(\) ]{13,100}$/)) {
        alert("enter a valid church name. Do not abbreviate!");
    } else if (churchname.match(/(.)\1{3,}/)) {
        alert("enter a valid church name");
    } else if (churchname2.length<13) {
        alert("church name too short");
    } else if (!schoolname.match(/^[a-zA-Z0-9',.\-_\(\) ]{13,100}$/)) {
        alert("enter a valid school name. Do not abbreviate!");
    } else if (schoolname2.length<13) {
        alert("school name too short");
    } else if (schoolname.match(/(.)\1{3,}/)) {
        alert("enter a valid school name");
    } else {
        $j("#reghloading").show();
        $j.post("processorthis.php",$j("#regform").serialize(),function(data) {
            $j(".regresult").html(data);
        }).done(function() {
            $j("#reghloading").hide();
        }).fail(function() {
            alert("unable to process your request now. Check back later");
        });
    };
return false;
}


text:
Q: how to resolve this error: bar() missing 1 required positional argument: 'height' I want to make a graph order frequency of each city. For this, I am trying to pass cities name on x-axis and their number on y-axis. I keep facing this error  TypeError: bar() missing 1 required positional argument: 'height' . Here is the code:
order_status = df.Order_Status.value_counts()

#making separate column for unique cities
unique_city = df.City.value_counts()

plt.bar(x=unique_city.index, y=unique_city.values)

Any help would be highly appreciated.

A: Use:
unique_city.plot.bar()

Or like @ commented:

Replace y with height matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html


text:
Q: How to initialize an array of structs in C I can not see why my code doesn't work
#include <stdio.h>
#include <stdlib.h>

typedef struct date{
    int month, day, year;
} Date;

typedef struct person{
    char name[32];
    Date date;
}Person;

int main()
{
    Person presidents[4];
    presidents[0] = {"George Washington", {30, 4, 1789}};
    presidents[1] = {"Thomas Jefferson", {4, 3, 1801}};
    presidents[2] = {"Abraham Lincoln", {4, 3, 1861}};
    presidents[3] = {"Theodore Roosevelt", {14, 8, 1901}};

    return 0;
}

This is the compiler's output:
>||=== Build: Debug in MyProject (compiler: GNU GCC Compiler) ===|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c||In function 'main':|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|16|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|17|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|18|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|19|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|15|warning: variable 'presidents' set but not used [-Wunused-but-set-variable]|
>||=== Build failed: 4 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

A: Try:
Person presidents[] = {
    {"George Washington", {30, 4, 1789}},
    {"Thomas Jefferson", {4, 3, 1801}},
    {"Abraham Lincoln", {4, 3, 1861}},
    {"Theodore Roosevelt", {14, 8, 1901}}
};

The initialization is always in the form
type var = init_val;

and the code above shows how to initalize an array of structs. Please note how you don't need to specify the number of elements of the presidents array, as the compiler will obtain it from the number of elements in the initializer.

A: As an extension to @RobertoCaboni's answer, since C99 you can also use compound literals:
Person presidents[4];
presidents[0] = (Person){"George Washington", {30, 4, 1789}};
presidents[1] = (Person){"Thomas Jefferson", {4, 3, 1801}};
presidents[2] = (Person){"Abraham Lincoln", {4, 3, 1861}};
presidents[3] = (Person){"Theodore Roosevelt", {14, 8, 1901}};


text:
Q: Compare Table column with JSON object and update another column in HTML This is the first time I'm using HTML and Javascript to create a Dashboard. This Dashboard contains a HTML table which contains server name,server desc and time UP,warning critical columns.
From Nagios JSON query generator, I will generate a Availability report URL which returns the JSON value. Now I need to compare the Service Desc in table column and update the the remaining columns by fetching value from the JSON output. How to achieve it.
HTML :

                            Service Name
                            Service Desc
                            Time OK %
                            Time Warning %
                            Time Critical %
                        </tr

                    jenkinsserver
                    Jenkins PROD GUI
                    0.00
                    0.00
                    0.00

                    nexusserver
                    nexus GUI
                    0.00
                    0.00
                    0.00

                    sonarserver
                    sonrqube GUI
                    0.00
                    0.00
                    0.00

                    CLEARCASE

                    clearcasewebserver
                    clearcase web
                    0.00
                    0.00
                    0.00

                    clearcase server
                    check clearcase status
                    0.00
                    0.00
                    0.00

Javascript:
function make_base_auth(user, password) {
            var tok = user + ':' + password;
            var hash = btoa(tok);
            return 'Basic ' + hash;
}
$(document).ready(function(){

var end1 =  Math.floor((new Date).getTime()/1000);
var start1 = Math.floor(time.setDate(time.getDate() - 1)/1000);
console.log(end1);
console.log(start1);

servicereport = " http://xx.xx.xx/nagios/cgi-bin/archivejson.cgi?query=availability&availabilityobjecttype=servicegroups&hostgroup=ALM&servicegroup=ALM+Tools&assumedinitialhoststate=up&assumedinitialservicestate=ok&starttime=" + start1 + "&endtime=" + end1;
$.support.cors = true;

 $.ajax({
 type: "GET",
 url: servicereport,
 crossDomain: true,
 async: false,
 beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization',
                        make_base_auth("nagiosadmin", "nagiosadmin"));
                },

 dataType: 'json',     //data format
 success: servicedisplay
 });
function servicedisplay(series) {
  // 1. remove all existing rows

    $('#service_table tbody').empty();

    var lent = series.data.servicegroup.services;
    var aa = lent.length;
    var sm = 0;
    var avg = 0;
    for (var i=0; i<aa; i++) {
        var dataO=series.data.servicegroup.services[i].time_ok;
        var dataW=series.data.servicegroup.services[i].time_warning;
        var dataC=series.data.servicegroup.services[i].time_critical;
        var dataA=(dataO/(dataO + dataW + dataC))*100;
        sm +=dataA;
        }
        avg = sm/aa;
        if ( avg < 100 ) {
        $('#almserv').css('background-color','red');
    } else {
        $('#almserv').css('background-color','green');
        }
    $('#servnum').text(parseFloat(avg).toFixed(2));

    $.each(series.data.servicegroup.services, function (index, serv) {

  $('
').append(
            $('').text(parseFloat((serv.time_ok/(serv.time_ok + serv.time_warning + serv.time_critical)*100)).toFixed(2)),
            $('').text(parseFloat((serv.time_warning/(serv.time_ok + serv.time_warning + serv.time_critical)*100)).toFixed(2)),
            $('').text(parseFloat((serv.time_critical/(serv.time_ok + serv.time_warning + serv.time_critical)*100)).toFixed(2)),
        ).appendTo('#service_table');
    });

A: My idea could be something like this:

                        Service Name
                        Service Desc
                        Time OK %
                        Time Warning %
                        Time Critical %
                    </tr

                jenkinsserver
                Jenkins PROD GUI

0.00

0.00

0.00

                nexusserver
                nexus GUI

0.00

0.00

0.00

                sonarserver
                sonrqube GUI

0.00

0.00

0.00

                CLEARCASE

                clearcasewebserver
                clearcase web

0.00

0.00

0.00

                clearcase server
                check clearcase status

0.00

0.00

0.00

Then in your script, you could create a Switch Statement and do the compare there like:
for (var i=0; i<aa; i++) {
  switch(series.data.servicegroup.services[i].VariableWithCol2Content){
   case "Jenkins PROD GUI": //code for the changes
     $("#col3JPG").text(series.data.servicegroup.services[i].time_ok);
     $("#col4JPG").text(series.data.servicegroup.services[i].time_warning);
     $("#col5JPG").text(series.data.servicegroup.services[i].time_critical);
     //add all require code to update the row
   break;
   case "nexus GUI": //code for the changes
     $("#col3NG").text(series.data.servicegroup.services[i].time_ok);
     $("#col4NG").text(series.data.servicegroup.services[i].time_warning);
     $("#col5NG").text(series.data.servicegroup.services[i].time_critical);
     //add all require code to update the row
   break;
     //and so on with all of them...


text:
Q: What is the sigma algebra of cylindrical sets? This is a basic question but still, let $C$ be the space of real-valued continuous functions $f$ on $[0,t]$. Then a cylindrical subset of $C$ is defined as a set of the form
$$
S = \{\, f\in C; \,(f(t_1),\dots\,f(t_n))\in B\}
$$
where $B\in \mathcal{B}^n$ and $0<t_1<\dots<t_n<t$. So, take
$$
S_1 = \{\, f\in C;\, f(t_1) \in B_1 \}
$$
$$
S_2 = \{\, g\in C;\, g(t_2) \in B_2 \}
$$
How is the union of these two sets a cylindrical subset of C as defined above? The union of the sets of functions $f$ and $g$ such that $f(t_1)$ is in some interval and $g(t_2)$ is in some other interval, isn't it the set of functions $h$ such that either $h(t_1)$ or $h(t_2)$ belong to the said intervals.
Or is it that the sum of the sets $S_1$ and $S_2$ is defined as the cylindrical set that corresponds to the Borel set $(B_1\times\mathbb{R})\, \cup \,(\mathbb{R}\times B_2)$?
(Apologies for any lack of rigor)

A: Be careful: the (or maybe "a") family of cylinder sets need not to be a priori closed under unions! You gave the right definition of cylinder set, but note that  the family:
$$ \{ C_{t_1 \dots t_n} (B) : B \in (\mathcal{B})^n\, \ n \in \mathbb{N}, \ t_1 \dots t_n \in [0,T] \} $$
is just a $\pi$-system (i.e, it is closed under finite intersections), not an algebra or even a $\sigma$-algebra. If you want a "closed-under union" property you must consider the $\sigma$-algebra generated by all cylinder sets. Here's an idea: let $\mathcal{F}_{t_1 \dots t_n}$ be the $\sigma$-algebra generated by the above family and define:
$$ \overline{\mathcal{F}} = \bigcup_{n=1}^{+\infty} \bigcup_{t_i \in [0,T], i \le n} \mathcal{F_{t_1 \dots t_n}}. $$
Then $ \overline{\mathcal{F}}$ is actually an algebra of cylinder sets.


text:
Q: get all element and value of html in android i have some html like this one:

text1

Second Text

TextAgain

i need to get element name and some properties of that in a list or array.
just name of tag (like p) and text of between tag and for img tag  src property.
like this:
 String[] elements = {
        "p",
        "p",
        "img",
        "p",
        "img"
    }

String[] values = {
    "text1  ",
    "<img src=...",
    "http://thesite.com/apple.png",
    "<img src=...",
    "http://thesite.com/sony.gif"
}

is there any library like Jsoup or any method to doing that?

A: You can do it with:
package com.github.davidepastore.stackoverflow35087945;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Stackoverflow question 35087945
 *
 */
public class App {
    public static void main(String[] args) {
        String html = "
text1

Second Text

TextAgain
";
        Document document = Jsoup.parse(html);
        Elements elements = document.select("body *");
        List<String> tagNames = new ArrayList<String>();
        List<String> values = new ArrayList<String>();
        for (Element element : elements) {
            String tagName = element.tagName();
            tagNames.add(tagName);
            if ("img".equals(tagName)) {
                values.add(element.attr("src"));
            } else {
                values.add(element.html());
            }
        }
        System.out.println(tagNames);
        System.out.println(values);
    }
}

It will print:
[p, p, img, p, img, p, p, img, p, p]
[text1  , , http://theSite.com/apple.png, , http://theSite.com/sony.gif, Second Text , , http://theSite.com/img.jpg,  , TextAgain ]


text:
Q: What is the maximum allowable load capacitance for 74HC04? Does anybody know the maximum allowable load capacitance for 74HC04? In the datasheet,  nothing is mentioned in the "Limiting values" section. Some of the dynamic characteristics are given for a load capacitance value of 50 pF, but the limiting value is not mentioned. Any ideas?
Abhishek

A: There really isn't any. The greater the capacitance the slower the output transition, but at least for single outputs, the output can be short-circuited to ground indefinitely. If all outputs are shorted the chip will probably overheat. The slow transition produced by driving a large capacitance can cause big problems if the output is driving other logic unless a Schmitt trigger is used. So how slow a rise or fall time are you willing to accept?

A: You can derive a maximum capacitance from thermal considerations (from your datasheet):

Absolute Maximum allowable dissipation is 500mW at up to 70°C (again, from the datasheet), so maybe we don't go quite that far- say 250mW.
Which gives us \$C_L(\text{max}) \approx \frac{250000}{n\cdot Vcc^2 \cdot f_o}\$
where n is the number of outputs loaded
so if n = 4 and Vcc = 5.1 and fo = 1MHz  Cl(max) is about 2.4nF.
Of course the rise and fall times under these conditions will be greatly extended, but the chip should survive, at least for a while. I would be somewhat concerned about long term reliability since there are failure modes that are related to the current passing through internal conductors on the chip.

A: Obviously 50 pF is safe, but you can't assume much beyond that.
My take on this is that somewhat larger capacitance isn't going to hurt the device, but the switching time specs are only guaranteed with up to 50 pF on the output.
Basically, these parts aren't intended to drive significant capacitance, so aren't specified that way.  If this is really important to you and you want a guaranteed spec from the manufacturer, then you probably have to use a line driver that is intended for such things and specified that way.


text:
Q: pageLength working only in firstpage - DataTable I just need to adjust few functions in my datatable (ref Datatables) after or before ajax response. I tried to extend the page length to 30. Its working in first page only, Eg If I have 200 rows,

*

*first page shows "Showing 1 to 30 of 200 entries"

*second page shows "Showing 31 to 200 of 200 entries"

*third page shows "Showing 61 to 200 of 200 entries"

rest of the pages are same like this.
 success : function(data) {

    var table=$('#datatable').DataTable()   // initializing datatable
    $('#datatable').dataTable().fnClearTable();  //clearing old data in every ajax response

    for (var i = 0; i < data.length; i++) {
        table.row.add(  //adding rows
            [
                data[i].name,
                data[i].phone
            ])
            .draw();
    }

    table.destroy()  // destroy existing datatable and appending following objects

    $('#datatable').DataTable({
        dom: 'Bfrtlip',
        buttons: [ 'copy', 'excel','print', 'colvis' ],
        columns: [
            {name: 'name', title: 'Name'},      // Renaming Header
            {name: 'phone', title: 'Phone'}
        ],
        rowsGroup: [        // Using rowspan / grouping
            'name:name',
            'phone:name'
        ],
        pageLength: '30' //page length

        })

    }   //end of success()

If I don't destroy existing table, it shows an error message "cannot reinitialise datatable". I think the problem with table.destroy(). If I comment pageLength: '30', its working fine as default(10 records per page)
Is there any way to add objects without destroying? or adding these objects while creating rows/ initializing datatable? Or any way to soleve this problem? Thank you in advance.

A: pageLength: 30 //page length should be an integer :D :D


text:
Q: Modular exponentitation (Finding the remainder) I want to find the remainder of $8^{119}$ divided by $20$ and as for as i do is follows:
$8^2=64\equiv 4 \pmod {20} \\
8^4\equiv 16 \pmod {20} \\
8^8\equiv 16 \pmod {20}\\
8^{16}\equiv 16 \pmod {20}$
from this i see the pattern as follows $8^{4\cdot 2^{n-1}} \text{is always} \equiv 16 \pmod {20} \,\forall n \ge 1$
So,
$\begin{aligned} 8^{64}.8^{32}.8^{16}.8^7 &\equiv 16.8^7 \pmod{20}\\
&\equiv 16.8^4.8^3 \pmod{20} \\
&\equiv 16.8^3 \pmod {20}\end{aligned}$
And i'm stuck. Actually i've checked in to calculator and i got the answer that the remainder is $12$. But i'm not satisfied cz i have to calculate $16.8^3$
Is there any other way to solve this without calculator. I mean consider my condisition if i'm not allowed to use calculator.
Thanks and i will appreciate the answer.

A: $8^n=(2^3)^n=2^{3n}$
As $(2^{3n},20)=4$ for $n\ge1$
Let's find $2^{3n-2}\pmod5$
Now $2^{3n-2}\equiv2^{(3n-2)\pmod4}\pmod5$ as $\phi(5)=4$
$\implies2^{3n}\equiv4\cdot2^{(3n-2)\pmod4}\pmod{20}$
Here $n=119\implies3n-2=3\pmod4$

A: You are almost there. You can reduce anything modulo $20$ so:
$$16\times 8^3\equiv 16\times 8^2\times 8\equiv 16\times 4 \times 8\equiv64\times 8\equiv 4\times 8\equiv 12$$
You could also have used $16\equiv -4$ if it had helped - sometimes negative numbers make life easier, but it was not necessary here.

A: Although $8^{4\cdot 2^{n-1}}\equiv 16\pmod {20} $ for all positive integer $n $,  it is actually much simpler:
$8^{4k}\equiv 16\pmod {20} $ for all $k>0$.  That is for any multiple of $4$, not just $4$times powers of $2$.
And furthermore $8^{4k+1}\equiv 16*8\equiv -4*8\equiv-32\equiv 8\pmod {20} $ for $k>0$
And $8^{4k+2}\equiv 8*8\equiv 4\pmod {20} $
And $8^{4k+3}\equiv 4*8\equiv 32\equiv 12\pmod {20} $.

A: Using $\, ab\bmod ac\, =\, a\,(b\bmod c) $ = mod Distributive Law to factor out $\,a =4\,$ yields
$\ \ \ \ 8^{\large 3+4K}\!\bmod 20\, =\, 4\,(\underbrace{2\cdot \color{#0a0}{8^{\large 2}}\,\color{#c00}8^{\large \color{#c00}{4}K}}_{\Large 2\,   (\color{#0a0}{-1})\,\color{#c00}1^{\Large K}}\bmod 5) = 4(3)\ $


text:
Q: ASP.NET - Can you use Dynamic Data without Linq to SQL? I have an application that creates database tables on the fly.
I'd like to create an interface to CRUD this data.
But because the tables are created as the application runs,  I can't create the Linq to SQL classes by dragging them onto the designer.
However, I do know in my code what the tables I want to edit are.
Can anyone tell me if it is possible to supply a feed to Dynamic Data via:

*

*SQL query

*Or a DataSet,

Rather than the Linq to SQL paradigm?

A: As far as I know this is not a possibility.  From MSDN :

It does this by automatically discovering the LINQ-to-SQL or Entities Framework data model at run time

There is an MVC version coming but that will have similar limitations.
There may be some way you can create a workaround for your situation since you do have tables at some point but I'm unsure without more information.

A: Well, DD works with Linq to SQL and Entity Framework.  For your problem, it seems neither would be very helpful.


text:
Q: Reading grib2 data Does anyone have any experience reading grib2 data? Looking to add functionality to one of my weather apps but can't seem to find a whole lot on grib2, or how one would get it into a readable form.

A: There is a program called wgrib2 that you can use to extract data from grib2 files. I use it from the command line to extract time series at a chosen lat/lon location, but it can do other kinds of slicing & dicing.


text:
Q: how do I create an index column in HTML Table I need to create a serial column of objects obtained by the get method of an external API. But I can not create this column in the table.
HTML

         #
         Nome
         Sobrenome
         Participação

            {{chart.id}}
            {{chart.name}}
            {{chart.lastname}}
            {{chart.participation}}%

Component:
  ngOnInit() {
    this.ChartGraph();
    this.Parallax();
  }
  getId() {

  }
  ChartGraph() {
    this.mainService.getChart().subscribe(data => this.charts = data)

JSON:
[{
    "name": "Carlos",
    "lastname": "Moura",
    "participation": 5.00
}, {
    "name": "Fernanda",
    "lastname": "Oliveira",
    "participation": 15.00
}, {
    "name": "Hugo",
    "lastname": "Silva",
    "participation": 20.00
}, {
    "name": "Eliza",
    "lastname": "Souza",
    "participation": 20.00
}, {
    "name": "Anderson",
    "lastname": "Santos",
    "participation": 40.00
}]

I need the table to look like this:

currently it looks like this:

A: ngFor provides you an index of every iteration. You simply need to use the same as follows -

    {{(i + 1)}}


text:
Q: linking boost log using cmake error what can cause the following problem:
I tried to use boost::log in a cmake project.
My CMakeList.txt file looks like this:
cmake_minimum_required(VERSION 3.10)
project(boostLogTest)
set(CMAKE_CXX_STANDARD 11)
add_executable(boostLogTest main.cpp)
ADD_DEFINITIONS(-DBOOST_LOG_DYN_LINK) #####  edit after DiCri's answer #####
find_package(Boost REQUIRED COMPONENTS log system)

if (Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})

    message("Boost VERSION: ${Boost_VERSION}")
    message("Boost INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message("Boost Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}")
    message("Boost LIBRARIES: ${Boost_LIBRARIES}")

    TARGET_LINK_LIBRARIES(boostLogTest ${Boost_LIBRARIES})
endif ()

and my main.cpp file looks like this:
#include <iostream>

#include <boost/log/trivial.hpp>

int main(int, char*[])
{
    BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
    BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
    BOOST_LOG_TRIVIAL(info) << "An informational severity message";
    BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
    BOOST_LOG_TRIVIAL(error) << "An error severity message";
    BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";

    return 0;
}

My CMake output is the following

-- Boost version: 1.64.0
-- Found the following Boost libraries:
--   log
--   system
--   date_time
--   log_setup
--   filesystem
--   thread
--   regex
--   chrono
--   atomic Boost VERSION: 106400 Boost INCLUDE_DIRS: /usr/local/include Boost Boost_LIBRARY_DIRS: /usr/local/lib Boost
LIBRARIES:
  /usr/local/lib/libboost_log.so;/usr/local/lib/libboost_system.so;/usr/local/lib/libboost_date_time.so;/usr/local/lib/libboost_log_setup.so;/usr/local/lib/libboost_filesystem.so;/usr/local/lib/libboost_thread.so;/usr/local/lib/libboost_regex.so;/usr/local/lib/libboost_chrono.so;/usr/local/lib/libboost_atomic.so
-- Configuring done
-- Generating done
-- Build files have been written to: /home/.../CLionProjects/boostLogTest/cmake-build-debug

but while linking I get the following error messages:

[ 50%] Linking CXX executable boostLogTest
CMakeFiles/boostLogTest.dir/main.cpp.o: In function `main':
/home/.../CLionProjects/boostLogTest/main.cpp:7: undefined reference to `boost::log::v2s_mt_posix::trivial::logger::get()'
/home/.../CLionProjects/boostLogTest/main.cpp:7: undefined reference to `boost::log::v2s_mt_posix::trivial::logger::get()'
/home/.../CLionProjects/boostLogTest/main.cpp:8: undefined reference to `boost::log::v2s_mt_posix::trivial::logger::get()'
/home/.../CLionProjects/boostLogTest/main.cpp:8: undefined reference to `boost::log::v2s_mt_posix::trivial::logger::get()'
/home/.../CLionProjects/boostLogTest/main.cpp:9: undefined reference to boost::log::v2s_mt_posix::trivial::logger::get()'
  CMakeFiles/boostLogTest.dir/main.cpp.o:/home/.../CLionProjects/boostLogTest/main.cpp:9: more undefined references toboost::log::v2s_mt_posix::trivial::logger::get()' follow ...

Edit after DiCri's answer:
Now I get the following error messages:

[ 50%] Linking CXX executable boostLogTest
/usr/bin/ld: CMakeFiles/boostLogTest.dir/main.cpp.o: undefined reference to symbol 'pthread_rwlock_unlock@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
CMakeFiles/boostLogTest.dir/build.make:103: recipe for target 'boostLogTest' failed
make[3]: *** [boostLogTest] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/boostLogTest.dir/all' failed
make[2]: *** [CMakeFiles/boostLogTest.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/boostLogTest.dir/rule' failed
make[1]: *** [CMakeFiles/boostLogTest.dir/rule] Error 2
Makefile:118: recipe for target 'boostLogTest' failed
make: *** [boostLogTest] Error 2

If I add
set(Boost_USE_STATIC_LIBS        ON)

the paths to the libraries change to a *.a file, like:
Boost LIBRARIES: /usr/local/lib/libboost_log.a;/usr/local/lib/libboost_system.a;...

All listed libraries (the *.so and the *.a) exist in this folders.
What am I missing?

A: Just try to add this line
#define BOOST_LOG_DYN_LINK 1

As the first line of the main.cpp file, i think it should work, someone got your same issue here
If that doesn't work, try to add this line
ADD_DEFINITIONS(-DBOOST_LOG_DYN_LINK)

To CMake file
You need to add OpenMP package too


text:
Q: Image slider in layout I need to develop image slider that will be in layout but i'm begginer in zf2. Is any method to load image src from database? I know how to set variables in onBootstrap() the only problem is to connect db and retrive data via fetchAll() in my tableGateway.

A: About your image slider, I think it will be in jquery, bootstrap ?
so you have just to print result from your database.
for example this : http://framework.zend.com/manual/2.0/en/modules/zend.db.result-set.html#quickstart

A: you can use inbuilt zf2 module:-
https://packagist.org/packages/ledsinclouds/leds-js-slider


text:
Q: Conditions a discontinuous f must obey so $\int f$ is continuous? What conditions must a discontinuous $f$ satisfy for the $\int\limits_{-\infty}^x f(u) \ dP$ to be continuous?
I would say the set of discontinuities must have measure zero. Is it also sufficient?
Am I missing something?
Any help would be appreciated.

A: Let $f$ be integrable over each set $(-\infty,a)$, $a\in\mathbb R$. Then, if $x > x_0$,
$$
\int_{(-\infty,x]}f\,dP - \int_{(-\infty,x_0]}f\,dP = \int_{(x_0,x]}f\,dP = \int_{(-\infty,x_0+1)}\chi_{(x_0,x]}f\,dP.
$$
The integral on the RHS tends to zero as $x$ approaches $x_0$ by Lebesgue's theorem. Hence, the function is always right-continuous. If $x < x_0$, then
$$
\int_{(-\infty,x_0]}f\,dP - \int_{(-\infty,x]}f\,dP = \int_{(x,x_0]}f\,dP = f(x_0)P(\{x_0\}) + \int_{(-\infty,x_0+1)}\chi_{(x,x_0)}f\,dP.
$$
Hence, the limit as $x\to x_0$ is zero if and only if either $f(x_0) = 0$ or if $P$ does not have mass at $x_0$.
Here, $(x_0,x]$ means either $(x_0,x]$ when $x > x_0$ or $[x,x_0)$, when $x < x_0$.
The discontinuities of $f$ are not important here. For example, let $f=1$ and let $P$ be the probability measure that has mass one at zero. Then
$$
\int_{(-\infty,x]}f\,dP = \begin{cases}0 &\text{if }x < 0\\1 &\text{if }x\ge 0\end{cases}.
$$
So, there is a jump at zero although $f$ is continuous.


text:
Q: java.security.NoSuchProviderException: no such provider: nCipherKM We are trying to connect to an HSM. However even after we add nCipher to the list of providers and restart wildfly, it is still giving this error upon deployment.
Any idea why it's not detecting it?

A: Make sure you have the nCipherKM in $JAVA_HOME/jre/lib/ext folder for JDK or $JAVA_HOME/lib/ext for JRE.
Reassure that you have both jcecsp and javasp bundles installed.
Hardserver configuration needs to be done properly to accept connections at 9000 and 9001 locally.
Security world needs to be created/imported. You can check that using nfkminfo command.
Restart the hardserver if you had to do any configuration changes.


text:
Q: How to avoid reloading every time page and tabs flutter My problem is when I enter the app its open home page and it will load the data from api, i am navigate to other page and then again when i come home page its again load the data. Same problem in tabs. I have 3 tabs in a page and each and every time data will load, I want load data only once but when data update in database then I want to show changes that's why I am using stream builder for creating list.
I am using stream builder.
following are my code:
late Stream<AdminPostModel> stream = Stream.periodic(Duration(seconds: 3))
      .asyncMap((event) async => await getCurrentAdminPost());

  Future<AdminPostModel> getCurrentAdminPost() async {

    var url = "https:myURL.php?id=$getUserId&pageNo=$currentPage";
    var response = await http.get(Uri.parse(url));
    var jsondata = jsonDecode(response.body.toString());

    if (response.statusCode == 200) {
           return AdminPostModel.fromJson(jsondata);
      }
    else {
      return AdminPostModel.fromJson(jsondata);
    }
  }

For making list of data:
               Expanded(
                    child: StreamBuilder<AdminPostModel>(
                  stream: stream,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return ....Code

A: That functionality called persist your class state & to achieve that you have to use wantKeepAlive
1) add  with AutomaticKeepAliveClientMixin after your State class

class ClassHome extends StatefulWidget{
@override
State<StatefulWidget> createState() => stateClassHome();

bool isPersistState;
ClassHome({required this.isPersistState});

}

class stateClassHome extends State<ClassHome> with AutomaticKeepAliveClientMixin {

*override wantKeepAlive variable
@override
 // TODO: implement wantKeepAlive
 bool get wantKeepAlive => widget.isPersistState;

 @override
 void initState() {
 …

*Write this condition in your build context
@override
Widget build(BuildContext context) {
   if (wantKeepAlive) {
     super.build(context);
   }

   return Scaffold(
     ….

*now in tabbar you've to set only isPersistState value if you set true then your data will not reload again & in some cases like when we've to deal with real time data then set it false
ClassDashboard(isPersistState: true,)


text:
Q: Is this a valid use of css3 :not() This is somehow not working: #ipadmenu.oldcontent ~ :not(#ipadmenu.newcontent) ~ #content.newcontent article {width:728px}
Is this normal? If this is correct it might be because of some other css rule that is conflicting, but I cannot seem to find it.
Did I do something wrong?
Thanks :)

A: There's a syntax error, as you can check with http://jigsaw.w3.org/css-validator/ (though its report is a bit cryptic in this case). The argument of :not() must be a simple selector, see definition of :not in the CSS3 spec. The code works (on sufficiently modern browsers) if you use e.g. just .newcontent as the argument.
I can't quite see why you would also have #ipadmenu there, as you cannot validly have two elements with the same id, i.e. #ipadmenu matches as most one element in a document.


text:
Q: update to a specific tag in liquibase I know that I can include a version tag in my changelog by having a changeset
<changeSet id="1234" author="John">
    <tagDatabase tag="version_1"/>
</changeSet>

and that will allow me to rollback a database to version_1.
If I have a brand new database, is it possible to run update and just target up to a tag? I know that I could do a full update and then rollback, but that's a bit awkward.

A: Update:
There is now an updateToTag command. See https://docs.liquibase.com/commands/community/updatetotag.html
Original:
There isn't currently a way to update to a tag. Liquibase assumes that the changelog matches your code and so you wan to make sure everything is ran. Normally if you want to only have portions of a changelog ran you would use multiple changeLogs or code branches with different changelog versions.
You can use updateCount to run a certain number of changeSets, but you need to know the number. You could also use the  tag which will halt changeSet execution at a certain point (possibly controlled with contexts or precoditions), but it is not tied to the tag functionality.

A: They now have a new attribute for liquibase command. Just do:
liquibase updatetotag <tagname>


text:
Q: Facebook connect without Javascript in WiFi Hotspot I am going to integrate the Facebook login access on my WiFi hotspot portal. Basically I would like the user to log on my portal using its Facebook credentials, in order to access the Internet via Hotspot.
The classical integration using connect-js via Javascript cannot work, since unauthenticated users cannot reach the Internet, and in this condition the browser cannot connect to Facebook.com.
Please, I would like to understand if there is a way, from my PHP portal, to send an HTTP post request to Facebook.com containing the users credentials. I just have made a test, but I have received the following response "For your security, never enter your Facebook password on sites not located on Facebook.com".
Thank you very much.

A: You need to manually-build-a-login-flow (relevant facebook documentation)
The below snippet is the crux of it however
https://www.facebook.com/v3.0/dialog/oauth?
    client_id={app-id}
    &redirect_uri={redirect-uri}
    &state={state-param}