text:
Q: Spring Boot Startup Analysis Tool I am trying to use this tool on github to analyze my spring boot app's startup time. Here's my main class:
@Configuration
@EnableAutoConfiguration
@ComponentScan(lazyInit = true, value = {"com.test.app","com.github.lwaddicor.springstartupanalysis"})
public class Application extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ApiApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}

My application starts up fine but when I try to navigate to: http://localhost:8080/spring-startup/ I get the following message:
{"status":401,"message":"Authentication failed","errorCode":10,"timestamp":1519416149986}

I tried editing the security filters like so:
@EnableWebSecurity
@EnableWebMvc
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(,
                "/configuration/ui",
                "/configuration/security",,
                "/spring-startup",
                "/webjars/**");
    }
}

But that didn't work. Any ideas what I'm doing wrong?

A: I think antMatchers() alone is not sufficient since you just tell the system which resources are affected but you do not specify how to deal with them. Append .permitAll() and it should work.
I am using something like this:
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.HEAD, "/**").permitAll()
.antMatchers("/v2/api-docs", "/configuration/ui", ...)
            .permitAll()
.antMatchers(basePath + "/**").authenticated()
...

basePath is the path to the rest api which should be secured.

A: I got this to work by commenting out the overriden configure method. Not optimal but I only need to run this locally once so not a big deal to turn security off either.


text:
Q: Linq, double left join and double count I'm looking to translate this SQL statement to a well working & performant LINQ command. I've managed to have the first count working using the grouping count and key members, but don't know how to get the second count.
select main.title, count(details.id) as details, count(messages.id) as messages
from main
 left outer join details on main.id = details.mainid
 left outer join messages on details.id = messages.detailid
group by main.title

Here's what I've done so far:
from main in Main
join detail in Details on main.Id equals detail.MainId into j1
from subdetail in j1.DefaultIfEmpty()
group main by main.Title into g
select new { Title = g.Key, Details = g.Count() }

Any advice is welcome!
EDIT: 24/03/2010 09.41
This query:
from main in Main
join detail in Details on main.Id equals detail.MainId into j1
from subdetail in j1.DefaultIfEmpty()
join message in Messages on subdetail.Id equals message.DetailId into j2
group main by main.Title into g
select new { Title = g.Key, Details = g.Count() }

generates this SQL statement:
SELECT COUNT(*) AS [Detail], [t0].[Title]
FROM [Main] AS [t0]
LEFT OUTER JOIN [Detail] AS [t1] ON [t0].[Id] = [t1].[MainId]
LEFT OUTER JOIN [Messages] AS [t2] ON [t1].[Id] = [t2].[DetailId]
GROUP BY [t0].[Title]

So, I'm almost done!
Fabian

A: Wouldn't something like this work?
from main in Main
select new {
    Title = main.Title,
    Details = main.Details.Count(),
    Messages = main.Details.Sum( d => d.Messages.Count())
}

If you have foreign key constraints, LINQ should generate the child-relationships automatically, so you could access main.Details for each Detail associated with main, and main.Messages for each Message associated with main.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ new line not translating First off, I'm a complete beginner at C++.
I'm coding something using an API, and would like to pass text containing new lines to it, and have it print out the new lines at the other end.
If I hardcode whatever I want it to print out, like so
printInApp("Hello\nWorld");

it does come out as separate lines in the other end, but if I retrieve the text from the app using a method that returns a const char then pass it straight to printInApp (which takes const char as argument), it comes out as a single line.
Why's this and how would I go about to fix it?

A: It is the compiler that process escape codes in string literals, not the runtime methods. This is why you can for example have "char c = '\n';" since the compiler just compiles it as "char c = 10".
If you want to process escape codes in strings such as '\' and 'n' as separate characters (eg read as such from a file), you will need to write (or use an existing one) a string function which finds the escape codes and converts them to other values, eg converting a '\' followed by a 'n' into a newline (ascii value 10).


text:
Q: Is random walk a martingale? Suppose $X_i \sim i.i.d. N(0,1), i=1,...$, $S_n=X_1+...+X_n$ let's
$ Y_{i}^{\left( v \right)} := X_i \textbf{1}_{ \left\{ \left| X_i \right| \leq v \right\} },
X_{i}^{\left( v \right)} := \left( Y_{i}^{\left( v \right)} - E [ Y_{i}^{\left( v \right)} ] \right) $ and
$ S_{n}^{(v)} = \sum\limits_{i=1}^{n} X_i \textbf{1}_{ \left\{ \left| X_i \right| \leq v \right\} } - E \left[ \sum\limits_{i=1}^{n} X_i \textbf{1}_{ \left\{ \left| X_i \right| \leq v \right\} } \right] $.
I have to show that sequence $\{ S_n-S_n^{(v)} \}_{n=1}^{\infty}$ is a martingale.
I tried to define a filtration but i don't know if it's good way and appropriate filtration. $\mathcal{F}_n=\sigma(X_1,...,X_n)$ and calculate
$ E[S_{n+1}-S_{n+1}^{(v)}|\mathcal{F}_n] $ and i got
$$ E[S_{n+1}-S_{n+1}^{(v)}|\mathcal{F}_n]=
E[S_{n}-S_{n}^{(v)}+ X_{n+1} \textbf{1}_{ \left\{ \left| X_{n+1} \right| > v \right\} }+E[X_{n+1} \textbf{1}_{ \left\{ \left| X_{n+1} \right| \leq v \right\} }] |\mathcal{F}_n]=
E[S_{n}-S_{n}^{(v)}|\mathcal{F}_n] + E[X_{n+1} \textbf{1}_{ \left\{ \left| X_{n+1} \right| > v \right\} }+E[X_{n+1} \textbf{1}_{ \left\{ \left| X_{n+1} \right| \leq v \right\} }] |\mathcal{F}_n]=
S_{n}-S_{n}^{(v)}+E[X_{n+1} \textbf{1}_{ \left\{ \left| X_{n+1} \right| > v \right\} }+X_{n+1} \textbf{1}_{ \left\{ \left| X_{n+1} \right| \leq v \right\} }|\mathcal{F}_n]=
S_{n}-S_{n}^{(v)} + E[X_{n+1}|\mathcal{F}_n]=S_{n}-S_{n}^{(v)}
$$
Because $X_{n+1}$ is independent of $\mathcal{F}_n$.
I'm not sure if it's a right way to do this.


text:
Q: How to shutdown an Android mobile programmatically? Is it possible to shutdown the mobile programmatically.
that is with out using su commands..

A: It is possible, but you need a Rooted Android device with Superuser access. You can't do it without Root unless your app is signed with the System Firmware Key. Try using the following code:
Shutdown:
try {
    Process proc = Runtime.getRuntime()
                    .exec(new String[]{ "su", "-c", "reboot -p" });
    proc.waitFor();
} catch (Exception ex) {
    ex.printStackTrace();
}

Reboot:
Same code, just use "reboot" instead of "reboot -p".
[On an other note: I read somewhere that these commands do not work on Stock HTC ROMs, but haven't confirmed myself]

A: You could possibly use the PowerManager to make it reboot (this does not guarantee that it'll reboot - OS may cancel it):
http://developer.android.com/reference/android/os/PowerManager.html#reboot(java.lang.String)
It requires the REBOOT permission:
http://developer.android.com/reference/android/Manifest.permission.html#REBOOT
Can you also check your logcat when trying to enable/disable keyguard, and post what's there?
You cannot do this from an ordinary SDK application. Only applications signed with the system firmware signing key can do this

A: This is the code i use to perform any system command.
void shutdown_sys()
{
    Process chperm;
    try {
        chperm=Runtime.getRuntime().exec("su");
          DataOutputStream os =
              new DataOutputStream(chperm.getOutputStream());

              os.writeBytes("shutdown\n");
              os.flush();

              chperm.waitFor();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Call this function from your android App. It will work if su is functional in your system.
Let me know in case it does not work. I dont have an Android base ready to test. But the same works for reboot. So shutdown is also a linux shell command which ithink will be there in Android as well.. All the best

A: With rooted shell command type in, svc power shutdown works for me in android 7.1

A: I don't see any resemblance with your title and the code snippet in the body. The snippet is related with KeyGuardManager which is used for lock and unlock the key pad.
In order to shutdown your phone you will need to use PowerManager or SU commands. (On rooted devices.)

A: If your device is rooted then you can try below solution
Shutdown:
try {
    Process proc = Runtime.getRuntime()
                    .exec(new String[]{ "su", "-c", "reboot -p" });
    proc.waitFor();
} catch (Exception ex) {
    ex.printStackTrace();
}

Restart:
Same code, just use "reboot" instead of "reboot -p".

A: My solution : I have a system app installed in priv-app, no signed with the system key.
Process proc = Runtime.getRuntime().exec(new String[] { "/system/bin/svc", "power", "shutdown" });
proc.waitFor();


text:
Q: if inside for Loop in postgresql I have two tables as below.
TABLE 1       TABLE 2
--------     --------
id            id
date          table1_id
total         subtotal
balance

table 1                     table 2
--------                    ---------
id  total  balance          id table1_id subtotal paid
1    20      10              1      1      5       5
2    30      30              2      1      15      5
                             3      2      10      0
                             4      2      10      0
                             5      2      10      0

I have to add paid column in table2. so can anyone help me to add values to newly added column for existing data. I tried to wrote procedure as below but as postgres will not allow if in for loop so am unable to do it.
CREATE OR REPLACE FUNCTION public.add_amountreceived_inbillitem() RETURNS void AS
$BODY$
DECLARE
rec RECORD;
inner_rec RECORD;
distributebalance numeric;
tempvar numeric;
BEGIN
FOR rec IN select * from table1
LOOP
distributebalance = rec.balance;
FOR inner_rec IN(select * from table2 where table1_id = rec.id order by id limit 1)
 tempvar = distributebalance - inner_rec.subtotal;
 if (distributebalance >0 and tempvar>=0) THEN
    update table2 set paid = inner_rec.subtotal where id = inner_rec.id ;
    distributebalance =distributebalance-inner_rec.subtotal;
 else if( distributebalance >0 and tempvar<0 )THEN
    update table2 set paid = distributebalance where id = inner_rec.id;
END IF;
END LOOP;
END LOOP;
END; $BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

Thanks In advance :)

A: Postgres does allow for IF statements in loops.
The issue is that by writing ELSE IF you've started a new IF statement, so you now have 2 opening IFs but only one closing END IF. A "proper" elseif in plpgsql is ELSIF or ELSEIF. So just delete the space between those words and it should work.


text:
Q: Can we have some statistics about users who could overcome the post-ban? We often come across questions on Meta where users complaint/rant that they can't ask/answer any further question; some come here for advice on how to overcome this restriction and re-juvenate their user accounts like the following one:

*

*Can I receive some account ban advice?
So, can we have some statistics about how many users are getting banned on a periodic basis and how many of them are able to recover and overcome this ban, what was the extent of effort required on their part to recover from this ban (amount of upvotes they had to receive, edit suggestions they had to made, etc), time period taken to overcome and other similar statistics which would help to assess the situation?


text:
Q: Space between FlatButton in flutter enter image description hereHello I am making an application where i need to maximize and minimise the screen.But i want to reduce space between 'A+'(i.e. maximising the screen) and 'A-'(i.e. minimising).I am attaching an image for better understanding.Thank you.

Here is the code:

return Scaffold(
      appBar: AppBar(
        title: Text(''),
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
           FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: null,
                child: Text('A+',style: TextStyle(
                  fontSize: 22.0,fontWeight: FontWeight.bold,color: Colors.white
                ),)),

          FlatButton(
            padding: EdgeInsets.all(0),
            onPressed: null,
            child: Text('A-',style: TextStyle(
                fontSize: 15.0,fontWeight: FontWeight.bold,color: Colors.white
            ),),

          )

        ],
      ),

A: Use SizedBox
Scaffold(
      appBar: AppBar(
        title: Text(''),
        titleSpacing: 10,
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
           SizedBox(
             width: 30,
             child: FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: null,
                child: Text('A+',style: TextStyle(
                  fontSize: 22.0,fontWeight: FontWeight.bold,color: Colors.white
                ),))),

          SizedBox(
             width: 30,
             child:FlatButton(
            padding: EdgeInsets.all(0),
            onPressed: null,
            child: Text('A-',style: TextStyle(
                fontSize: 15.0,fontWeight: FontWeight.bold,color: Colors.white
            ),),

          ))

        ],
      ))

A: Image of the Flatbutton:

Container(
        decoration: new BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.blue, width: 1.0),
          borderRadius: new BorderRadius.all(Radius.circular(3.0)),
        ),
        width: double.infinity,
        child: FlatButton(
          padding: EdgeInsets.all(8.0),
          onPressed: () {
            // Write the function
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text("Add a Note"),
              Icon(
                Icons.note_add,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),


text:
Q: How can I solve chart_js.Chart.register problem when using chart.js Am developing a user dashboard application using Next.js. I query my client from a node and MongoDB server. I need to load my graphs using chart.js. But when I run the code I experience this error. TypeError: chart_js.Chart.register is not a function.
Here is the code snippet:
import {Chart as ChartJS} from 'chart.js';
import { Bar } from 'react-chartjs-2';

import React, { useEffect, useReducer } from 'react';
import Layout from '../../components/Layout';
import { getError } from '../../utils/error';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

A: 2 Things, you are not importing all the elements you are trying to register and since Chart.register is not a function I suspect you are using V2 of Chart.js which is non treeshakable. So you can't and don't have to use register to show the charts unless you are going to upgrade to V3 and use treeshaking
If you want to register any plugins in V2 you need to register them on the plugins of the chart like so:
Chart.plugins.register(plugins);


text:
Q: How to make move up and move down mark in proofreading? MWE
\documentclass[12pt]{article}
\begin{document}
$\underline{a}\sqcap\underline{a}$
$\overline{a}\sqcup\overline{a}$
\end{document}

but what I try to do

Can you help me fix it?
Edited:
How did this happen? And Is there anyone who can make it better?
\documentclass[a4paper,11pt]{article}

\usepackage[svgnames]{xcolor}
\usepackage{mathtools}
\usepackage{tikz}
\usepackage{pgflibraryshapes}
\usepackage{stackengine}

\begin{document}

$\color{red}{\underline{\textnormal{\color{black}{a}}}} \kern3pt \tclap[-1.7pt]{$\sqcap$} \kern3pt \color{red}{\underline{\textnormal{\color{black}{a}}}}$
$\color{red}{\overline{\textnormal{\color{black}{a}}}} \kern3pt \tclap[-.3pt]{$\sqcup$} \kern3pt \color{red}{\overline{\textnormal{\color{black}{a}}}}$

\end{document}

A: Like this?
\documentclass[12pt]{article}
\begin{document}
$\underline{a}\sqcap\underline{a}$ $\to$
$\begin{array}{c|c|c}
\cline{2-2}
a & & a\\
\cline{1-1}\cline{3-3}
\end{array}$\\ \\
$\overline{a}\sqcup\overline{a}$ $\to$
$\begin{array}{c|c|c}
\cline{1-1}\cline{3-3}
a & & a\\
\cline{2-2}
\end{array}$
\end{document}

A: A different approach with TikZ

\documentclass[border=2mm,tikz]{standalone}

\newcommand\moveup[2]{%
  \begin{tikzpicture}
    \path[draw=red] (0,0)--node[above=-1.5pt] {#1}(0.25,0)--(0.25,0.25)--(0.5,0.25)--(0.5,0)--node[above=-1.5pt]{#2}(0.75,0);
  \end{tikzpicture}%
}

\newcommand\movedown[2]{%
  \begin{tikzpicture}
    \path[draw=red] (0,0.25)--node[below=-1.5pt] {#1}(0.25,0.25)--(0.25,0)--(0.5,0)--(0.5,0.25)--node[below=-1.5pt]{#2}(0.75,0.25);
  \end{tikzpicture}%
}

\begin{document}

\moveup{a}{a}
\movedown{a}{a}

\end{document}

A: Cragfelt beat me by a couple of minutes, but a here is a slightly different approach with TikZ.

\documentclass{article}
\usepackage{tikz}
\newcommand\moveup[3][]{
\begin{tikzpicture}[baseline=(a.base)]
\node [inner sep=0pt] (a) {#2};
\node [inner sep=0pt,right=1em,anchor=base west] (b) at (a.base east) {#3};
\draw [red,#1] ([shift={(-2pt,-3pt)}]a.base west) -| ([shift={(1pt,2ex+2pt)}]a.base east) -|
               ([shift={(-1pt,-3pt)}]b.base west) -- ([shift={(2pt,-3pt)}]b.base east);
\end{tikzpicture}}
\newcommand\movedown[3][]{
\begin{tikzpicture}[baseline=(a.base)]
\node [inner sep=0pt] (a) {#2};
\node [inner sep=0pt,right=1em,anchor=base west] (b) at (a.base east) {#3};
\draw [red,#1] ([shift={(-2pt,2ex+2pt)}]a.base west) -| ([shift={(1pt,-3pt)}]a.base east) -|
               ([shift={(-1pt,2ex+2pt)}]b.base west) -- ([shift={(2pt,2ex+2pt)}]b.base east);
\end{tikzpicture}}
\begin{document}
Foo \moveup{g}{b} bar \movedown{Lorem}{ipsum}
\end{document}


text:
Q: How to cluster Hazelcast instances? How to run two Hazelcast instances on two different machines within the same cluster?
this is my configuration here
I want to know how we can configure multicast and TCP in the network element for testing high-availability. I tried searching in many articles but could not find any relevant configuration

A: If you have two machines, with static IPs, then the simplest way is to use the TCP/IP configuration.
Assuming the IP addresses or your machines are: 1.2.3.4 and 5.6.7.8 and you use the default Hazelcast port 5701, you should have the following configuration:
<multicast enabled="false" />
<tcp-ip enabled="true">
    <member-list>
        <member>1.2.3.4</member>
        <member>5.6.7.8</member>
    </member-list>
</tcp-ip>


text:
Q: Weak Reference to NSTimer Target To Prevent Retain Cycle I'm using an NSTimer like this:
timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(tick) userInfo:nil repeats:YES];

Of course, NSTimer retains the target which creates a retain cycle. Furthermore, self isn't a UIViewController so I don't have anything like viewDidUnload where I can invalidate the timer to break the cycle.  So I'm wondering if I could use a weak reference instead:
__weak id weakSelf = self;
timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:weakSelf selector:@selector(tick) userInfo:nil repeats:YES];

I've heard that the timer must be invalidated (i guess to release it from the run loop). But we could do that in our dealloc, right?
- (void) dealloc {
    [timer invalidate];
}

Is this a viable option? I've seen a lot of ways that people deal with this issue, but I haven't seen this.

A: Swift 3
App target < iOS 10:
Custom WeakTimer (GitHubGist) implementation:
final class WeakTimer {

    fileprivate weak var timer: Timer?
    fileprivate weak var target: AnyObject?
    fileprivate let action: (Timer) -> Void

    fileprivate init(timeInterval: TimeInterval,
         target: AnyObject,
         repeats: Bool,
         action: @escaping (Timer) -> Void) {
        self.target = target
        self.action = action
        self.timer = Timer.scheduledTimer(timeInterval: timeInterval,
                                          target: self,
                                          selector: #selector(fire),
                                          userInfo: nil,
                                          repeats: repeats)
    }

    class func scheduledTimer(timeInterval: TimeInterval,
                              target: AnyObject,
                              repeats: Bool,
                              action: @escaping (Timer) -> Void) -> Timer {
        return WeakTimer(timeInterval: timeInterval,
                         target: target,
                         repeats: repeats,
                         action: action).timer!
    }

    @objc fileprivate func fire(timer: Timer) {
        if target != nil {
            action(timer)
        } else {
            timer.invalidate()
        }
    }
}

Usage:
let timer = WeakTimer.scheduledTimer(timeInterval: 2,
                                     target: self,
                                     repeats: true) { [weak self] timer in
                                         // Place your action code here.
}

timer is instance of standard class Timer, so you can use all available methods (e.g. invalidate, fire, isValid, fireDate and etc).
timer instance will be deallocated when self is deallocated or when timer's job is done (e.g. repeats == false).
App target >= iOS 10:
Standard Timer implementation:
open class func scheduledTimer(withTimeInterval interval: TimeInterval,
                               repeats: Bool,
                               block: @escaping (Timer) -> Swift.Void) -> Timer

Usage:
let timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] timer in
    // Place your action code here.
}

A: The proposed code:
__weak id weakSelf = self;
timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:weakSelf selector:@selector(tick) userInfo:nil repeats:YES];

has the effect that (i) a weak reference is made to self; (ii) that weak reference is read in order to provide a pointer to NSTimer. It won't have the effect of creating an NSTimer with a weak reference. The only difference between that code and using a __strong reference is that if self is deallocated in between the two lines given then you'll pass nil to the timer.
The best thing you can do is create a proxy object. Something like:
[...]
@implementation BTWeakTimerTarget
{
    __weak target;
    SEL selector;
}

[...]

- (void)timerDidFire:(NSTimer *)timer
{
    if(target)
    {
        [target performSelector:selector withObject:timer];
    }
    else
    {
        [timer invalidate];
    }
}
@end

Then you'd do something like:
BTWeakTimerTarget *target = [[BTWeakTimerTarget alloc] initWithTarget:self selector:@selector(tick)];
timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:target selector:@selector(timerDidFire:) ...];

Or even add a class method to BTWeakTimerTarget of the form +scheduledTimerWithTimeInterval:target:selector:... to create a neater form of that code. You'll probably want to expose the real NSTimer so that you can invalidate it, otherwise the rules established will be:

*

*the real target isn't retained by the timer;

*the timer will fire once after the real target has begun (and probably completed) deallocation, but that firing will be ignored and the timer invalidated then.

A: In Swift I've defined a WeakTimer helper class:
/// A factory for NSTimer instances that invoke closures, thereby allowing a weak reference to its context.
struct WeakTimerFactory {
  class WeakTimer: NSObject {
    private var timer: NSTimer!
    private let callback: () -> Void

    private init(timeInterval: NSTimeInterval, userInfo: AnyObject?, repeats: Bool, callback: () -> Void) {
      self.callback = callback
      super.init()
      self.timer = NSTimer(timeInterval: timeInterval, target: self, selector: "invokeCallback", userInfo: userInfo, repeats: repeats)
    }

    func invokeCallback() {
      callback()
    }
  }

  /// Returns a new timer that has not yet executed, and is not scheduled for execution.
  static func timerWithTimeInterval(timeInterval: NSTimeInterval, userInfo: AnyObject?, repeats: Bool, callback: () -> Void) -> NSTimer {
    return WeakTimer(timeInterval: timeInterval, userInfo: userInfo, repeats: repeats, callback: callback).timer
  }
}

And then you can use it like such:
let timer = WeakTimerFactory.timerWithTimeInterval(interval, userInfo: userInfo, repeats: repeats) { [weak self] in
  // Your code here...
}

The returned NSTimer has a weak reference to self, so you can call its invalidate method in deinit.

A: iOS 10 and macOS 10.12 "Sierra" introduced a new method, +scheduledTimerWithTimeInterval:repeats:block:, so you could capture self weakly simply as:
__weak MyClass* weakSelf = self;
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer* t) {
    MyClass* _Nullable strongSelf = weakSelf;
    [strongSelf doSomething];
}];

Equivalence in Swift 3:
_timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.doSomething()
}

If you still need to target iOS 9 or below (which you should at this moment), this method cannot be used, so you would still need to use code in the other answers.

A: It doesn't matter that weakSelf is weak, the timer still retains the object so there's still a retain cycle. Since a timer is retained by the run loop, you can (and I suggest to ) hold a weak pointer to the timer:
NSTimer* __weak timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target: self selector:@selector(tick) userInfo:nil repeats:YES];

About invalidate you're way of doing is correct.

A: If you are not that concerned about the millisecond accuracy of the timer events, you could use dispatch_after & __weak instead of NSTimer to do this. Here's the code pattern:
- (void) doSomethingRepeatedly
{
    // Do it once
    NSLog(@"doing something …");

    // Repeat it in 2.0 seconds
    __weak typeof(self) weakSelf = self;
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [weakSelf doSomethingRepeatedly];
    });
}

No NSTimer @property, no invalidate/runloop stuff and no proxy object, just a simple clean method.
The downside of this approach is that (unlike NSTimer) the execution time of the block (containing [weakSelf doSomethingRepeatedly];) will impact scheduling of the events.

A: If you are using Swift here is an auto-cancelling timer:
https://gist.github.com/evgenyneu/516f7dcdb5f2f73d7923
The timer cancels itself automatically on deinit.
var timer: AutoCancellingTimer? // Strong reference

func startTimer() {
  timer = AutoCancellingTimer(interval: 1, repeats: true) {
    print("Timer fired")
  }
}

A: Swift 4 version. Invalidate must be called before the dealloc.
class TimerProxy {

    var timer: Timer!
    var timerHandler: (() -> Void)?

    init(withInterval interval: TimeInterval, repeats: Bool, timerHandler: (() -> Void)?) {
        self.timerHandler = timerHandler
        timer = Timer.scheduledTimer(timeInterval: interval,
                                     target: self,
                                     selector: #selector(timerDidFire(_:)),
                                     userInfo: nil,
                                     repeats: repeats)
    }

    @objc func timerDidFire(_ timer: Timer) {
        timerHandler?()
    }

    func invalidate() {
        timer.invalidate()
    }
}

Usage
func  startTimer() {
    timerProxy = TimerProxy(withInterval: 10,
                            repeats: false,
                            timerHandler: { [weak self] in
                                self?.fireTimer()
    })
}

@objc func fireTimer() {
    timerProxy?.invalidate()
    timerProxy = nil
}

A: With theory and practice.Tommy's solution is not work.
Theoretically,__weak instance is as the parameter,In the implementation of
[NSTimer scheduledTimerWithTimeInterval:target:selector: userInfo: repeats:],

target will be retained still.
You can implement a proxy ,which hold the weak reference and forward selector calling to self , and then pass the proxy as the target. Such as YYWeakProxy.

A: the answer in very simple. for example you can try this:
@interface Person : NSObject
@property(nonatomic, strong) DemoViewController_19 *vc;
@end

@implementation Person
@end

@interface DemoViewController_19 ()
@property(nonatomic, strong) Person *person;
@end

@implementation DemoViewController_19

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.person = [Person new];
    __weak typeof(self) weaks = self;
    self.person.vc = weaks;
}

@end

After run you can see vc dealloc is not called. It depends on Person's property of strong attribute.


text:
Q: VBScript exit code 3010 for SCCM 2012 I am writing a vbscript to install a .exe application. Script works fine except that once the script is completed I need SCCM 2012 to get a exit code of 3010 so that it would schedule a restart of the PC.
The .exe when run with silent switch suppresses the reboot but the application won't work until restarted. Could you help with a vbscript to return 3010 once setup is finished.

A: If your script runs under cscript.exe, use WScript.Quit:
copy con 27878706.vbs
WScript.Quit 3010
^Z
        1 file(s) copied.

cscript 27878706.vbs

echo %ERRORLEVEL%
3010


text:
Q: C++: set value to floating point variable by bits I have a large message which must be initialized to default values. The message is a structure with many sub-structures, enums, etc. I have an automatically generated description file of the message, which contains the field-by-field parse of the message: field start byte, start bit, length, type, default value.
I've implemented a mechanism which treats the message as a bits buffer and initializes it according to the description file. But.... I have a problem with floating point defaults.
How do I make the automation of setting floating point variable bitwise?
Thanks!

A: Well, I've managed to solve it by myself.
Assume the following:
MSG_STRUCT_TYPE OutputMsg; // e.g.750 bytes
int startByte = 28; // the start byte of floating point field in the message
float defVal = -1.75f; // the default value for the field above

Now, using the reinterpret_cast we can do the following manipulation:
unsigned char* bytes_to_set = reinterpret_cast<unsigned char*>(&defVal);
unsigned char* msgBuff = reinterpret_cast<unsigned char*>(&OutputMsg);
*reinterpret_cast<float*>(&msgBuf[startByte]) = *reinterpret_cast<float*>(bytes_to_set);

That do the job.

After implementing and checking  njuffa's comment bellow, I'm adding it as another (simplier and cleaner) answer:
unsigned char* msgBuff = reinterpret_cast<unsigned char*>(&OutputMsg);
memcpy(&msgBuf[startByte], &defVal, sizeof(float);


text:
Q: How to prove $(p \to (p \lor q)) \equiv\operatorname{True}$ I know how to prove the expression $(p \to (p \lor q))$ being a tautology using truth table. I would also like to know how to prove it using algebraic methods.
Thanks in advance.

A: $$\begin{align}(p\to(p\lor q))&\equiv(\bar{p}\lor(p\lor q))\\&\equiv((\bar{p}\lor p)\lor q)\\&\equiv(\top\lor q)\\&\equiv\top\end{align}$$
Therefore, $$(p → (p ∨ q))$$ is a tautology.


text:
Q: PHP POST variable not defined when using Chrome + XHR This question is nearly identical to the year-old unanswered question:
HTTP-POST XHR not working in chrome.
I was hoping to find a solution and can offer more details than the original question.
Background
I have a sever-side php script that is supposed to take POST data from a form or XHR request. When I test the site using a form for submission, it works in Chrome and IE9. However, when I generate the request using XHR, the php POST variable is undefined when using Chrome on the client side. This behavior is inconsistent: about 1 in 20 tries, the php does accept the data.
I have checked the php://input stream and see that the post data is being sent to server in all cases; and note that a small few of the HTTP headers ($_SERVER) are different between test cases.
Code
Server side:
<?php
   echo file_get_contents("php://input") . "\n";
   print_r($_SERVER);
   print_r($_POST);
?>

Client side form version (Chrome and IE9 both work)
<form action="scriptName.php" method="post">
      Field: <input type="text" name="myField"><br>
      <input type="submit" value="Submit">
</form>

Client side XHR version (IE9 always works, Chrome works about 5% of time)
<script>
function postToURL(url,data)
{
  // Typical XHLHttpRequest declarations are removed for brevity
  //  - checks browser type and declares xmlhttp accordingly
  //  - defines a onreadystatechange handle

    xmlhttp.open("POST",url,false);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
}
</script>
...
<form>
<button type="button" onClick="postToURL('scriptname.php','myField=test');">
Test
</button>
</form>

Output
In all cases the request body data (php://input) returns the same value.
The headers are mostly the same, but Chrome adds an [HTTP_PRAGMA] => no-cache in XHR mode
The $_POST variable is defined  as [myField] => test except in the Chrome + XHR case.
Questions
Where is the problem likely occurring? Is there something wrong with the HTTP headers possibly, or should I be looking server-side. Any ideas?

A: Place this code in the first line of your page
<?php ob_start(); error_reporting(E_ALL & ~E_NOTICE & ~8192); ?>
<!-- Ignore Errors , Header Sent Report -->

and this code in the last line of your page
<!-- Ignore Header Sent Error -->
<?php ob_flush(); ?>
<!-- Ignore Header Sent Error -->

i hope that helps you


text:
Q: Test for external undefined references in Linux Is there a built in linux utility that I can use to test a newly compiled shared library for external undefined references?  Gcc seems to be intelligent enough to check for undefined symbols in my own binary, but if the symbol is a reference to another library gcc does not check at link time.  Instead I only get the message when I try to link to my new library from another program.
It seems a little silly to get undefined reference messages in a library when I am compiling a different project so I want to know if I can do a check on all references internal and external when I build the library not when I link to it.
Example error:
make -C  UnitTests debug
make[1]: Entering directory `~/projects/Foo/UnitTests`
g++ [ tons of objects ] -L../libbar/bin -lbar -o UnitTests
libbar.so: undefined reference to `DoSomethingFromAnotherLibrary`
collect2: ld returned 1 exit status
make[1]: *** [~/projects/Foo/UnitTests] Error 1

A: Usually, undefined references are allowed when linking shared objects, but you can make the linker generate an error if there are undefined symbols in the object files that you are linking to create the shared library by supplying -z defs to the linker (or equivalently -Wl,-z,defs in the gcc command that calls the linker).


text:
Q: sftp Broken pipe Couldn't read packet: Connection reset by peer I am trying to setup a sftp account to a specific folder. I have created a group ftpaccess and user testuser with home directory as seen here:
sudo addgroup ftpaccess

sudo useradd -d /home/forge/mydomain.com/downloads -m testuser -g ftpaccess -s /bin/false

sudo passwd testuser

sudo chown root:root /home/forge/mydomain.com/downloads

sudo chmod 755 /home/forge/mydomain.com/downloads

Then I have created an transfers directory inside testuser home folder:
sudo mkdir /home/forge/mydomain.com/downloads/transfers

sudo chown testuser:ftpaccess /home/forge/mydomain.com/downloads/transfers

Then I have setup sshd_config like this (rules added to the end of file):
# SFTP account
Subsystem sftp internal-sftp
Match group ftpaccess
ChrootDirectory %h
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
PasswordAuthentication yes

Now trying to sftp with this user sftp testuser@localhost but I get error:
packet_write_wait: Connection to 127.0.0.1 port 22: Broken pipe
Couldn't read packet: Connection reset by peer

What am I doing wrong?

A: Please try moving Subsystem sftp internal-sftp line from your existing block to # override default of no subsystems in sshd_config
It worked for me.


text:
Q: How do different kinds of vacuum pick-up tools compare? My company has extensive experience assembling through-hole PCBs, but relatively little experience with SMT. I've just been introduced to the idea of vacuum pick-up tools for SMT components. (Examples here.) This looks like a huge improvement over tweezers! There seems to be quite some variation in these tools. There are unpowered squeeze bulb models, battery powered models, and AC models. Cost ranges from $5 to $625. (More if you get a manual pick-and-place, but I'm not looking at those right now.)
What should I look for in these tools? What specs have an effect on the results during use?

A: I have a vacuum pickup tool with the pen pickup.  It uses the vacuum finger release method.  I don't recommend it.  I recommend some type of foot operated system, perhaps like this.  Fine pitch placement is a pain to do because the item will shift when you release the hole.
I wouldn't even consider one of the bulb type systems for reasons listed above.
You will probably still end up using a tweezers for small parts, as the rubber doesn't want to release.  It might help if the suction is turned off by foot petal, but in a manual operation there is enough suction with the finger off the hole to keep the part on the tip.  With or without rubber it wants to just vacuum your 0603 parts into oblivion.
My latest favorite method for placing IC's is to wet the end of a Q-tip, and let surface tension hold the part, once it hits lead paste it releases.
If you can set the vacuum level on the machine that would also work, just set it enough to hold the part until the paste tacks it down.  I do that with my finger on my current setup and works better than manually releasing.


text:
Q: Greasemonkey replace unityObject source in webpage I'm completely new to Greasemonkey, and I searched for quite a bit looking for what I want to do and didn't find anything.  I'm doing some whitehat hacking for this browser-based Unity FPS, and I'm trying to make the webpage embed a direct-linked edited copy of the game file instead of the normal game client.
Specifically, I'm trying to change the URL in the second attribute of the UnityObject.embedUnity() function on line 335 of the source of this page. I figure Greasemonkey is the way to go with it.
My confusion is coming from the fact that viewing the source (ctrl+u) shows this source in a javascript function, but using the inspector in dev tools shows the result of the function in an embed tag. I'm not sure which to try to account for in my Greasemonkey script. I don't have the direct link file up yet, but I tried this script (which didn't work) (google is just a placeholder to see if the text replacement works):
var tags = document.getElementsByTagName('embed');
tags[0].src = tags[0].src.replace('http://oldurl.com', 'http://newurl.com')
How would I go about writing a script to do this?

A: That embed element is inserted by Unity Player js code residing inside <script> tag of the page, which is executed automatically when the browser parses it.
Firefox still has beforescriptexecute event you can use to change that script before it runs:
document.addEventListener("beforescriptexecute", replacePlayer, true);
function replacePlayer(e) {
    var lookFor = 'http://data.warmerise.com/Warmerise/Production/Warmerise.unity3d?5.7.5';
    var replaceWith = 'http://google.com';
    if (e.target.text.indexOf(lookFor) > 0) {
        e.target.text = e.target.text.replace(lookFor, replaceWith);
    }
}


text:
Q: Unresolved externals error - Visual C++ using FTD2XX.h I am fairly new to C++ programming, so please bear with me.  I am writing a small application in visual studio that would be used to communicate with an FTDI module (UM232H high speed USB module).  FTDI provides the D2XX drivers for this module and is readily available on their website.  Right now the program I have is very simple.  It is calling a function called FT_Open (ftd2xx.h) to simply open the device and top check to see if the device is connected to the computer.
However right now I keep getting the error LNK2019, unresolved external symbol.  Now I did read through the application note provide by Visual Studio website but I still can not seem to resolve my error.  I think I am making a silly mistake and would like some guidance from you guys, if you guys could help me out.
I have provide my code as well as the header file (ftd2xx.h) that was provide from the FTDI website.
Main Program:
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "ftd2xx.h"
#include <iostream>

using namespace std;
FT_HANDLE ftHandle;
FT_STATUS ftStatus;

int main(){
    ftStatus =  FT_Open(0,&ftHandle);

    if (ftStatus == FT_OK) {
        cout << "hello world";
    // FT_Open OK, use ftHandle to access device
    }
    else {
    // FT_Open failed
    }
    return 0;
}

ftd2xx.h:
#include "windows.h"
/*#include <stdarg.h>
#include <windef.h>
#include <winnt.h>
#include <winbase.h>*/

/*++
Copyright © 2001-2011 Future Technology Devices International Limited

THIS SOFTWARE IS PROVIDED BY FUTURE TECHNOLOGY DEVICES INTERNATIONAL LIMITED "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
FUTURE TECHNOLOGY DEVICES INTERNATIONAL LIMITED BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

FTDI DRIVERS MAY BE USED ONLY IN CONJUNCTION WITH PRODUCTS BASED ON FTDI PARTS.

FTDI DRIVERS MAY BE DISTRIBUTED IN ANY FORM AS LONG AS LICENSE INFORMATION IS NOT MODIFIED.

IF A CUSTOM VENDOR ID AND/OR PRODUCT ID OR DESCRIPTION STRING ARE USED, IT IS THE
RESPONSIBILITY OF THE PRODUCT MANUFACTURER TO MAINTAIN ANY CHANGES AND SUBSEQUENT WHQL
RE-CERTIFICATION AS A RESULT OF MAKING THESE CHANGES.

Module Name:
ftd2xx.h

Abstract:
Native USB device driver for FTDI FT232x, FT245x, FT2232x and FT4232x devices
FTD2XX library definitions

Environment:
kernel & user mode
--*/

#ifndef FTD2XX_H
#define FTD2XX_H

// The following ifdef block is the standard way of creating macros
// which make exporting from a DLL simpler.  All files within this DLL
// are compiled with the FTD2XX_EXPORTS symbol defined on the command line.
// This symbol should not be defined on any project that uses this DLL.
// This way any other project whose source files include this file see
// FTD2XX_API functions as being imported from a DLL, whereas this DLL
// sees symbols defined with this macro as being exported.

#ifdef FTD2XX_EXPORTS
#define FTD2XX_API __declspec(dllexport)
#else
#define FTD2XX_API __declspec(dllimport)
#endif

typedef PVOID   FT_HANDLE;
typedef ULONG   FT_STATUS;

//
// Device status
//
enum {
    FT_OK,
    FT_INVALID_HANDLE,
    FT_DEVICE_NOT_FOUND,
    FT_DEVICE_NOT_OPENED,
    FT_IO_ERROR,
    FT_INSUFFICIENT_RESOURCES,
    FT_INVALID_PARAMETER,
    FT_INVALID_BAUD_RATE,

    FT_DEVICE_NOT_OPENED_FOR_ERASE,
    FT_DEVICE_NOT_OPENED_FOR_WRITE,
    FT_FAILED_TO_WRITE_DEVICE,
    FT_EEPROM_READ_FAILED,
    FT_EEPROM_WRITE_FAILED,
    FT_EEPROM_ERASE_FAILED,
    FT_EEPROM_NOT_PRESENT,
    FT_EEPROM_NOT_PROGRAMMED,
    FT_INVALID_ARGS,
    FT_NOT_SUPPORTED,
    FT_OTHER_ERROR,
    FT_DEVICE_LIST_NOT_READY,
};

#define FT_SUCCESS(status) ((status) == FT_OK)
//
// FT_OpenEx Flags
//
#define FT_OPEN_BY_SERIAL_NUMBER    1
#define FT_OPEN_BY_DESCRIPTION      2
#define FT_OPEN_BY_LOCATION         4

//
// FT_ListDevices Flags (used in conjunction with FT_OpenEx Flags
//

#define FT_LIST_NUMBER_ONLY         0x80000000
#define FT_LIST_BY_INDEX            0x40000000
#define FT_LIST_ALL                 0x20000000

#define FT_LIST_MASK (FT_LIST_NUMBER_ONLY|FT_LIST_BY_INDEX|FT_LIST_ALL)
//
// Baud Rates
//
#define FT_BAUD_300         300
#define FT_BAUD_600         600
#define FT_BAUD_1200        1200
#define FT_BAUD_2400        2400
#define FT_BAUD_4800        4800
#define FT_BAUD_9600        9600
#define FT_BAUD_14400       14400
#define FT_BAUD_19200       19200
#define FT_BAUD_38400       38400
#define FT_BAUD_57600       57600
#define FT_BAUD_115200      115200
#define FT_BAUD_230400      230400
#define FT_BAUD_460800      460800
#define FT_BAUD_921600      921600
//
// Word Lengths
//
#define FT_BITS_8           (UCHAR) 8
#define FT_BITS_7           (UCHAR) 7
//
// Stop Bits
//
#define FT_STOP_BITS_1      (UCHAR) 0
#define FT_STOP_BITS_2      (UCHAR) 2
//
// Parity
//
#define FT_PARITY_NONE      (UCHAR) 0
#define FT_PARITY_ODD       (UCHAR) 1
#define FT_PARITY_EVEN      (UCHAR) 2
#define FT_PARITY_MARK      (UCHAR) 3
#define FT_PARITY_SPACE     (UCHAR) 4
//
// Flow Control
//
#define FT_FLOW_NONE        0x0000
#define FT_FLOW_RTS_CTS     0x0100
#define FT_FLOW_DTR_DSR     0x0200
#define FT_FLOW_XON_XOFF    0x0400

//
// Purge rx and tx buffers
//
#define FT_PURGE_RX         1
#define FT_PURGE_TX         2
//
// Events
//
typedef void (*PFT_EVENT_HANDLER)(DWORD,DWORD);
#define FT_EVENT_RXCHAR         1
#define FT_EVENT_MODEM_STATUS   2
#define FT_EVENT_LINE_STATUS    4

//
// Timeouts
//
#define FT_DEFAULT_RX_TIMEOUT   300
#define FT_DEFAULT_TX_TIMEOUT   300

//
// Device types
//
typedef ULONG   FT_DEVICE;

enum {
    FT_DEVICE_BM,
    FT_DEVICE_AM,
    FT_DEVICE_100AX,
    FT_DEVICE_UNKNOWN,
    FT_DEVICE_2232C,
    FT_DEVICE_232R,
    FT_DEVICE_2232H,
    FT_DEVICE_4232H,
    FT_DEVICE_232H,
    FT_DEVICE_X_SERIES
};

//
// Bit Modes
//
#define FT_BITMODE_RESET                    0x00
#define FT_BITMODE_ASYNC_BITBANG            0x01
#define FT_BITMODE_MPSSE                    0x02
#define FT_BITMODE_SYNC_BITBANG             0x04
#define FT_BITMODE_MCU_HOST                 0x08
#define FT_BITMODE_FAST_SERIAL              0x10
#define FT_BITMODE_CBUS_BITBANG             0x20
#define FT_BITMODE_SYNC_FIFO                0x40

//
// FT232R CBUS Options EEPROM values
//
#define FT_232R_CBUS_TXDEN                  0x00    //  Tx Data Enable
#define FT_232R_CBUS_PWRON                  0x01    //  Power On
#define FT_232R_CBUS_RXLED                  0x02    //  Rx LED
#define FT_232R_CBUS_TXLED                  0x03    //  Tx LED
#define FT_232R_CBUS_TXRXLED                0x04    //  Tx and Rx LED
#define FT_232R_CBUS_SLEEP                  0x05    //  Sleep
#define FT_232R_CBUS_CLK48                  0x06    //  48MHz clock
#define FT_232R_CBUS_CLK24                  0x07    //  24MHz clock
#define FT_232R_CBUS_CLK12                  0x08    //  12MHz clock
#define FT_232R_CBUS_CLK6                   0x09    //  6MHz clock
#define FT_232R_CBUS_IOMODE                 0x0A    //  IO Mode for CBUS bit-bang
#define FT_232R_CBUS_BITBANG_WR             0x0B    //  Bit-bang write strobe
#define FT_232R_CBUS_BITBANG_RD             0x0C    //  Bit-bang read strobe

//
// FT232H CBUS Options EEPROM values
//
#define FT_232H_CBUS_TRISTATE               0x00    //  Tristate
#define FT_232H_CBUS_TXLED                  0x01    //  Tx LED
#define FT_232H_CBUS_RXLED                  0x02    //  Rx LED
#define FT_232H_CBUS_TXRXLED                0x03    //  Tx and Rx LED
#define FT_232H_CBUS_PWREN                  0x04    //  Power Enable
#define FT_232H_CBUS_SLEEP                  0x05    //  Sleep
#define FT_232H_CBUS_DRIVE_0                0x06    //  Drive pin to logic 0
#define FT_232H_CBUS_DRIVE_1                0x07    //  Drive pin to logic 1
#define FT_232H_CBUS_IOMODE                 0x08    //  IO Mode for CBUS bit-bang
#define FT_232H_CBUS_TXDEN                  0x09    //  Tx Data Enable
#define FT_232H_CBUS_CLK30                  0x0A    //  30MHz clock
#define FT_232H_CBUS_CLK15                  0x0B    //  15MHz clock
#define FT_232H_CBUS_CLK7_5                 0x0C    //  7.5MHz clock

//
// FT X Series CBUS Options EEPROM values
//
#define FT_X_SERIES_CBUS_TRISTATE           0x00    //  Tristate
#define FT_X_SERIES_CBUS_RXLED              0x01    //  Tx LED
#define FT_X_SERIES_CBUS_TXLED              0x02    //  Rx LED
#define FT_X_SERIES_CBUS_TXRXLED            0x03    //  Tx and Rx LED
#define FT_X_SERIES_CBUS_PWREN              0x04    //  Power Enable
#define FT_X_SERIES_CBUS_SLEEP              0x05    //  Sleep
#define FT_X_SERIES_CBUS_DRIVE_0            0x06    //  Drive pin to logic 0
#define FT_X_SERIES_CBUS_DRIVE_1            0x07    //  Drive pin to logic 1
#define FT_X_SERIES_CBUS_IOMODE             0x08    //  IO Mode for CBUS bit-bang
#define FT_X_SERIES_CBUS_TXDEN              0x09    //  Tx Data Enable
#define FT_X_SERIES_CBUS_CLK24              0x0A    //  24MHz clock
#define FT_X_SERIES_CBUS_CLK12              0x0B    //  12MHz clock
#define FT_X_SERIES_CBUS_CLK6               0x0C    //  6MHz clock
#define FT_X_SERIES_CBUS_BCD_CHARGER        0x0D    //  Battery charger detected
#define FT_X_SERIES_CBUS_BCD_CHARGER_N      0x0E    //  Battery charger detected inverted
#define FT_X_SERIES_CBUS_I2C_TXE            0x0F    //  I2C Tx empty
#define FT_X_SERIES_CBUS_I2C_RXF            0x10    //  I2C Rx full
#define FT_X_SERIES_CBUS_VBUS_SENSE         0x11    //  Detect VBUS
#define FT_X_SERIES_CBUS_BITBANG_WR         0x12    //  Bit-bang write strobe
#define FT_X_SERIES_CBUS_BITBANG_RD         0x13    //  Bit-bang read strobe
#define FT_X_SERIES_CBUS_TIMESTAMP          0x14    //  Toggle output when a USB SOF token is received
#define FT_X_SERIES_CBUS_KEEP_AWAKE         0x15    //

// Driver types
#define FT_DRIVER_TYPE_D2XX     0
#define FT_DRIVER_TYPE_VCP      1

#ifdef __cplusplus
extern "C" {
#endif

    FTD2XX_API
        FT_STATUS WINAPI FT_Open(
        int deviceNumber,
        FT_HANDLE *pHandle
        );

--Rest of the of the header file was omitted because of the limit to the number of characters I could write.
Sorry for the large amount of code I provided here, I just wanted to be sure that I provided everything that I possibly could.  Let me know if I would need to provide the rest of the header file.

A: Maybe it is bit later for an answer.
I got same error with old outdated ftd2xx.lib file.
Afetr adding new ftd2xx.lib, ftd2xx.dll and ftd2xx.h files, cleaning and rebuilding the project a problem was solved.

A: Have you made sure to include the .lib your compiler will need to link against? Along with any header files, they probably provided a .lib and/or .dll.

A: If you use the static version of the .lib, you will have to define FTD2XX_STATIC to the preprocessor, as explained in the documentation (chapter 2.4 of Instructions on Including the D2XX
Driver in a VS Express Project).


text:
Q: Implement RSA Public / Private key decryption in .NET to Java / Spring I'm trying to port an application from .NET to Spring 4 (Java). How do I do a password decryption in Java which was previously encrypted usin .NET RSACryptoServiceProvider? I am from a Java background.
I have a privatekey.xml file from .NET. This is the private key sampel code:
<RSAKeyValue>
<Modulus>dfgkjkdfg99444</Modulus>
<Exponent>ABCD</Exponent>

dadskfkkeej3434j==

<Q>sdakfksa/sdfd/sdf3wfsd==</Q>
<DP>sdERfdsf333==</DP>
<DQ>sdfsd222sdfEWEf==</DQ>
<InverseQ>kadkfimmds+/sdkks+/sdfsdkKKD==</InverseQ>
<D>sdfsadfsadfsadfdsafasdfsadfsadfdsafdsf=</D>
</RSAKeyValue>

Question/s:
Where is the actual private key in this?
Can I use it as a salt to decrypt the encrypted text? How can I write a decryption function in Java using this privatekey? Is there already a function for this in Java which accepts these param? Any examples?
I've gone through many theoretical articles about RSA already. But was not helpful in understanding this scenario. So sample codes specifically to handle this scenario in java, counter-part examples in java, links to useful articles etc. will be very helpful.

A: You've got an XML containing the elements that make up the private key. These elements are base 64 encoded. The base 64 decodes to byte arrays. These byte arrays in turn represent big or little integer encoded numbers. All the values together make up the private key.
Obviously you've altered the values themselves, so it would be rather tricky to go any further than this.
So basically you've got the following steps you need to do:

*

*parse the XML;

*retrieve the encoded elements;

*base 64 decode those elements into a byte array;

*convert the arrays into BigInteger values

*put the values in a RSAPrivateCrtKeySpec

*feed the spec into an "RSA" KeyFactory.

As you also have the private D value you can also use RSAPrivateyKeySpec but your resulting RSA operation is possibly slower.


text:
Q: Sqlite copy data from temp table to another with conflict i have db sqlite with main table and temp table. I want to import data from text file and then i want to insert data from temp table to main table.
INSERT INTO table(key) SELECT src.key FROM temp as src
ON CONFLICT (table.key) DO UPDATE SET to_insert = 0, to_delete =0;

When i am trying run this query then sqlite throw me this error.

Query 1 ERROR: near "DO": syntax error

Is possible insert data from another table with conflicts?

A: The select statement needs a where clause:
insert into mytable(key)
select key from temp where true
on conflict (key) do update set to_insert = 0, to_delete =0;

This pitfall is documented as parsing ambiguity (emphasis mine):

When the INSERT statement to which the UPSERT is attached takes its values from a SELECT statement, there is a potential parsing ambiguity. The parser might not be able to tell if the ON keyword is introducing the UPSERT or if it is the ON clause of a join. To work around this, the SELECT statement should always include a WHERE clause, even if that WHERE clause is just WHERE true.


text:
Q: "Persistence" in C#. How to store objects between procedures? I have GUI that allows an user to create and modify a point object. I need to store a list of these points to insert at a specific drawing.
Here's how I came up with it:
In the form code, I opened a private property List<Points> and I manipulate it directly inside form code. Is this the correct way to handle?
Something like:
public partial class TesteInterface_AdicionarVertice : Form {

   public List<VerticeDNPM> listaVertices;

   public TesteInterface_AdicionarVertice()
   {
      InitializeComponent();
      listaVertices = new List<VerticeDNPM>();
   }

}

So, what do you think about this design? Is there a better way to do it?

Thanks for all thoughs.

I will make the list read-only. thanks for that idea.
The real thing here is this: I have a button which creates points, and another that creates polygons from points.
I need to have a way to get the List of points at the time the user chooses to create that certain polygon. That is basically what i am asking :P
I though to use a class property (in this case List) to store temp points, until the user creates the polygon. Is this a valid approach?

A: Sorry for that. The correct code is:
public partial class TesteInterface_AdicionarVertice : Form
{
    public List<VerticeDNPM> listaVertices;

    public TesteInterface_AdicionarVertice()
    {
        InitializeComponent();
        listaVertices = new List<VerticeDNPM>();
    }

}

A: I'm not really sure what you are asking.  Aside from moving your non-UI code out of the UI, I would change the list creation to a readonly field like so:
public partial class TesteInterface_AdicionarVertice : Form {
    private readonly List<VerticeDNPM> listaVertices = new List<VerticeDNPM>();
    public List<VerticeDNPM> Vertices {get; set;};

    public TesteInterface_AdicionarVertice()
    {
        InitializeComponent();
    }
}

A: Assuming that you include the appropriate namespace inclusions and class definitions, then what you have posted is valid and does not clearly violate any best practices (unless you count naming conventions, in which case VerticeDNPM should be VerticeDnpm according to Microsoft's naming guidelines).  However, in order critique your approach from a design standpoint, you'd really need to provide more information.

A: I wouldn't make your list public. Then you never know who is modifying it. Make your list private, then expose it as read only.
You can read more about it here. You can also run your code through FxCop. I'm sure it would pick this up.

A: Thanks for all thoughs.
I will make the list read-only. thanks for that idea.
The real thing here is this:
I have a button which creates points, and another that creates polygons from points.
I need to have a way to get the List of points at the time the user chooses to create that certain polygon. That is basically what i am asking :P
I though to use a class property (in this case List) to store temp points, until the user creates the polygon. Is this a valid approach?

A: I agree that making your list public is a bad idea as then a consumer of the class can modify the actual list object itself, which is not what you want.  Instead you want to expose it as a read-only property thereby allowing consumers to access the list contents.
public partial class TestInterface_ADicionaryVertice : Form
{
    private List<VerticeDNPM> listVertices = new List<VerticeDNPM>();
    public List<VerticeDNPM> { get { return listVertices; } }

    public TestInterface_ADiciontaryVertice()
    {
        InitializeComponent();
        ...manipulate list of points here...
    }
}

In this way you are modifying a private list of points in your code while still allowing a consumer (presumably something that receives the form as a parameter?) to access the list of points and read through it.
Two additional thoughts:
 1) If the only consumer is deriving from this form instead of operating on it (receiving it as a parameter somewhere) then consider making the list protected instead.
 2) If you do not want the list to be modified by any consumer (i.e. the list of points can't change once you're done manipulating them) then consider exposing an enumerator for the list instead of the list itself.  This way someone can enumerate the points but can't change them.
Example:
   public IEnumerator GetPoints { get { return listVertices.GetEnumerator(); } }

A: If you give a user access to a read-only property and return the original list, then the a consumer could still modify that list.  The List is still a reference type, so the property is returning a pointer to the list.  A true read-only property will create a copy of the list inside the 'get' and return that instead.


text:
Q: showing name of Column in text view in my recycle view , when user clicks on any of items, an alert dialog will show up and shows the item name and some buttons for edit,delete and..., how can I get my Item name and show it in alert dialog?
I tried set text, cursor and many things but non of the worked
here is the class i am working on
package com.example.hozoor;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Classes extends AppCompatActivity {
    Cursor cursor;
    TextView add;
    Database database;
    private SQLiteDatabase sqLiteDatabase;
    private class_adaptor mclassadaptor;
    RecyclerView.LayoutManager layoutManager;
    String nameclass;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_classes );
        Toolbar toolbar = findViewById ( R.id.toolbar );
        setSupportActionBar ( toolbar );

        Database mdatabase = new Database ( this );
        sqLiteDatabase = mdatabase.getWritableDatabase ();
        RecyclerView recyclerView = findViewById ( R.id.rec_1 );
        recyclerView.setLayoutManager ( new LinearLayoutManager ( this ,LinearLayoutManager.VERTICAL,false ) );
        mclassadaptor = new class_adaptor ( this, getAllItem () );

        recyclerView.setAdapter(mclassadaptor);

        FloatingActionButton fab = findViewById ( R.id.fab );
        fab.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder ( Classes.this );
                View view1 = getLayoutInflater ().inflate ( R.layout.custom_dialog_add_calss, null );

                final EditText New_kelas = (TextInputEditText) view1.findViewById ( R.id.name_class );
                TextView afzodn = (TextView) view1.findViewById ( R.id.btn_afzodn_new_class );
                final TextView cancel = (TextView) view1.findViewById ( R.id.btn_cancel_new_class );

                afzodn.setOnClickListener ( new View.OnClickListener () {
                    @Override
                    public void onClick(View view) {

                        if (New_kelas.getText().toString().trim().length()==0 ) {

                        } else {
                            Toast.makeText ( Classes.this, "نام کلاس را وارد کنید", Toast.LENGTH_SHORT ).show ();
                            String name=New_kelas.getText().toString();
                            ContentValues cv=new ContentValues();
                            cv.put(Database.COLUMN_NAME,name);

                            sqLiteDatabase.insert(Database.TABLE_NAME,null,cv);

                            mclassadaptor.swapcursor(getAllItem());

                            New_kelas.getText().clear();
                        }

                    }
                } );

                cancel.setOnClickListener ( new View.OnClickListener () {
                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent ( getApplicationContext (), Classes.class );
                        startActivity ( intent );
                        finish ();
                    }
                } );

                builder.setView ( view1 );
                AlertDialog dialog = builder.create ();
                dialog.show ();

}
        } );
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager ( layoutManager );
        recyclerView.addOnItemTouchListener(new rec_listener(getApplicationContext(), recyclerView, new rec_listener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent =new Intent(getApplicationContext(),Situation.class);
                startActivity(intent);
            }

            @SuppressLint("ResourceType")
            @Override
            public void onLongClick(View view, int position) {
                String id=cursor.getString ( cursor.getColumnIndex ( "_ID" ) );
                String name= (String) getText ( R.id.name_class );
                TextView name_kelas = findViewById ( R.id.txt_name_kelas );

                AlertDialog.Builder builder = new AlertDialog.Builder ( Classes.this );
                View view1 = getLayoutInflater ().inflate ( R.layout.custom_dialog_edit_delete_bikhial, null );
                EditText New_kelas = (TextInputEditText) view1.findViewById ( R.id.name_class );

               String Name= cursor.getColumnName ( Integer.parseInt ( id ) );
                name_kelas.setText ( Name );

                builder.setView ( view1 );
                AlertDialog dialog = builder.create ();
                dialog.show ();

            }
        }));

    }

    private Cursor getAllItem(){
        return sqLiteDatabase.query(
                Database.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                Database.COLUMN_TIMESTAMP+" DESC"

        );
}

}

I wanted my text view to show Column name

A: First of all make two alert dialog box,
first for adding value(name) and second for Show value(name).
shows Add alert dialog box in activity in which activity you want to add event, Save That event,
public void SaveEvent(String name) {
    databaseHelper.SaveEvent(name);
    databaseHelper.close();
    Toast.makeText(context, Name Saved!!", Toast.LENGTH_SHORT).show();
}

Call this method in onCreate activity of view and also initiate databasehelper class,
DatabaseHelper databaseHelper;

Call another alert box  dialog box  where you want to show details ,
and get all saved data in that view by,
final MyAdapter myAdapter = new MyAdapter(MainActivity.this,ShowName(name));
            recyclerView.setAdapter(myAdapter);
            eventRecyclerAdapter.notifyDataSetChanged();

set showname method in view
public void ShowName(String name) {
String name;
    SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
    Cursor cursor = databaseHelper.ShowDetail(name);
}

I hope this will help You!
Thanks!


text:
Q: how to put a bracket for a number in pascal triangle? Here's the question : highlight(by putting a bracket) the answer for C(n, k) in the triangle.
I have constructed my code for my 11 line pascal triangle. but i can't be able to highlight C(n, k).
Here's what I've done.
#include<stdio.h>

int recursive(int n, int k);

int main(void)
{
    int row, space, column, b, x, y;

    printf("Pascal triangle with 11 rows : \n");
    printf("Enter the row and column that you would like to highlight on the triangle : ");
    scanf("%d %d", &x, &y);

    if (x > 11)
    {
          printf("Error! The row entered must be smaller than 11! \n ");
    }

    else if (y > x)
    {
        printf("Error! Column CANNOT more than number of row!\n");
    }

    else
    {
        for(row = 0 ; row < 11 ; row++)
        {
            for(space = 30 - 3 * row ; space > 0 ; space--)
            {
                printf(" ");
            }

            for(column = 0;column <= row; column++)
            {
                {
                if(column == 0 || row == 0)
                {
                    b = 1;
                }
                else
                {
                    b = ( b * (row - column + 1)/column );
                }
                printf("%6d", b);
                }

                if(row == x-1 && column == y-1)
                {
                    printf("(%2d)",recursive( row , column ));
                }
                else
                {
                    printf("%d ",recursive( row , column ));
                }
            }
            printf("\n");

        }

    }

    return 0;
}

int recursive(int n,int k)
{
    if( k == 0 || k > n)
        return 0;
    else if( n == 1 && k == 1 )
        return 1;
    else
        return ( recursive( n - 1, k) + recursive( n - 1, k - 1) );
}

Can someone tell me where have I done wrong?

A: Since you're printing the first digit in a loop. You need to check if the iteration is the one you want to highlight (just like you did for the part where you print the second digit).
Instead of:
printf("%6d", b);

Change to:
if(row == x-1 && column == y-1){
    printf("(6%d", b);
}
else{
    printf("%6d", b);
}

Then change your original attempt (where you print last digits) to have a single closing parenthesis.
printf("%2d)",recursive( row , column ));


text:
Q: GitLab CI Runner with relative paths in main.tex I have a LaTeX document where I include another TeX file with a relative path like \include{../Meta/commands.tex}. If I compile it on my local machine all works fine.
Now I also want to use the CI feature of GitLab. I have my runner working in a way that following file gets compiled without an error.
\documentclass{article}
\begin{document}
  Hello World!
\end{document}

My .gitlab-ci.yml files looks like this:
compile_pdf:
  image: aergus/latex
  script:
      - latexmk -pdf -interaction=nonstopmode ./Test/main.tex
  artifacts:
    paths:
      - main.pdf
    expire_in: 1 week

If now the main.tex file contains a relative path to \include{../Meta/commands.tex}, then I get the following error:
Latexmk: Missing input file: '../Meta/commands.tex' from line
  '! LaTeX Error: File `../Meta/commands.tex' not found.'

Does anybody know how to resolve this unpleasant issue? Most likely I have to resolve the relative paths but I do not know how...
Thanks for any help!

A: It usually works best to run tex from the document directory, so
cd Test; latexmk main.tex

rather than
latexmk Test/main.tex


text:
Q: Why all attributes are prefixed? What is the design advantage to do this
<TextView
    android:layout_width="105px"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

and not this
<android:TextView
    layout_width="105px"
    layout_height="wrap_content"
    text="@string/hello"
    />

Is that android: prefix everywhere not a little bit to chatty?

A: In XML, attributes have to be prefixed in order to be in a namespace; they don't automatically pick up the namespace of the element.

A: android is a namespace prefix and it is used to tell that those attributes are in the XML namespace bound to that prefix. You should have a namespace declaration somewhere in your XML document which looks like xmlns:android = "the namespace URI here". It is quite unusual to prefix attributes but it is necessary when attributes of a given XML vocabulary are found in XML elements not belonging to that vocabulary because it avoids collisions.

A: Its xml references afaik, look at the top view and see the link.

A: Have never seen the second variant in use and don't really know if it works or not. If yes - I'm sure you can use it if you want.

A: I think the answer is: there is no advantage in this design. Which is why I've never seen anyone use it.


text:
Q: How to change the keyphrase in the pass program without reinitializing a pass store from scratch I'm using the pass application which I find really handy. I want to change the keyphrase (mother password). I had a look at the man page there but i'm not sure what to do. Do I have to use the init command?. Is it possible to change the passphrase without reinitializing a pass store from scratch? If yes which exact command should be done?
I tried the following from the comments:
Many thank for your comment
So I did the following:
$ gpg --list-secret-keys

/Users/user/.gnupg/pubring.kbx
-------------------------------
sec   ....
      ....
uid           [ultimate] firstnamelastname <firstnamelastname@mail.com>
ssb   ...

sec   ....
      ....
uid           [ultimate] Firstname Lastname <firstnamelastname@mail.com>
ssb   ...

Note the email adress is the same
There is no file ~/.gnupg/gpg.conf. I created a one and wrote default-key firstnamelastname in it and source it but got
gpg.conf:1: command not found: default-key

A: pass uses gpg to encrypt your password store.  To change the passphrase for pass, you need to change the passphrase for your gpg key.
e.g.
gpg --change-passphrase user-id


text:
Q: Frequency of fluctuations in power in an input power design circuit I am thinking about the following power design circuit in section 6.1 : http://www.arndaleboard.org/wiki/downloads/supports/BaseBoard_Specification_Arndale_Ver1_0.pdf
Is it possible to calculate how fast the fluctuations in power might be at most from this ? If I measure samples of the input current with 1ms intervals, would this be sufficient to get a fair precision of variations over time, or would the fluctuations that appear when the load varies "destroy" my readings ?
EDIT : Sorry, I meant to say that I measure the input current, not voltage! (I measure the voltage drop across a shunt resistor coupled in series with the input. I am trying to measure the board's power and energy consumption with low accuracy)

A: Your question is a little ambiguous. What does "power fluctuation" mean here?
Yes, you can calculate the frequency response of the two sections; the 5V input is a capacitor filtered part which turns into an RC filter (with the ESR of the capacitors.) The post-regulator part (3.3V?) is an LC filter. Knowing the values of the components, you can calculate the frequency response of the system. Additionally, you need to model the voltage regulator in that circuit, if you worry about the voltage out of that system. (Note that the regulator may introduce ringing in response to steps in power demand.)
But what does "power fluctuation" mean? The board may draw varying amounts of power with different workloads. This may affect the voltage of the input power supply if the source impedance is not zero. Exactly how quickly the power will vary depends both on the source impedance of your power supply, and the filtering section of the board power.
So, depending on the fluctuations in power demand of the board, you can characterize the system. If the board can go from demanding 1 mA, to demanding 10 A, in one microsecond, then that's a megahertz-range signal, and a millisecond sample will not be sufficient to show the ringing involved. In general, you're going to have a much better time just measuring the ringing as a result of steps in power demand using an oscilloscope, rather than trying to calculate it, as the ESR of capacitors and the response of the voltage regulator will not be very accurately characterized values.


text:
Q: Given $G:\mathbb{R}^3\to\mathbb{R}^3$, find $F$ such that $G=\operatorname{curl}(F)$ At my calculus II class we are studying multivariable functions and yesterday er talked about the curl operator (we used the definition in "usage" section here.
The typical exercise we got as homework, was like: given a function $F:\mathbb{R}^3\to\mathbb{R}^3$, compute $\operatorname{curl}(F)$ and so far so good. Today I got this homework which is exactly the opposite, i.e.
$$"\text{Let } \ G=\frac{x}{|x|^3}. \text{Find an example of } \ F:\mathbb{R}^3\to\mathbb{R}^3 \text{such that } \ G=\operatorname{curl}(F)."$$
The exercise was proposed for $G=\frac{x}{|x|^3}$ and $G=\frac{x}{|x|^2}$, so I guess there is a similar strategy.
Could someone please help me in find an example even in only one of the cases?
I am thinking to examples like $F(x)= x/|x|$, or to some powers, but it is not working.
Thank you.

A: The vector field
$$
G(x,y,z)=\frac{1}{(x^2+y^2+z^2)^{3/2}}\begin{pmatrix}x\\y\\z\end{pmatrix}\,,\quad\text{ on }\mathbb R^3\setminus\{0\},
$$
describes Coulomb's law and
Newton's law of universal gravitation and is mathematically interesting in many ways: It is rotation free and divergence free. A scalar function
whose gradient is $G$ is
$$
H(x,y,z)=-\frac{1}{(x^2+y^2+z^2)^{1/2}}\,.
$$
The divergence freeness of $G$ suggests that there should be a vector field $F$ whose curl is $G\,.$ It turns out that

*

*$F$ exists but cannot be defined on all of $\mathbb R^3\setminus\{0\}\,.$
This was briefly remarked in this answer. After some confusion on my side an finally learning it from Ted Shifrin I'd like to sum it up a bit: If $F$ is defined on all of $\mathbb R^3\setminus\{0\}$ one can apply Stokes' theorem to each hemisphere separately to conclude that the flux of $G$ through the whole unit sphere must be zero but this cannot happen because the flux of $G$ is
\begin{align}
\oint_{S^2}\hat{\mathbf{n}}\cdot G\,dS&=\oint_{S^2}\frac{\left(\begin{smallmatrix}x\\y\\z\end{smallmatrix}\right)}{(x^2+y^2+z^2)^{1/2}}\cdot \frac{\left(\begin{smallmatrix}x\\y\\z\end{smallmatrix}\right)}{(x^2+y^2+z^2)^{3/2}}\,dS\\
&=\int_0^{2\pi}\int_0^\pi \sin\theta\,d\theta\,d\varphi=4\pi\,.
\end{align}
To see that on the contrary Stokes' theorem leads to a flux of zero (assuming that $F$ is defined on all of $\mathbb R^3\setminus\{0\}$) note that the line integral of $F$ along the boundary of each hemisphere equals the flux of $\nabla\times F=G$ through that hemisphere. But these line integrals cancel out because of their opposite orientation which leads to zero flux. A contradiction.

*

*Consequently, when $F$ whose curl is $G$ exists there must be at least one point on one of the two hemispheres on which $F$ is not defined. An example for such an $F$ is
$$
F(x,y,z)=\frac1{r^2+rz}\begin{pmatrix}-y\\x\\0\end{pmatrix}\,,\quad r:=(x^2+y^2+z^2)^{1/2}\,,
$$
which is a simpler notation for the solution found here. This $F$ is defined for all $x,y,z\in\mathbb R^3$ except on the ray $z\le 0,x=y=0$ (where $r+z$ becomes zero) and
describes a clockwise circular motion around the $z$-axis and parallel to the $xy$-plane. A way to visualise it is to look at the speed of this motion
which is
$$
\|F\|=\frac{\varrho}{\varrho^2+z^2+z\sqrt{\varrho^2+z^2}}\,,\quad\varrho:=\sqrt{x^2+y^2}\,.
$$
The following picture shows this speed as a function of the distance $\varrho$ to the $z$-axis for various levels of $z\,.$ For  $z\le 0$ where $F$ is not defined on the $z$-axis the speed blows up when the $z$-axis is approached.

Another interesting picture shows the $[0,3\pi/2]$-sectors of the surfaces of constant speed $\|F\|\,.$
The blue surfaces has the slowest speed and the brown surface the highest.
These surfaces converge at the origin.

Further properties of $F\,:$

*

*The one-form
$$
\omega=\frac{-y\,dx+x\,dy}{r^2+rz}
$$
is closed if and only if $z=0\,.$ This follows from $(\nabla\times F)_3=\partial_xF_2-\partial_yF_1=G_3=z/r^3\,.$ For $z=0$ this form has interesting properties that I summarized here.

*On the unit sphere $S^2$ the speed of the integral curves can be written
more simply as
$$
\|F\|=\sqrt{\frac{1-z}{1+z}}\,.
$$
This is zero at the north pole $z=1$ and infinite at the south pole $z=-1\,.$ The vorticity of this vector field
is, as we know, $\nabla\times F=G$ which on $S^2$ is simply $\left(\begin{smallmatrix}x\\y\\z\end{smallmatrix}\right).$
Due to the circular motion in planes parallel to the $xy$--axis this seems odd at points away from the poles.
But this rotationally symmetric vorticity $G$ arises from different speeds of integral curves next to each other.
In particular, near the equator we have practically a
parallel flow with shear that has a nice animation here.


text:
Q: Symfony Warning : rename (../app/cache/dev , ../app/cache/dev_old ) : Access Denied . (Code : 5) I am working on Symfony project.
When i try to do :
php app/console cache:clear

i get the following ErrorException:
Warning : rename (../app/cache/dev , ../app/cache/dev_old ) : Access Denied . (Code : 5) in ../vendors/Symfony/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php on line 76

What is the problem here? I have given all permissions to the user on my machine (Windows 7 OS). Any ideas why it is happening?
Thank You.

A: To expand on leek's post, Symfony 2 cache-clearing operations shuffle the cached items across different folders during the cleanup.  Part of this process includes creating cache/dev-new/ and cache/dev-old/ folders.
If you are using Eclipse or another IDE that dynamically monitors subfolders within your project, the IDE will nearly instantly spot the new folder creation and look in those folders for new files (in Eclipse, I noticed the DLTK module constantly doing this in the Progress View).  This may unfortunately get in the way of Symfony, which wants to rename and/or delete these folders.
Specifically with Eclipse Indigo on Windows 7 64-bit, you can remove the cache/, cache/dev/, cache/dev_old/ and cache/dev_new/ folders from the build path by right-clicking your project and selecting "Build Path > Configure Build Path...".  This originally had no effect for me; I kept seeing the DLTK module trying to index the cache folders. I ended up uninstalling the Aptana Studio plug-in, closing all Editor documents, shutting down Eclipse, manually deleting the sub-folders in the cache/ folder, running Symfony cache:clear, then starting up Eclipse and reinstalling Aptana.  Seems to have worked thus far.

A: It's an issue with Symfony 2.0.x and Symfony 2.1.x. These a workaround for this:
Open the file: src\Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand.php
and add the statement sleep(1); where the directory creation is failing, in the execute() function:
    //...
    rename($realCacheDir, $oldCacheDir);
    sleep(1);
    rename($warmupDir, $realCacheDir);
    //...

You might have to re-open the CLI twice and run cache:clear, but it will fix the problem after that

A: Be sure that the files are not in use (as meze pointed out). If you're using something like TortoiseGit or Netbeans, etc - be sure to mark the cache folder as ignored so that they are not accessed.
If all else fails, download a free program like Unlocker that will allow you to quickly and easily detach running processes from the files/folders you are trying to modify.

A: If you're using text editors as Sublime Text try to ignore path of cached files
Go to Preferences/Setting
edit config file
{
...
     "folder_exclude_patterns": ["var","node_modules",  ".git"],
...
}

in my case
Cache folders containers.
Symfony 4
/var
Symfony 2
/app/cache
Nice coding!

A: I had the same issue with Symfony 4.1.13 and the root cause was that the VS Code was using the file "var/cache/dev/srcDevDebugProjectContainer.xml4QSKuA".
The issue was  Cannot rename  "var/cache/dev/srcDevDebugProjectContainer.xml4QSKuA".
I fix it adding **/var on the fields "Files to Exclude"
See the following steps:
1º Step:

2º Step search for "exclude" word, then add **/var/cache as the following image:

It's worked for me.

A: To have tranquility once and for all I create clear.bat file in MyProject folder under Windows 7 .
rmdir d:\symfony\framework-standard-edition\app\cache\  /S /Q

I guarantee 100% effectiveness for cleaning cache. Some minor problems can occurred after first time refresh website: Symfony must recreate some folders they need.

A: SYMFONY AND ANTIVIRUS
Multiple symfony calling in local windows machine get cross with some Antivirus software such as NOD in my case. Exclude symfony cache folder from real time protection


text:
Q: Strange behavior of MPMusicPlayerController.currentPlaybackTime While a song is being played, I tried to get currentPlaybackTime.
        NSLog(@"Playback: %f", appDelegate.appMusicPlayer.currentPlaybackTime);

I always got "Playback: nan". The application gets the currentPlaybackTime correctly when running (not debugging). The LLDB debugger also gives the correct currentPlaybackTime.
Does anyone know what going on with this property?

A: I would have commented on this but since I don't have enough reputation to do so...
According to this solution (I know, it's for MPMoviePlayerController but since both conform to the MPMediaPlayback Protocol this may be useful):
https://stackoverflow.com/a/10652551/3374794
You'll probably have to wait 1ms (1/1000 s) for the player to (?load?) the item.
MPMediaPlayBack Protocol Reference


text:
Q: print a file with certain extension I'd like to print a file selected with a file picker (or somehow) with
certain extension, so that PyQt or printer will automatically recognize
the format (e.g. pdf, ms word, excel, txt, html, jpg etc.)
So far, I have found here how to print the content
of the TextEdit, but I'd like to print files with various formats.
Is it possible with PyQt5 or should I search elsewhere?

A: Printing a plain text document does not require a viewer, since the print_() function actually calls the internal QDocument's print_() function:
filePath, filter = QFileDialog.getOpenFileName(self, 'Open file', '', 'Text (*.txt)')
if not filePath:
    return
doc = QtGui.QTextDocument()
try:
    with open(filePath, 'r') as txtFile:
        doc.setPlainText(txtFile.read())
    printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.HighResolution)
    if not QtPrintSupport.QPrintDialog(printer, self).exec_():
        return
    doc.print_(printer)
except Exception as e:
    print('Error trying to print: {}'.format(e))

You might want to add some functionalities to set the page size, document margins, font sizes etc, before actually printing (just read the QTextDocument docs), I'll leave that to you.

Printing from html files is almost similar, but you'll need to use the QWebEnginePage class from QtWebEngineWidgets. See this answer.
Do not use QTextDocument.setHtml(), as Qt has limited support for html tags.
The same is valid for PDF files too, the difference is that the file has to be loaded through setUrl() and the QWebEngineSettings.PluginsEnabled setting has to be enabled through page.settings().setAttribute(setting, bool) in case it's not.
Read the documentation about PDF File Viewing.

Printing images could be done through two approaches.
The first and simpler, is to create a temporary html file that embeds the image and load to a webengine page as above (you could add controls for zoom/scaling).
Alternatively, you could directly print using QPainter, but you'll have to relate to the printer resolution and image size, so you'd probably want to have a preview dialog before actually printing the image, otherwise it might be too small (or too big).
While more complex than a plain , this allows a better control on the positioning and sizing of the image[s].
class ImagePrintPreview(QtWidgets.QDialog):
    def __init__(self, parent, printer, pixmap):
        super().__init__(parent)

        self.printer = printer
        self.pixmap = pixmap

        layout = QtWidgets.QGridLayout(self)

        self.viewer = QtWidgets.QLabel()
        layout.addWidget(self.viewer, 0, 0, 1, 2)

        self.resoCombo = QtWidgets.QComboBox()
        layout.addWidget(self.resoCombo, 1, 0)

        self.zoom = QtWidgets.QSpinBox(minimum=50, maximum=200, suffix='%')
        self.zoom.setValue(100)
        self.zoom.setAccelerated(True)
        layout.addWidget(self.zoom, 1, 1)
        self.zoom.valueChanged.connect(self.updatePreview)

        self.buttonBox = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.Cancel)
        layout.addWidget(self.buttonBox)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        default = printer.resolution()
        self.resoCombo.addItem(str(default), default)
        for dpi in (150, 300, 600, 1200):
            if dpi == default:
                continue
            self.resoCombo.addItem(str(dpi), dpi)
        self.resoCombo.currentIndexChanged.connect(self.updatePreview)

        self.updatePreview()

    def updatePreview(self):
        # create a preview to show how the image will be printed
        self.printer.setResolution(self.resoCombo.currentData())
        paperRect = self.printer.paperRect(self.printer.DevicePixel)
        printRect = self.printer.pageRect(self.printer.DevicePixel)

        # a temporary pixmap that will use the printer's page size
        # note that page/paper are QRectF, they have a QSizeF which has to
        # be converted to a QSize
        pm = QtGui.QPixmap(paperRect.size().toSize())
        # new pixmap have allocated memory for their contents, which usually
        # result in some random pixels, just fill it with white
        pm.fill(QtCore.Qt.white)
        # start a qpainter on the pixmap
        qp = QtGui.QPainter(pm)
        # scale the pixmap to the wanted zoom value
        zoom = self.zoom.value() * .01
        scaled = self.pixmap.scaledToWidth(int(self.pixmap.width() * zoom), QtCore.Qt.SmoothTransformation)
        # paint the pixmap aligned to the printing margins
        qp.drawPixmap(printRect.topLeft(), scaled)

        # other possible alternatives:

        # Center the image:
        #   qp.translate(printRect.center())
        #   delta = QtCore.QPointF(scaled.rect().center())
        #   qp.drawPixmap(-delta, scaled)

        # To also rotate 90° clockwise, add this to the above:
        #   qp.rotate(90)
        # *after* qp.translate() and before qp.drawPixmap()

        # when painting to a non QWidget device, you always have to end the
        # painter before being able to use it
        qp.end()
        # scale the temporary pixmap to a fixed width
        self.viewer.setPixmap(pm.scaledToWidth(300, QtCore.Qt.SmoothTransformation))

    def exec_(self):
        if super().exec_():
            self.printer.setResolution(self.resoCombo.currentData())
            # do the same as above, but paint directly on the printer device
            printRect = self.printer.pageRect(self.printer.DevicePixel)
            qp = QtGui.QPainter(self.printer)
            zoom = self.zoom.value() * .01
            scaled = self.pixmap.scaledToWidth(int(self.pixmap.width() * zoom), QtCore.Qt.SmoothTransformation)
            qp.drawPixmap(printRect.topLeft(), scaled)
            # as above, that's important!
            qp.end()

class ImagePrinter(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout(self)
        selBtn = QtWidgets.QPushButton('Open image')
        layout.addWidget(selBtn)
        selBtn.clicked.connect(self.selectFile)

    def selectFile(self):
        filePath, filter = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '/tmp', 'Images (*.jpg *.png)')
        if not filePath:
            return
        pixmap = QtGui.QPixmap(filePath)
        if pixmap.isNull():
            return

        printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.HighResolution)
        if QtPrintSupport.QPrintDialog(printer, self).exec_():
            ImagePrintPreview(self, printer, pixmap).exec_()

Note that I couldn't test this under windows, so it might be necessary to change things related to the resolution (possibly by using printer.supportedResolutions()).

As already explained in the comments, printing to other (and possibly proprietary) formats requires external modules.


text:
Q: ¿Cómo puedo insertar el espacio en este cifrado césar? Soy un poco novata en esto, y probablemente la respuesta sea obvia, pero no consigo hacer que mi código imprima el texto con espacios. He utilizado el cifrado césar.
Cuando imprime mediante consola lo hace todo pegado sin espacios ni caracteres especiales.
Dejo debajo mi código.

let senteceCy = 'Merry Christmas';
let cypherTxt = '';

for(let i = 0; i < senteceCy.length; i++){
let numLetter = senteceCy.charCodeAt(i);
let cyFormula;
let newLetter;
  if(numLetter>= 65 && numLetter<= 90){
    cyFormula = (numLetter - 65 + 15)%26 + 65;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt += newLetter;
   }else if(numLetter >= 97 && numLetter <= 122){
    cyFormula = (numLetter - 97 +15)%26 + 97;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt = cypherTxt + newLetter;
   }
}
console.log(cypherTxt);

A: Basándome en lo que menciona el título: simplemente te falta contemplar el ASCII del espacio (32) en tu if.

let senteceCy = 'Merry Christmas';
let cypherTxt = '';

for(let i = 0; i < senteceCy.length; i++){
let numLetter = senteceCy.charCodeAt(i);
let cyFormula;
let newLetter;
  if(numLetter>= 65 && numLetter<= 90){
    cyFormula = (numLetter - 65 + 15)%26 + 65;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt += newLetter;
   }else if(numLetter >= 97 && numLetter <= 122){
    cyFormula = (numLetter - 97 +15)%26 + 97;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt = cypherTxt + newLetter;
   }
   else if(numLetter == 32) {
    newLetter = String.fromCharCode(numLetter);
    cypherTxt += newLetter;
   }
}
console.log(cypherTxt);

Para el caso de los caracteres especiales, es nada más un else.

let senteceCy = 'Merry Christmas ▲▼';
let cypherTxt = '';

for(let i = 0; i < senteceCy.length; i++){
let numLetter = senteceCy.charCodeAt(i);
let cyFormula;
let newLetter;
  if(numLetter>= 65 && numLetter<= 90){
    cyFormula = (numLetter - 65 + 15)%26 + 65;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt += newLetter;
   }else if(numLetter >= 97 && numLetter <= 122){
    cyFormula = (numLetter - 97 +15)%26 + 97;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt = cypherTxt + newLetter;
   }
   else {
    newLetter = String.fromCharCode(numLetter);
    cypherTxt += newLetter;
   }
}
console.log(cypherTxt);

A: Faltaría incluir una condicional para identificar a los espacios en tu cadena, es decir, cuando identifica el espacio, genera un espacio en el string final:
else if(numLetter === 32){
    cypherTxt += ' ';
}

Código:

let senteceCy = 'Merry Christmas';
let cypherTxt = '';

for (let i = 0; i < senteceCy.length; i++) {
  let numLetter = senteceCy.charCodeAt(i);
  let cyFormula;
  let newLetter;
  if (numLetter >= 65 && numLetter <= 90) {
    cyFormula = ((numLetter - 65 + 15) % 26) + 65;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt += newLetter;
  } else if (numLetter >= 97 && numLetter <= 122) {
    cyFormula = ((numLetter - 97 + 15) % 26) + 97;
    newLetter = String.fromCharCode(cyFormula);
    cypherTxt = cypherTxt + newLetter;
  } else if (numLetter === 32) {
    cypherTxt += ' ';
  }
}
console.log(cypherTxt);


text:
Q: how to apply here singleton pattern to prevent creating object of fom3 again and again public Form fr;
private void button2_Click(object sender, EventArgs e)
{

       fr = Form1.ActiveForm;

       fr.Hide();

       Form3 fr1 = new Form3(fr);
       fr1.Show();
}

A: You don't need to create Form3 as singleton (I think you can't do that) but you need to instantiate it only once. For instance you could use something like this:
public Form fr;
Form3 fr1 = null;
private void button2_Click(object sender, EventArgs e)
{

       fr = Form1.ActiveForm;

       fr.Hide();
       if(fr1==null)
        fr1 = new Form3(fr);
       fr1.Show();
}

A: Don't.
You cannot use the singleton pattern with UI components because a Windows Form encapsulates a Win32 hWnd window, which will need to be disposed of eventually, and you cannot resurrect a window, you have to recreate it, which is contrary to the singleton pattern.
Furthermore, the Windows Forms designer needs a public default constructor. Even if you could use singleton you would need to disable the private constructor every time you edit your form in the designer.
Assuming your project has no consumers, a better idea is to change your form to internal and just track every instantiation yourself.


text:
Q: Run CMD from C# Console Application? How might I run CMD.EXE from my C# Console Aplication? Like in Powershell you can run cmd.exe by typing "cmd"
EDIT: Open Powershell. Type "cmd". That's what I want.
EDIT2: Thank you for your help. I will try to make it clearer. I want it so that when the user enters "cmd" into my command line C# Application, it runs CMD.EXE in that same window. it is basically the same as typing CMD in Powershell.

A: is Process.Start("cmd.exe") is what you're seeking for? (Don't forget to add  using System.Diagnostics))
More info about Process class on MSDN

A: I think that you want your user to have an interactive shell inside your application.
One way to do that is to redirect both stdin and stdout of cmd.exe to your application. It will input/output data from console in a string so you can show it in a textbox of whatever flots your boat.
This project from code project seems to do what you want to do


text:
Q: org.hibernate.Hibernate constant for enum my question very simple if org.hibernate.Hibernate.SRTING for handle String class, and org.hibernate.Hibernate.INTEGER for Integer class, so what constant in org.hibernate.Hibernate for handle enum class??
Thanks....

A: Try
org.hibernate.Type.EnumType

A: If your enum is non parametrized then just do this
@Enumerated(EnumType.STRING)
@Column(name="enumTest")
private YourEnum myEnum;

In case of parametrized a little bit trick is required see here.