text:
Q: How to save input from actionlistener, and then compare to another in Java? I am making a rock-paper-scissors game, where 2 players have to choose if they are going to use rock, paper or scissors. And then my program is suposed to compare the the choices. But I'm having problems saving the choices as a variable.
I can print out the the choices, but I don't know how I can use the answers outside the actionlisteneres.
So this is the code I have(some of the names are in Norwegian, so might be a bit confusing, but hopefully you understand):
package oblig8;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class Oblig8 extends JFrame{

public static void main(String[] args) {
    // TODO Auto-generated method stub
JFrame Frame = new JFrame("Stein - Saks - Papir");
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setSize(500, 500);
Frame.setVisible(true);
JButton Spiller1 = new JButton("Spiller 1");
JButton Spiller2 = new JButton("Spiller 2");
Frame.getContentPane().add(Spiller1, BorderLayout.WEST);
Frame.getContentPane().add(Spiller2, BorderLayout.EAST);
String[] muligheter = new String[3];
muligheter[0]="Stein";
muligheter[1]="Saks";
muligheter[2]="Papir";

Spiller1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          int valg1 = JOptionPane.showOptionDialog(Frame,
                  "Spiller 1 har trykket",
                  "Stein - Saks - Papir",
                  JOptionPane.YES_NO_CANCEL_OPTION,
                  JOptionPane.QUESTION_MESSAGE,
                  null,
                  muligheter,
                  muligheter[2]);
          System.out.println(valg1);}});
Spiller2.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      int valg2 = JOptionPane.showOptionDialog(Frame,
              "Spiller 2 har trykket",
              "Stein - Saks - Papir",
              JOptionPane.YES_NO_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              muligheter,
              muligheter[2]);
      System.out.println(valg2);}});
}}

A: You need to get your main method to create an instance of the Oblig8 class, and then use that as the JFrame. Once you've done this, the rest of your code can be moved to instance methods of that class.
Your ActionListeners will then be running inside instances of your Oblig8 class, and they'll have access to its fields and methods. They'll be able to write to instance fields, and also to invoke instance methods to get further things to happen.
So your main method can be very short:
public static void main(String[] args) {
    Oblig8 oblig8 = new Oblig8();
    oblig8.doSomeStuff();
}

All your other code can then be moved into the Oblig8 constructor, or its doSomeStuff method.
Add some fields to your Oblig8 class, and then get your ActionListeners to interact with them.

A: You can declare static int variables in the class scope, and store the answer in these variable, then used it as you wish
public class Oblig8 extends JFrame {

static int valg1;
static int valg2;

public static void main(String[] args) {
    ...

    Spiller1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            valg1 = JOptionPane.showOptionDialog(Frame,
                    "Spiller 1 har trykket",
                    "Stein - Saks - Papir",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    muligheter,
                    muligheter[2]);
            System.out.println(valg1);
        }
    });
    ...
}
}

A: Your problem is with the anonymous class, which does not store the value to be accessed later. Since these methods are basically the same it seems just efficient to go ahead and create a proper nested subclass.
static class SpillerButton extends JButton implements ActionListener {
   int valg;

   SpillerButton(String name){
      super(name);
      addActionListener(this);
   }

   public void actionPerformed(ActionEvent evt) {
      valg = JOptionPane.showOptionDialog(null,
              getText()+"har trykket",
              "Stein - Saks - Papir",
              JOptionPane.YES_NO_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              muligheter,
              muligheter[2]);
     System.out.println(valg);
  }
}

And muligheter should probably be a final static constant in Oblig8 anyway, but it needs to be where this subclass can find it.
Now instead of using generic JButtons you use SpillerButtons and get the value whenever you want to show the results.


text:
Q: Dock Intellihide Is there any way to get the dock to use "intellihide" (this is a carry over from various docks in the linux world). Basically that means that the dock is always visible if no windows are in its space, but if a window gets too close, the dock reverts to autohide type behavior. I can only find "autohide" and always visible. I would prefer something as I described.

A: I have developed an application (mainly using AppleScript) that does this, or at least very close to what you want: https://github.com/gjherbiet/DockIntellihide.app

A: No. I don't believe that this is supported by Apple at this time.
Sorry for the pessimistic answer, but to my knowledge it's true.
There may be ways to run Docky or the like through macports or fink.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to capture previous page url in Custom VF Tab I am trying to capture the URL of the previous page in a custom VF Page, when someone clicks on my custom tab from any page, especially when they are in Setup or Reports area.
Following is what I am trying to do, which is not giving me the desired results. I'll appreciate if anyone can provide any insights on this.
My goal is to capture the previous page url, execute my logic on my custom VF page, and redirect the user to the same previous page.

I have a Custom Tab 'Check URL' that displays the custom VF Page. I want to display the following url in the case of click the tab from setup area:
https://na15.salesforce.com/setup/forcecomHomepage.apexp?setupid=ForceCom&retURL=%2Fhome%2FshowAllTabs.jsp
The code is as follow:
<apex:page standardStylesheets="true" sidebar="false" showHeader="false">

   {!$CurrentPage.URL}

 « Go back

</apex:page>

A: You can get the prior page using (Apex Code):
String referrer = apexpages.currentPage().getheaders().get('Referer');

This value may be unreliable if the user uses a bookmark or when Developer Mode is enabled.


text:
Q: How to get function pointer arguments names using clang LibTooling? Say I analyze a code like this:
struct Foo
{
    void(*setParam)(const char* name, int value);
};

I use clang LibTooling and get FieldDecl on a setParam.
I figured I can get argument types like so:
auto ft = fieldDecl->getFunctionType()->getAs<FunctionProtoType>();
for (size_t i = 0; i < fpt->getNumParams(); i++)
{
    QualType paramType = fpt->getParamType(i);
    ....
}

But how do I get argument names? ("name" and "value" in that case) Is that even possible or I need to manually look into source (with SourceManager)?

A: I don't think it's possible to get the parameter names directly from the type, since they're not part of the type information.
But your task can be accomplished by one more visiting to the function pointer declaration:
class ParmVisitor
    : public RecursiveASTVisitor<ParmVisitor>
{
public:
    bool VisitParmVarDecl(ParmVarDecl *d) {
        if (d->getFunctionScopeDepth() != 0) return true;

        names.push_back(d->getName().str());
        return true;
    }

    std::vector<std::string> names;
};

Then the calling site is:
bool VisitFieldDecl(Decl *d) {
    if (!d->getFunctionType()) {
        // not a function pointer
        return true;
    }
    ParmVisitor pv;
    pv.TraverseDecl(d);
    auto names = std::move(pv.names);

    // now you get the parameter names...

    return true;
}

Pay attention to the getFunctionScopeDepth() part, it's necessary because a function parameter might be a function pointer itself, something like:
void(*setParam)(const char* name, int value, void(*evil)(int evil_name, int evil_value));

getFunctionScopeDepth() being 0 ensures that this parameter is not in a nested context.


text:
Q: how to call an external function from inside a class? i want to call an external function inside a class. thats the code;
in checkConnectionStatus function,
this[_funcNameForSucceededCon].apply();    doesnt work because "this" is the class, not the Application. How can i reach Application at this time or what can i do?
any help will be greatly appreciated.
best regards,
mira.
package myLibrary
{
     import air.net.URLMonitor;

     import flash.events.Event;
     import flash.events.StatusEvent;
     import flash.net.URLRequest;

     public class connectionControl
     {
         private var _urlReq:URLRequest;
         private var _urlMonitor:URLMonitor;

         private var _funcNameForSucceededCon:String;
         private var _funcNameForFailedCon:String;

         public function connectionControl(targetURL:String, funcNameForSucceededCon:String, funcNameForFailedCon:String)
         {
             _urlReq = new URLRequest(targetURL);
             _urlMonitor = new URLMoniotor(_urlReq);

             _urlMonitor.addEventListener(StatusEvent.STATUS, checkConnectionStatus);

             _funcNameForSucceededCon = funcNameForSucceededCon;
             _funcNameForFailedCon = funcNameForFailedCon;

             if(_urlMonitor.running == false)
             {
                 _urlMonitor.start();
             }
             else
             {
                 _urlMonitor.stop();
                 _urlMonitor.start();
             }
         }

         private function checkConnectionStatus(e:Event):void
         {
             _urlMonitor.removeEventListener(StatusEvent.STATUS, checkConnectionStatus);

             if(_urlMonitor.available)
             {
                this[_funcNameForSucceededCon].apply();
             }
             else
             {
                this[_funcNameForFailedCon].apply();
             }

         }

     }
}

A: You have passed the name of the function to be serving as a callback. Use instead the function itself and pass it to connectionControl.
 public class connectionControl
 {

     private var _funcSucceededCon:Function;
     private var _funcFailedCon:Function;

     public function connectionControl(targetURL:String, funcSucceededCon:Function, funcFailedCon:Function)
     {
         _urlReq = new URLRequest(targetURL);
         _urlMonitor = new URLMoniotor(_urlReq);

         _urlMonitor.addEventListener(StatusEvent.STATUS, checkConnectionStatus);

         _funcSucceededCon= funcSucceededCon;
         _funcFailedCon= funcFailedCon;

         ...

And:
        if(_urlMonitor.available)
         {
            _funcSucceededCon();
         }


text:
Q: How to define the mapDispatchToProps type of redux thunk function Follow the official doc, I make a login typescript like thunk function.
function loginApi(user: UserState) {
  return fetch(
    `${baseUrl}/login?user=${user.userName}&pwd=${user.pwd}`
  )
    .then(res => res.json())
}

export const thunkLogin = (
  user: UserState
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
  const asyncResp = await loginApi(user)
  dispatch(
    updateUser({
      loggedIn: asyncResp.isloggedIn,
      userName: user.userName,
      userPwd: user.userPwd
    })
  )
}

I want add this thunk function to my app component using react-redux connect hoc function.
import { thunkLogin } from './thunkLoginPath'

interface Props {
  // place 1
  thunkLogin: typeof thunkLogin
}

interface State {
  userName: string
  userPwd: string
}

class AppComponent extends React.Component<Props, State> {
  handleSubmit = () => {
    this.props.thunkLogin({
      userName: this.state.userName,
      userPwd: this.state.userPwd
    })
  }

  render(){
    return(
      <TouchableOpacity
        style={style.loginBotton}
        onPress={this.handleSubmit}
      >
        <Text style={style.loginBottomText}>LOGIN</Text>
      </TouchableOpacity>
    )
  }
}

export default connect(
  (state: AppState) => ({
    user: state.user
  }),
  // place 2
  { thunkLogin }
)(AppComponent)

It report a error show that the thunkLogin declare at Props not assignable to mapDispatchToProps (place 1 -> place 2).

A: did you mean to connect AppComponent or Login component, since you trying
to call this.props.thunkLogin from AppComponent but you connect Login.
try to change it like this.
export default connect(
  (state: AppState) => ({
    user: state.user
  }),
  // place 2
  { thunkLogin }
)(AppComponent)

A: Your mapDispatchToProps is totally okay. If you want to use some other syntax here you have:
const mapDispatchToProps = (dispatch) => {
  return {
    thunkLogin: (user: UserState) => {
      dispatch(thunkLogin(user))
    }
  }
}

But I think that this won't help you with TypeScript errors. At least I had many many problems with react-thunk. I ended up throwing away all that ThunkAction crap since TypeScript is smart enough to recognize functions types. I only took care that nested function of action creator returns any. In reality it always returns void (but TypeScript doesn't like it). Your function would look something like this:
export const thunkLogin = (user: UserState) => async (dispatch): any => {
  const asyncResp = await loginApi(user)
  dispatch(
    updateUser({
      loggedIn: asyncResp.isloggedIn,
      userName: user.userName,
      userPwd: user.userPwd
    })
  )
}

This solution is good enough for me, because it shows me typing inside the component. I can be aware if action creator is regular or thunk-powered. An example:

If you want to read more about react-thunk and typescript, go here:
https://github.com/reduxjs/redux-thunk/issues/103


text:
Q: HttpContext.Current.User.Identity.Name is incorrect but only for me We have a number of webpages that employees can access. I have a table, in a database, which determines who can access the individual pieces.
I use HttpContext.Current.User.Identity.Name, to get the current username, and then determine whether they are allowed to access the page they are requesting. If not, they are redirected to an access denied page, which has contact details where they can request access.
This is been working for months and is still working for everybody, except me! As well as my usual active directory account, I have what we call a developer account to login to servers et cetera. When I run the webpages on my PC, either through visual studio or IIS, I have determined that it is working because it is using my standard active directory account.
I am not aware of making any changes. I was actually just going through the pages as part of a documentation exercise.
However, as soon as I try to browse the pages on the server, it appears to be using my developer account! How do I know this? Firstly, I have built a test page that displays the current username. Secondly, I have an audit table, which records who try to access what page, when and whether they were allowed access.
Yes I could add my developer account to the users table but that would obviously not be my preferred solution. I have been working on something else for the past few days (nothing to do with this) and based on the audit table, I think this problem started today.
Any ideas?


text:
Q: In Networkx is there a way to select when to save to a file, when show on screen and when both? At the moment, I am doing both:

pos = nx.spring_layout(G)

f1 = plt.figure(figsize=(18,10))

default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)

edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)

plt.savefig('graph.jpg')

I would like to be able to select if to display, save or both (what I am doing now)

A: There is no built-in option for that in networkx. One option is to wrap the code in a function along these lines:
def custom(G, plot=True, save_file=False):
   '''plots G by default. save_file should be a string'''
   pos = nx.spring_layout(G)

   f1 = plt.figure(figsize=(18,10))
   default_axes = plt.axes(frameon=True)
   nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)

   edge_labels = nx.get_edge_attributes(G, "weight")
   nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)

   if save: plt.savefig(save) # can allow custom save name
   if plot: plt.show()

   return

Note that if the figure displays regardless of the option passed to the command, then the inline option might need to be disabled.


text:
Q: python: Unable to use eval() to run object methods I'm trying to use eval() to run dynamic code, but it seems to reject object-based methods:
def GetHelp():
    return 'Help'

class MyClass:
    def __init__(self):
        self.child = 5
    def GetChild():
        return self.child

x = eval('Get{}()'.format('Help'))
print(x)

obj = MyClass()
y = eval('obj.Get{}()'.format('Child'))
print(y)

The above code gives me:
Help
Traceback (most recent call last):
  File "/Users/kakyo/Desktop/0.Dev/playground/python/hello_eval.py", line 14, in <module>
    y = eval('obj.Get{}()'.format('Child'))
  File "<string>", line 1, in <module>
TypeError: GetChild() takes 0 positional arguments but 1 was given

I tried to add obj to locals:
y = eval('obj.Get{}()'.format('Child'), {'obj': obj})

but got the same error.

A: The error is unrelated to the fact you used eval (but do not use eval). It is because GetChild does not accept self (or actually any other argument) as the instance in its signature.
It should be def GetChild(self)
But (if it wasn't clear already) eval should be avoided at all costs and is very rarely the only solution to a given problem.
In this case, it is preferable to use getattr:
obj = MyClass()
y = getattr(obj, 'Get{}'.format('Child'))()
print(y)


text:
Q: Accessing a variable declared in fla from as file On the stage I have a movieclip by the name of rect_mc. Inside it have have a MovieClip sqaure_mc.
In the time line that I get when I double click on rect_mc (timeline of rect_mc) I have written the following code
var width1:Number;
width1 = sqaure_mc.width;

How can I access width1 from the document class?

A: Export your square_mc for ActionScript and define a class. Then in this class, define your variables.
package
{
    import flash.display.MovieClip;

    public class SquareMC extends MovieClip
    {
        public var width1:Number;

        public function SquareMC()
        {
            width1 = width;
        }
    }
}

The properties defined within this will be accessible from the document class via:
rect_mc.square_mc.width1;


text:
Q: java retrieve objects from a Set In Java 5, If i have a Set, and i add two objects to the Set. When I retrieve the objects, will it give me back in the same order as I added?
I am not able to find the answer to this. Does it depend on which Set implementation I use?

A: Yes, it depends on which implementation you use. For example, LinkedHashSet will preserve insertion order:

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

... but HashSet won't:

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

A: Straight from the documentation:

The elements are returned in no particular order (unless this set is
  an instance of some class that provides a guarantee).

A: Depends on Set implementation. LinkedHashSet does exactly that.

A: Yes it does depend on the implementation you choose. HashSet will not guarantee order but LinedHashSet will.

A: JavaDocs is your best friend. It's implementation specific. For example:
java.util.Set:

Iterator<E> iterator();
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).

and
java.util.TreeSet:

public Iterator<E> iterator();
Returns an iterator over the elements in this set in ascending order.

A: The Set interface itself is for unordered container implementations. But there might be implementations of Set that do return the elements in a particular order.
Also see the documentation of Set.iterator:

Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee)


text:
Q: Virtual box machine, Created in windows run on linux? Can a virtual box machine that was created in Virtual Box for windows run on Virtual box for linux?
And if so do I just need to transfer the hdd files?

A: Yes you can use Virtual Box images portability across different host OSs. It's a little bit complicated because you need more than the hard drive image, you also need the virtual machine configuration file.

*

*If this is a one time transfer you might consider the export / import options to help you get all this stuff transferred.

*If this is a transfer you hope to make many times, you might look into VirtualBox's teleport function that allows you to transfer running virtual machines back and forth between different hosts.

Starting with version 3.1, VirtualBox supports "teleporting" -- that is, moving a virtual machine over a network from one VirtualBox host to another, while the virtual machine is running. This works regardless of the host operating system that is running on the hosts: you can teleport virtual machines between Solaris and Mac hosts, for example.
Teleporting requires that a machine be currently running on one host, which is then called the "source". The host to which the virtual machine will be teleported will then be called the "target"; the machine on the target is then configured to wait for the source to contact the target. The machine's running state will then be transferred from the source to the target with minimal downtime.


text:
Q: errorBody() Expected BEGIN_ARRAY I'm trying to convert the errorBody into my RegistrationResponse but it is always throwing an Expected BEGIN_ARRAY but was BEGIN_OBJECT
RegistrationResponse
data class RegistrationResponse(
    val status: Boolean,
    val errors: List<RegistrationBody>
)

RegistrationBody
data class RegistrationBody(
    val lastname: String,
    val firstname: String,
    val middlename: String
)

My Converter
if (it is HttpException) {
    if (it.code() == 400) {
        // Bad Request
        val errorConverter: Converter<ResponseBody, RegistrationResponse>? = retro?.responseBodyConverter(RegistrationResponse::class.java, arrayOfNulls<Annotation>(0))
        Log.i("TAG", "${errorConverter?.convert(it.response().errorBody())}")
    }
}

My Expected Output
{
    status: false,
    errors: {
        lastName: "The last name is required.",
        firstName: "The first name is required.",
        middleName: "The middle name is required.",
    }
}

did I miss something in the code?
I also try the
val errorConverter: Converter<ResponseBody, List<RegistrationResponse>>? = retro?.responseBodyConverter(RegistrationResponse::class.java, arrayOfNulls<Annotation>(0))

still the error is Expected BEGIN_ARRAY but was BEGIN_OBJECT

A:
Expected BEGIN_ARRAY but was BEGIN_OBJECT

RegistrationBody is OBJECT not ARRAY.
You should use
    data class RegistrationResponse(
    val status: Boolean,
    val errors: RegistrationBody
)


text:
Q: SFTP works over linux command line but filezilla fails I have set up an ftp user on my ubuntu server.  I can sftp in to ftp_user@ip, am asked for my password, and get connected fine.
Filezilla (which worked 3 months ago), doesn't connect.  This is a redacted version of the ssh logs:
Jul 19 14:18:33 sshd[14275]: Invalid user user from  port 47990
Jul 19 14:18:33 sshd[14275]: Received disconnect from  port 47990:11: Normal Shutdown, Thank you for playing [preauth]
Jul 19 14:18:33 sshd[14275]: Disconnected from invalid user user  port 47990 [preauth]
Jul 19 14:18:44 sshd[14277]: Invalid user user from  port 48558
Jul 19 14:18:44 sshd[14277]: Received disconnect from  port 48558:11: Normal Shutdown, Thank you for playing [preauth]
Jul 19 14:18:44 sshd[14277]: Disconnected from invalid user user  port 48558 [preauth]
Jul 19 14:18:55 sshd[14282]: Invalid user user from port 49142
Jul 19 14:18:55 sshd[14282]: Received disconnect from  port 49142:11: Normal Shutdown, Thank you for playing [preauth]
Jul 19 14:18:55 sshd[14282]: Disconnected from invalid user user port 49142 [preauth]

This sounds like Filezilla is trying user "user", which is not correct, but my settings has:

EDIT: it works if I use the quickconnect bar, but not the above main settings.
What am I doing wrong?


text:
Q: How does Newton's third law work This law states that to each action there is an opposite and equal reaction. and I understand that this is the law that Rocket thrusters are built on. they use the combustion of fuel to push out hot exhaust gas in huge quantities and acceleration, and the gas in turn will push the rocket in the opposite direction.
So theoretically if we let's say have a 1/2 pound beach ball resting on a 100 pound metal bowling ball and we quickly pull the bowling ball to the right giving it a great amount of acceleration (similar to the exhaust gas). the ball should in turn provide a force in the opposite direction that is equal to force we applied on it, and should cause the beach ball to move to the left. But that does not happen. if we do this, the beach ball would simply either stay at rest, or may be roll forward to the right if the surface was not leveled (assuming we had a way to prevent the bowling ball from rolling in the first place). so why is that?

A: Newton's Third Law of Motion applies between two bodies: if body A applies a force on body B, then body B applies an equal, but opposite force upon body A.
Let the upper ball be A, and the lower ball B. Gravity supplies a force on A, which can be found using Newton's 2nd Law of Motion and the local gravitational acceleration, F=mg; this force passes from A to B, through the surface contact. This force is thus $ FA=m_A×g$.
By Newton's 3rd law, the reaction force is $ FB =-FA $. This is the normal force.
Now you introduce a new force, by pulling the bottom ball away. Call this the grabbing force on B, $ GFB $. The friction between the two balls is proportional to the normal force between them, so as you pull the lower ball away, the frictional force will oppose the motion of your ball, B; and the reaction force, acting on A, will be equal and opposite. It will cause the now falling A to begin rotaing as it falls.


text:
Q: Linking Kim Walisch Primes Libraries in Visual Studio I am trying to use Kim Walisch primes libraries found on github (primecount, primesum & primesieve). For start, I tried to use primecount - https://github.com/kimwalisch/primecount .
Not being an expert C/C++ programmer, nor a Visual Studio user, I searched for the process on the internet - Youtube and here (Stackoverflow). I downloaded the github extension for Visual Studio, and then cloned the repository from github. The repository is saved on "C:\Users\MYNAME\source\repos". I then understood I need to 'link' the library to my current project. I did the following:

*

*Right click on my project name found to the left --> Properties at the bottom --> configuration properties --> C/C++ --> Additional Include Directories --> and here I just copy the path: "C:\Users\MYNAME\source\repos\primecount\include"

*Right click on my project name found to the left --> Properties --> configuration properties --> Linker --> General --> Additional Library Directories --> and here I just copy another path: "C:\Users\MYNAME\source\repos\primecount\Primes\Primes\Debug"

*Right click on my project name found to the left --> Properties --> configuration properties --> Linker --> Input --> Additional Dependencies --> and here I just copy the same path: "C:\Users\MYNAME\source\repos\primecount\Primes\Primes\Debug"
There aren't any .lib or dll files, so I simply tried varius of other things. I tried to copy the paths with/without quotes. Tried to use different paths for each of these 3. I think I am getting the first one right, but not the linker. I keep getting errors like "LNK1107" "LNK1120" and most often "LNK1104". Different errors occur when I change the paths. In the link above, it says the following contains more information: https://github.com/kimwalisch/primecount/blob/master/doc/libprimecount.md and at the bottom of this link, it says "Linking: c++ -O2 primes.cpp -lprimecount" so I tried to use this in a way as well (not sure if it's meant for this). I tried to locate the 'library', which from my understand is what I need to link, but I can't find it anywhere in the folder. The closest I found are the above paths, that contain an obj. file, but still it doesn't work and I have absolutely no idea what I am doing wrong here. Even when trying numerous different paths for the linker. This library is very famous and is used often, so obviously it can work. I know 'similiar' questions have been asked, but my question is very specific, and still, following every instruction and guide I could on youtube and on this site, I can't set it right.
Would appreciate an explanation that picks off right at the start of the above 3 steps, and mentions exactly which paths I need to use. Or if I am missing something before that, point me in the right direction. I am almost 100% sure I mentioned each and every step that I did, without skipping any.


text:
Q: Multiple Component with Same Function Name in React Native I'm using react-native-material-menu's popup for showing menu options.
But the issue is, it's not working for multiple scenarios.
I mean when I click on first menu button, the same methods gets triggered and hence the same menu is opened every time.
What should be the better approach for to handle this particular scenario.
 _menu = null;

 setMenuRef = ref => {
     this._menu = ref;
 };

 hideMenu = () => {
     this._menu.hide();
 };

 showMenu = () => {
     this._menu.show();
 };

  <FlatList
      data={this.state.clientsList}
      renderItem={({ item }) => {
      return (
          <View style={styles.caseItem} >
              <Card style={styles.card}>
                  <CardItem>
                     <Body>
                        <View style={styles.rowTitle}>
                           <Text style={styles.title}>{item.FullName}</Text>
                           <Menu
                                ref={this.setMenuRef}
                                button={
                                   <Icon
                                        type="Feather"
                                        name="more-vertical"
                                        onPress={this.showMenu}
                                           style{{fontSize:20,color:'#555'}}
                                     />
                             }>
                                <MenuItem onPress={this.hideMenu}>View</MenuItem>
                                <MenuItem onPress={this.hideMenu}>Edit</MenuItem>
                                <MenuItem onPress={this.hideMenu}>Delete </MenuItem>
                            </Menu>
                        </View>

                        <View>
                            <Text style={styles.lbl}>Email: <Text style={styles.lblValue}>{item.EmailID}</Text></Text>
                            <Text style={styles.lbl}>Client Type: <Text style={styles.lblValue}>{item.ClientType}</Text></Text>
                        </View>
                     </Body>
                  </CardItem>
               </Card>
            </View>
         );
      }}
      keyExtractor={item => item.ID}
   />

Snack Here

A: To handle the states in the correct way, you will need to create a new Class which will be handling just the MenuItem
The below code will work: Here is the Snack.
import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Container, Content, Card, CardItem, Body, Icon } from "native-base";
import * as Font from "expo-font";
import Menu, { MenuItem, MenuDivider } from "react-native-material-menu";
// You can import from local files
import AssetExample from "./components/AssetExample";

export default class App extends React.Component {

  onView = () => {
    alert("Do something here");
    console.log("You can do what ever you want here");
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.caseItem}>
          <Card style={styles.card}>
            <CardItem>
              <Body>
                <View style={styles.rowTitle}>
                  <Text style={styles.title}>John Doe</Text>
                  <CustomMenu onView={this.onView}/>
                </View>

                <View>
                  <Text style={styles.lbl}>
                    Email: <Text style={styles.lblValue}>john@yopmail.com</Text>
                  </Text>
                  <Text style={styles.lbl}>
                    Client Type: <Text style={styles.lblValue}>Individual</Text>
                  </Text>
                </View>
              </Body>
            </CardItem>
          </Card>
        </View>
        <View style={styles.caseItem}>
          <Card style={styles.card}>
            <CardItem>
              <Body>
                <View style={styles.rowTitle}>
                  <Text style={styles.title}>John Doe</Text>
                  <CustomMenu  onView={this.onView}/>
                </View>

                <View>
                  <Text style={styles.lbl}>
                    Email: <Text style={styles.lblValue}>john@yopmail.com</Text>
                  </Text>
                  <Text style={styles.lbl}>
                    Client Type: <Text style={styles.lblValue}>Individual</Text>
                  </Text>
                </View>
              </Body>
            </CardItem>
          </Card>
        </View>
        <View style={styles.caseItem}>
          <Card style={styles.card}>
            <CardItem>
              <Body>
                <View style={styles.rowTitle}>
                  <Text style={styles.title}>John Doe</Text>
                  <CustomMenu onView={this.onView} />
                </View>

                <View>
                  <Text style={styles.lbl}>
                    Email: <Text style={styles.lblValue}>john@yopmail.com</Text>
                  </Text>
                  <Text style={styles.lbl}>
                    Client Type: <Text style={styles.lblValue}>Individual</Text>
                  </Text>
                </View>
              </Body>
            </CardItem>
          </Card>
        </View>
      </View>
    );
  }
}

class CustomMenu extends React.Component {
  _menu = null;
  setMenuRef = ref => {
    this._menu = ref;
  };

  hideMenu = () => {
    this._menu.hide();
  };

  onViewClick = () => {
    const {onView} = this.props;
    onView();
    this.hideMenu();
  }

  showMenu = () => {
    this._menu.show();
  };

  render() {
    return (
      <Menu
        ref={this.setMenuRef}
        button={
          <Icon
            type="Feather"
            name="more-vertical"
            onPress={this.showMenu}
            style={{ fontSize: 20, color: "#555" }}
          />
        }
      >
        <MenuItem onPress={this.onViewClick}>View</MenuItem>
        <MenuItem onPress={this.hideMenu}>Edit</MenuItem>
        <MenuItem onPress={this.hideMenu}>Delete </MenuItem>
      </Menu>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  rowTitle: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%"
  },
  title: {
    fontSize: 14,
    marginBottom: 5
  },
  lbl: {
    fontSize: 11,
    color: "#000"
  },
  lblValue: {
    fontSize: 11,
    color: "#555",
    fontWeight: "normal"
  },
  caseItem: {
    marginBottom: 0
  }
});

A: Since the FlatList will iterate over the menu items, you need to maintain index for each iterable menu options.
You can check, you are passing item object within renderItems prop. So you can use the same item.id as a key to your child (iterable) component.
Since the child component now maintains an index, so now you can pass it in methods which will help you differentiate the event which got triggered from the child element.
I hope this might give you an idea about the issue.


text:
Q: What is the difference between GNU bison and yacc? I am writing a parser and I want it to be as portable as possible.
Right now I am using GNU bison to generate my parser but I am not sure if my code is relying on yacc extensions that are not fully portable.
So I would like to know features GNU bison has that the original yacc is missing.
The reason I get worried is because I noticed that my parser failed to compile on Windows using a bison port. I would sacrifice GNU bison features and stick with the original standardized yacc if it would make my parser easier to port between different platforms.
So what are the differences between GNU bison and the original standard yacc? What features should I avoid when using GNU bison if I want my program to be as portable as possible?

A: Usually the way you distribute a bison-generated parser is to distribute the generated parser. That means that neither bison nor yacc even needs to be installed on the target machine, and allows you to freely chose the version of bison you are comfortable with and use its features. (The bison input file will also be in the distribution, of course; including the bison output files simply means that bison does not need to be run to compile the code.)
If you want to verify that your parser description is compatible with yacc, you could try using the --yacc flag when you generate the parser. That will make bison attempt to mimic yacc, although it doesn't prevent you from asking for features which are clearly well out of yacc's scope, like %glr-parser or Java/C++ output. But frankly, I think you would be better off with the strategy outlined in the first paragraph.
If you want to get a list of bison features which are not in yacc, you could start by searching for the word yacc in the bison manual. Or you could read the Posix yacc documentation.


text:
Q: When using JDBC with Oracle DB how to find if the connection really timed out or if credentials were wrong? I already have the connection string and DBA username. I accept DBA password from the user.
To check if the password provided by him is correct, I try to create a connection using
    String connString = "jdbc:oracle:thin:@" + connDesc;
    Properties props = new Properties();
    props.put("user", user);
    props.put("password", pwd);

    props.put("internal_logon", "sysdba");
    Class.forName("oracle.jdbc.OracleDriver").newInstance();
    Connection conn = DriverManager.getConnection(connString, props);

Now when it throws SQLException I need to find if that exception is because of wrong password or network timeout. Is there any way to do that?
Also, is there any better way to validate password than what I'm currently doing?

A: You can use the SQLException.getErrorCode() method to read the Oracle-specific error code for the error.
For an invalid username/password combination, the error code is 1017.
It's not clear to me exactly what error you mean by 'network timeout'.  If the message is The Network Adapter could not establish the connection, then the error code you want appears to be 17002.  (I got this error attempting to connect to my local Oracle XE instance using JDBC but with the TNS listener shut down.)
There isn't a better way of validating a username/password than attempting to create a connection to the database using that username and password.


text:
Q: Django functional Based view to FormView I have my code written in functional-based views and I came to know about the generic views which are built into Django. I have made changes using Views, TemplateViews but I got stuck at FormView.
Functional Based View:
def NewTeam(request):
    form = NewTeamForm()
    if request.method == 'POST':
        form= NewTeamForm(request.POST, request.FILES)

        if form.is_valid():
            form.save(commit = True)
            return teams(request)
        else:
            print("Invalid Form")
    return render(request,'teamform.html', {'form':form})

FormView I tried
class NewTeam(FormView):
    template_name = 'teamform.html'
    form_class = NewTeamForm
    success_url = '.'

    def get_context_data(self,**kwargs):
        context = super(NewTeam, self).get_context_data(**kwargs)
        form = NewTeamForm()
        if request.method == 'POST':
            form= NewTeamForm(request.POST, request.FILES)

            if form.is_valid():
                form.save(commit = True)
                return teams(request)
            else:
                print("Invalid Form")
        context['form'] =form
        return context

I can understand that I need to get the context in the first function and create a new function form_valid. I have seen the documentation and other stack answers but I couldn't get it like how to validate the form with in it. Thanks in Advance.

A: Django FormView automatically calls validation on the form
from django.http import HttpResponseRedirect

class NewTeam(FormView):
    template_name = 'teamform.html'
    form_class = NewTeamForm
    success_url = '.'

def form_valid(self, form):
    # Form is Valid
    new_team = form.save(commit=True)

    # Do whatever

    return HttpResponseRedirect(self.get_success_url())

def form_invalid(self, form):
    # Form is Invalid
    print(form.errors)

    return self.render_to_response(self.get_context_data(form=form))


text:
Q: When does $.ajax call success in synchronous and asynchronous request? Is there a difference in when $.ajax() calls its success function depending on if I have async set to true or false?

A: Success is called after the webpage queried returns all its information to the browser without error.  i.e. http 200, 206, etc.  if it receives an error i.e. 404, 500 it calls error instead


text:
Q: NSDictionary splitting data from API I'm trying to split json data I have in a NSDictonary into smaller parts i can use, however I seem te be stuck.
The data i'm receiving from the api I use is current public transport data. This is the data I receive:
{
    Storingen =     {
        Gepland =         {
            Storing =             {
                Advies = "U kunt gebruikmaken van de omreisroute of de bussen reis tussen Alphen a/d Rijn en Gouda met de NS-bus reis vanaf zondag 29 april van Alphen a/d Rijn naar Gouda met de trein via Woerden reis tussen Leiden Centraal en Gouda via Den Haag Centraal";
                Bericht = "
\n

\n            Wanneer: van zaterdag 28 april tot en met zondag 6 mei
\n

\n            Oorzaak: door geplande werkzaamheden
\n

\n            Advies: U kunt gebruikmaken van de omreisroute of de bussen
\n
\treis tussen Alphen a/d Rijn en Gouda met de NS-bus
\treis vanaf zondag 29 april van Alphen a/d Rijn naar Gouda met de trein via Woerden
\treis tussen Leiden Centraal en Gouda via Den Haag Centraal

Extra Reistijd: een kwartier tot een half uur

\n    ";
                Oorzaak = "door geplande werkzaamheden";
                Periode = "van zaterdag 28 april tot en met zondag 6 mei";
                Traject = "Alphen a/d Rijn-Gouda";
                Vertraging = "een kwartier tot een half uur";
                id = "2012_apn_gd_28apr_6mei";
            };
        };
        Ongepland = "";
    };
}

Sofar I have this:
-(void)loadJson
{
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:kJsonURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });

}

- (void)fetchedData:(NSData *)responseData {
    NSError* error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSDictionary *storingen = [json objectForKey:@"Storingen"];
    NSDictionary *gepland = [storingen objectForKey:@"Gepland"];

    NSLog(@"%@", json);

}

Currently the api is only returning one "Gepland", planned, "Storing", malfunction. But there can be more melfunctions at the save time. The api returns this as an array in the "Storing" key. My question is, how can I, lets say, loop trough the "Storing items and user their data to make a table view with just one label and a detail view with  all the other information?

A: Use can use the data from the dictionary as the data source in your table. What I think you will have in return is an NSArray with NSDictionaries. So it should look like this:
NSArray *storingen = [json objectForKey:@"Storingen"];

for (NSDictionary *storing in storingen ){
     NSString *advies = [storing objectForKey:@"Advies"];
}

However, the anoying part with JSON and common pasers is that if there only is 1 disruption (Een storing is one disruption), you will get an NSDictionary, otherwise if there are several you will get an NSArray. You can solve that this way:
- (void)fetchedData:(NSData *)responseData {
    NSError* error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    id storingen = [json objectForKey:@"Storingen"];
    NSDictionary *gepland = [storingen objectForKey:@"Gepland"];

    NSMutableArray *result = [[NSMutableArray alloc] init];

    if ([storingen isKindOfClass:[NSArray class]]) {
        result = storingen;
    }
    else {
        [result addObject:storingen];
    }
}

Now, storingen will always be an array and you can use that array to display it in a UITableView e.g.
Veel success!


text:
Q: Asp.Identity with an existing Users table i need to prepare an MVC 5 application with an existing tbl_users table for members. Can i use or modify Asp.Identity or need to prepare a custom membership?
Please advise.
CREATE TABLE [dbo].[tbl_user](
    [id] [bigint] IDENTITY(1,1) NOT NULL,
    [user] [varchar](50) NOT NULL,
    [password] [varchar](60) NOT NULL,
    [password_raw] [varchar](255) NULL,
    [name] [varchar](255) NOT NULL,
    [email] [varchar](255) NOT NULL,
    [url] [varchar](255) NULL,
    [language] [varchar](255) NULL,
    [active] [smallint] NOT NULL,
    [session_id] [varchar](100) NULL,
    [reg_date] [datetime2](0) NOT NULL,
    [theme] [varchar](255) NULL,
    [timezone] [varchar](255) NULL,
    [last_visit_date] [datetime2](0) NULL,
    [past_visit_date] [datetime2](0) NULL,
    [activation] [varchar](32) NULL,
    [activation_date] [datetime2](0) NULL,
    [ip_address] [varchar](255) NULL,
    [security_question] [varchar](255) NULL,
    [security_answer] [varchar](255) NULL,
    [lock_url] [varchar](500) NULL,
    [lock_is_locked] [smallint] NOT NULL,
    [lock_time] [datetime2](0) NULL,
    [change_password] [smallint] NOT NULL,
    [last_change_password_date] [datetime2](0) NOT NULL,
    [expire_date] [date] NULL,
    [employee_no] [bigint] NULL,
    [student_no] [bigint] NULL,
    [parent_no] [bigint] NULL,
    [user_type] [varchar](5) NULL,
    [last_site] [varchar](50) NULL

Thank you.

A: You could derive your custom user class from IUser and define properties (extras) there. Something like this:
public class IdentityUser: IUser
{
    #region Constructors

    /// <summary>
    /// Initializes a new instance of the <see cref="IdentityUser"/> class
    /// </summary>
    public IdentityUser()
    {
        Id = Guid.NewGuid().ToString();
        Roles = (ICollection<IdentityUserRole>)new List<IdentityUserRole>();
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="IdentityUser"/> class
    /// </summary>
    /// <param name="username">Username for the user</param>
    public IdentityUser(string username): this()
    {
        UserName = username;
    }

    #endregion

    #region IUser<string> members
    // Custom properties...
    #endregion
}

You can find more information here: https://jinishbhardwaj.wordpress.com/2014/07/16/decoupling-asp-net-identity-2-0-from-entity-framework-in-mvc5-part-1/


text:
Q: Swift crash report function signature specialization Owned To Guaranteed A number of my users started getting a crash after I rewrote some Objective-C code in Swift. I cannot reproduce at all when linked to Xcode, and I cannot figure out why only a few of my users are getting the crash. I retrieved the logs from HockeyApp and the reason stated is: Selector name found in current argument registers: registeredContacts. This is an array I am dealing with in my code but under no circumstance can I get it to crash in relation to accessing or setting that array.
I think it may be my Swift block syntax and how I am calling it from Objective-C. My Swift function signature:
func retrieveActivities(handler: (([WPActivity], Error?) -> Void)?) {
and I am calling it in Objective-C with:
[[WPActivitiesManager shared] retrieveActivitiesWithHandler:nil];
Sometimes I do use the block but on startup I do not need it. As I said, this does not crash for me and there are no compiler warnings.
The top of my crash log:
Exception Type:  SIGTRAP
Exception Codes: #0 at 0x1001c0438
Crashed Thread:  0

Application Specific Information:
Selector name found in current argument registers: registeredContacts

Thread 0 Crashed:
0   Waypoint                             0x00000001001c0438 function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Owned To Guaranteed> of Waypoint.WPActivitiesManager.(retrieveActivities (handler : ([__ObjC.WPActivity], Swift.Error?) -> ()?) -> ()).(closure #2) with unmangled suffix "_merged" + 612
1   Waypoint                             0x00000001001c13a4 partial apply forwarder for Waypoint.WPActivitiesManager.(retrieveActivities (handler : ([__ObjC.WPActivity], Swift.Error?) -> ()?) -> ()).(closure #2) with unmangled suffix "_merged" + 64
2   Foundation                           0x0000000189ca2754 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 12
3   Foundation                           0x0000000189be72c8 -[NSBlockOperation main] + 92
4   Foundation                           0x0000000189bd78c4 -[__NSOperationInternal _start:] + 616
5   Foundation                           0x0000000189ca4b00 __NSOQSchedule_f + 224
6   libdispatch.dylib                    0x00000001880691c0 _dispatch_client_callout + 12
7   libdispatch.dylib                    0x000000018806dd6c _dispatch_main_queue_callback_4CF + 996
8   CoreFoundation                       0x000000018918bf2c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
9   CoreFoundation                       0x0000000189189b18 __CFRunLoopRun + 1656
10  CoreFoundation                       0x00000001890b8048 CFRunLoopRunSpecific + 440
11  GraphicsServices                     0x000000018ab3e198 GSEventRunModal + 176
12  UIKit                                0x000000018f0a42fc -[UIApplication _run] + 680
13  UIKit                                0x000000018f09f034 UIApplicationMain + 204
14  Waypoint                             0x0000000100122888 main (main.m:14)
15  libdyld.dylib                        0x000000018809c5b8 start + 0

I suspect the registeredContacts comment (added by HockeyApp I believe) is not relevant here but it is an ObjC/Swift issue. Any ideas appreciated.
The log is finally available in Xcode and I have this additional info:

A:
I suspect the registeredContacts comment (added by HockeyApp I believe) is not relevant here

No, I think you have it backwards. That is exactly what is relevant. It is your crash report that is not relevant.
SIGTRAP merely means that we got an exception. The exception is being thrown in the code (or rather, in the course of executing the code). But you don't seem to be getting any info as to what it is. My guess is that HockeyApp is actually interfering with your receiving the real report, which would tell you what the exception was.
The problem is thus somewhere in retrieveActivities. You might try to guess where by counting lines (you are told the number of lines into your method where the crash actually happens). It could be something as simple as out-of-bounds array access, I believe. The fact that an array registeredContacts is popping up here is thus quite suggestive. Look for a registeredContacts access at about that point in the method.


text:
Q: Wrong output in printf I'm new to C and trying to learn as best I can. I have this problem which I solved and the logic works pretty good, but whenever there is a wrong input it shows the message on screen and plus that the condition is not true. So whenever there is supposed to be an Invalid Input message I also get NE - which is what it would print out if the condition isn't true.
This is the code:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    if(a <= 0 || b <= 0) {
        printf("Invalid input");
    } else {
        if(a < b) {
            int tmp = a;
            a = b;
            b = tmp;
        }
    }
    a/=10;
    int c1,c2;
    while (a!=0 && b!=0){
        c1 = a%10;
        c2 = b%10;
        a /= 100;
        b /= 10;
    }
    if (c1 == c2)
        printf("PAREN\n");
    else
        printf ("NE\n");
    return 0;
}

A: Its because there is nothing thats stop it to do so:
If you just want to terminate your program just return whenever if condition is true:
if(a <= 0 || b <= 0) {
printf("Invalid input");
return 1;
 }

Alternative: Just add rest of the code under else clause.

A: Either you add a return statement as suggested in other answers, or you include everything that should happen for valid input in the first else clause (in other words, just move the closing brace of the first else clause, just before the closing brace of your main function.)

A: First, let's reformat the code so it is easier to see the control flow:
int main()
{
    int a, b;
    scanf("%d %d", &a, &b);
    if(a <= 0 || b <= 0) {
        printf("Invalid input");
    } else {
        if(a < b) {
            int tmp = a;
            a = b;
            b = tmp;
        }
    }
    a/=10;
    int c1,c2;
    while (a!=0 && b!=0){
        c1 = a%10;
        c2 = b%10;
        a /= 100;
        b /= 10;
    }
    if (c1 == c2)
        printf("PAREN\n");
    else
        printf ("NE\n");
    return 0;
}

What's happening here is that when it prints "Invalid Input" the program continues running.  From here it can either print "PAREN" or "NE".
I suspect what you actually want to do is to stop processing once you've determined that the input is invalid.
The simplest way to do this in your code would be to add "return 0;" immediately after the "printf("Invalid input");" line.


text:
Q: deleting m4a after merging youtube-dl I am trying to download a playlist from youtube but I always have this problem:

youtube-dl download video, sound and merge.

But when it tries to delete the rest, there is no progress.
[fishticker@archsamsung F1.4]$ youtube-dl https://www.youtube.com/watch?v=cKlJrMyWAE0&list=PLBD47CE9F15D97BEC
[2] 3822
[fishticker@archsamsung F1.4]$ [youtube] cKlJrMyWAE0: Downloading webpage
[youtube] cKlJrMyWAE0: Extracting video information
[youtube] cKlJrMyWAE0: Downloading DASH manifest
[download] Destination: J-doe  - #iongivafuhabownuhn (I Don't Give A Fuck About Nothing)-cKlJrMyWAE0.f137.mp4
[download] 100% of 54.17MiB in 01:29
[download] Destination: J-doe  - #iongivafuhabownuhn (I Don't Give A Fuck About Nothing)-cKlJrMyWAE0.f141.m4a
[download] 100% of 5.28MiB in 00:04
[ffmpeg] Merging formats into "J-doe  - #iongivafuhabownuhn (I Don't Give A Fuck About Nothing)-cKlJrMyWAE0.mp4"
Deleting original file J-doe  - #iongivafuhabownuhn (I Don't Give A Fuck About Nothing)-cKlJrMyWAE0.f137.mp4 (pass -k to keep)
Deleting original file J-doe  - #iongivafuhabownuhn (I Don't Give A Fuck About Nothing)-cKlJrMyWAE0.f141.m4a (pass -k to keep)

A: This is a shell problem not a youtube-dl issue, since the url contains a & character you have to quote the url:

youtube-dl 'https://www.youtube.com/watch?v=cKlJrMyWAE0&list=PLBD47CE9F15D97BEC'

otherwise youtube-dl only gets https://www.youtube.com/watch?v=cKlJrMyWAE0(you can check this by running youtube-dl with the --verbose option).
There is more info in the youtube-dl README.


text:
Q: Jenkins returns (403) Forbidden when createItem in C# I am trying to create a task with the Jenkins API.
The user has permissions but there is no way.
The error that throwing is 403.
public void CreateJobWihtXmlTemplateAndRazorRemplaceWhitAutoritazion()
{
    var configData = File.ReadAllText(configCobol);
    byte[] credentialBuffer = new UTF8Encoding().GetBytes("user" + ":" +"pass");
    var webClient = new WebClient();
    webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(credentialBuffer));
    webClient.UseDefaultCredentials = true;
    webClient.Proxy.Credentials = CredentialCache.DefaultCredentials;

    var jenkinsJobData = FactoryDataProvider.CreateJenkinsJobData();
    var result = Razor.Parse(configData, jenkinsJobData);

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(result);
    const string FORMAT = "http://{0}:{1}/createItem?name={2}";
    var path =
    string.Format(
    FORMAT,
    "someserver.example.com",
    "8080",
    jenkinsJobData.ProjectName);

    webClient.Headers["content-type"] = " application/xml";
    string response = webClient.UploadString(
    path,
    "POST",
    result
    );
    Assert.AreEqual(HttpStatusCode.OK, HttpStatusCode.OK);
}

A:
Uncheck "Prevent Cross Site Request Forgery exploits"


text:
Q: Выборка MySQL. Сортировка по тегам Добрый день, пользователи! Помогите пожалуйста составить правильный MySQL-запрос. Вопрос мой в следующем:
Есть таблица, в которой хранятся "теги" и ничего более.. В другой таблице "Новости" есть поле "tags", которое содержит ID введенных мною тегов, например, 1, 2, 4, 7.
Я передаю в функцию тег и мне нужно отсортировать все новости с этим тегом.
Не хочу использовать в таблице выборку по полю "tags" через WHERE LIKE "%%". Можете помочь и предложить хорошую и правильную альтернативу без WHERE tags LIKE "%%"?
A: Сделал на данный момент БЕЗ WHERE LIKE "%%" следующим образом. Если что поправьте меня, если ничем поправить, то может кому-нибудь и пригодиться...
SELECT
    n.id, n.text, n.tags
FROM tags t, news n
WHERE t.name="нужный тег" AND FIND_IN_SET(t.id, n.tags) > 0


text:
Q: Show Laravel Horizon jobs data After I configured Horizon to run jobs from Redis queue I can't see any logs from my jobs but I found the some suitable for me view on Horizon dashboard. I want to show there some data that I printed before to a job's log. How to configure a job to set the data field on the screenshoot?

Job's handle method just return some data but it isn't got to the view. The job's code is:
class UpdateBalanceValuesAnalyticsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the middleware the job should pass through.
     *
     * @return array
     */
    public function middleware()
    {
        return [(new WithoutOverlapping('UpdateBalanceValuesAnalyticsJob'))->dontRelease()];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $hbs = HistoricalBalance::where('watch', true)->get();

        $needProcNum =
            $hbs->map(function($hb) {
                return
                    $hb->values()->hasNotAnalytics()
                    ->orWhere(function ($query) {
                        $query->analyticsInvalidated();
                    })
                    ->count();
            })->sum();

        Log::channel('job')->info('handle UpdateBalanceValuesAnalyticsJob, processing '
            .$needProcNum.' HistoryBalanceValues');

        $alreadyReady = 0;
        foreach($hbs as $hb) {
            $userAnalytics = $hb->analytics();
            $values = $userAnalytics->valuesWithAnalyticsCalculateIncr();
            $alreadyReady += $values->count();
            Log::channel('job')->info("[$alreadyReady / $needProcNum] UpdateBalanceValuesAnalyticsJob", [
                'status' => 'calculation updated'
            ]);
        }

        Log::channel('job')->info('finish handle UpdateBalanceValuesAnalyticsJob');
        return 123;
    }
}

And Horizon config is:
'defaults' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default'],
            'balance' => 'auto',
            'maxProcesses' => 1,
            'maxTime' => 0,
            'maxJobs' => 0,
            'memory' => 128,
            'tries' => 1,
            'timeout' => 60,
            'nice' => 0,
        ],
    ],

    'environments' => [
        'production' => [
            'supervisor-1' => [
                'maxProcesses' => 10,
                'balanceMaxShift' => 1,
                'balanceCooldown' => 3,
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'maxProcesses' => 3,
            ],
        ],
    ],


text:
Q: Upgrade dual booted MacBook Pro to Lion from Snow Leopard/Ubuntu I have a MacBook Pro running Snow Leopard and Ubuntu on separate partitions. I use rEfit to choose which operating system I want to boot into. I would like to upgrade to Lion, but I'm concerned this will cause major problems due to my partitioning scheme. Has anyone else done this?

A: I used to dual boot fedora and snow leopard on a macbook pro and upgraded it to Lion no problems. You should just be able to upgrade as normal without altering your ubuntu partition, although as per Vlads answer it's always best to take a full backup first (not that I'm always very good at following that advice myself).

A: Lion upgrade should not touch your Ubuntu partition (unless you choose to repartition/format the disk). You might need to reinstall/update rEfit as well to be able to boot into Ubuntu after upgrade.
I highly recommend you take a full backup of your disk image before the upgrade to an external drive. Better safe than sorry!


text:
Q: Angular protractor test presence of modal I am trying to test that my sign up modal is presence when clicking the signup button, my problem is that it seems like protractor finish the test before angular is opening the modal and the test fails, my other solution is to use Expected Conditions, but for some reason this is not working too, the wait function does not wait the time that i set, the test is running like normal and failed.
var SignUpPage = require('./signup.page');

describe('signup page', function() {
  var SignupPage;
  beforeEach(function() {
    browser.get('http://localhost:9000');
    browser.waitForAngular();
    SignupPage = new SignUpPage();
  });

  it('should open the modal when clicking signup in the main nav', function() {
    var EC = protractor.ExpectedConditions;
    SignupPage.clickModalBtn();

    browser.wait(EC.presenceOf(SignupPage.getModalEle()), 10000);

    expect(SignupPage.getModalEle().isPresent()).toBe(true);
  });

});

The Signuppage:
function SignUpPage() {
  this.openModalBtn = element(by.css('.nav-sign-in-btn'));
  this.modal = element(by.css('.reSkill-auth'));
  this.email = element(by.css('input[type="email"'));
  this.password = element(by.css('input[type="password"'));
  this.signInBtn = element(by.css('button[type="submit"]'));
}

SignUpPage.prototype.clickModalBtn = function() {
  this.openModalBtn.click();
}

SignUpPage.prototype.getModalEle = function() {
  return this.modal;
}

SignUpPage.prototype.setEmailAndPassword = function() {
  this.email.sendkeys('mail@gmail.com');
  this.password.sendkeys('123456789');
}

SignUpPage.prototype.clickSignIn = function() {
  this.signInBtn.click();
}

module.exports = SignUpPage;

How can i test this?

A: One thing that might help is to increase the default jasmine timeout interval:
jasmineNodeOpts: {
    showColors: true,
    isVerbose: true,
    includeStackTrace: true,
    defaultTimeoutInterval: 60000  // 60 seconds
}


text:
Q: How to build a predictive model that uses only a subset of training factors , for testing? Generally, all the predictive algorithms work as follows :
input factors : x1,x2,x3,x4...xn

responses: y1,y2..ym

and the model (say M) built gives the predicted output as M(x1,x2,x3..,xn)=(Y1,Y2,..,Yk).Now suppose while training the model I have all the input factors and responses as given above  but while predicting I have only some 'j' input factors (where j < n).
Eg. I have x1,x2,x3..,xj and I want to do M(x1,x2,x3..xj).
Can I still use my model for prediction ?

A: One possible approach which is statistically sound is to build an ensemble of models using only subset of features (random) in each simple one. For example consider building something like random forest, but each tree can only use 80% of features (classical RF removes features in each node, and I am talking here about removing them globally). Then, once you train your ensemble, and you get a testing point which does not have some features - you simply use only these models from the ensemble, which are consistent with observation (were trained on features which are available). Given enough weak learners in ensemble this should work well.

A: For most models you can't. You will either have to remove the additional j-n inputs that you don't have in your predicting set and retrain the model using only j variables. Otherwise you will have to approximate the missing values.
I suggest you read some theory on the topic of 'handling missing values' in statistics for more details on how to treat such situations. There are some models which allow for missing values as well.
https://en.wikipedia.org/wiki/Missing_data

A: As always, it depends. Most common models can't handle NA values in the inputs, but you can substitute mean or median values from the training set for missing inputs. If missing predictors are of low importance, predictions could be good enough. Anyway, first thing to try is to replace missing variables with mean values from the training set and benchmark your model.


text:
Q: How to provide GraphViewDataInterface as a input to method in graphview I am trying to add a graph to my project for that purpose I am using GraphView library.
My issue here is in one of the methods drawseries expecting an interface (GraphViewDataInterface) which I am confused on how to provide as a input.
draw series method input parameters:
The method drawSeries(Canvas, GraphViewDataInterface[], float, float, float, double, double, double, double, float, GraphViewSeries.GraphViewSeriesStyle)
I have provided all parameters but struck at GraphViewDataInterface.
How can I provide an interface as a parameter to the method?
Code:
public class graph extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.graph);

        BarGraphView bgv=new BarGraphView(getApplicationContext(), "firstgraph");
        Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        bgv.drawSeries(c,
                 GraphViewDataInterface[] {10.0,10.0}, (float) 1.0,
                (float) 1.0,
                (float) 1.0,
                1.0,
                1.0,
                1.0,
                1.0,
                (float) 1.0,
                new GraphViewSeries.GraphViewSeriesStyle(1, 1));

            LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
            layout.addView(bgv);
    }

A: I'm not sure what exactly you want to do. drawSeries is an intern method. normally you never call it explicit. Take a look at the examples and the documentation.
Anyway, the GraphViewDataInterface is used to return just the x and y values. You could provide your own class and methods to do so. But normally you use the class GraphViewData that already implements that interface.
import com.jjoe64.graphview.GraphView.GraphViewData;
//...
// create data array
GraphViewDataInterface[] data = new GraphViewDataInterface[] {
  new GraphViewData(0, 1),
  new GraphViewData(1, 5),
  new GraphViewData(2, 3)
};


text:
Q: Accessing Attributes inside an object in Ruby I created a Class and created many instances and stored it into an array called messages
If I type,
print messages[0]

It gives
#<SMSMessage:0x00000001681d88 @id=29185, @account_id=1565, @upload_id=0, @txaction_type_id=9, @txid=0, @finanalytics_txid=1565,
 @date_posted=2015-05-13 17:58:01 +0530, @sequence=1, @sic_code=0,
 @amount=-1802.0, @raw_name="MERLINS", @filtered_name="MERLINS",
@cleaned_name="NULL", @merchant_id="NULL", @memo="NULL",
@check_num="NULL", @ref_num="NULL", @balance=0.0, @created_at=2015-05-13 18:03:30 +0530,
@updated_at=2015-05-13 18:08:17 +0530, @status="0", @tagged=0, @merged_with_txaction_id=0, @note="NULL", @usd_amount=0.0, @attachment_ids="NULL", @automatch=0, @merchant_name="MERLINS", @tag_names=nil, @transfer_txaction_id=0, @fi_date_posted=2015-05-13 17:58:01 +0530, @transaction_status_id=0, @mc_code="NULL", @provider_txn_type="NULL", @latitude=19.09686, @longitude=72.8537753, @sync_status=31, @sec_account_id=0, @associated_sms_id=130672, @account_key="YzI5ZDUyNWY5NmYwNWFiNjJiYmE1YTk4Y2VkYTBjYTZmOGM5ZTI0NzE2MzU2MzAwMmU2OWU2MzNiYmQ2YTZhMA==", @id_on_client=229, @sync_delete_status=0,
@matching_bill_id=0, @mapped_account_number=0, @additional_description="NULL", @category_id=45, @data_processing_flag=4,
@derived_description="NULL", @final_description="NULL", @derived_merchant="Merlins Bar", @final_merchant="NULL",
@tentative_location_flag=-1, @tentative_latitude="-90.00000000000", @tentative_longitude="-90.00000000000", @mongo_merchant_id="102", @parent_category_id=40, @raw_description="NULL", @formatted_description="NULL", @associated_sms_client_id=779, @account_client_id=4>

If i try to access the ID by typing,
print messages[0].id

It gives me an error
NoMethodError: undefined method `id' for #<SMSMessage:0x00000001681d88>

How do I resolve this ?
PS - The SMSMessage Class Code is
class SMSMessage
def initialize(id,account_id,upload_id,txaction_type_id,txid,finanalytics_txid,date_posted,sequence,sic_code,amount,raw_name,filtered_name,cleaned_name,merchant_id,memo,check_num,ref_num,balance,created_at,updated_at,status,tagged,merged_with_txaction_id,note,usd_amount,attachment_ids,automatch,merchant_name,tag_names,transfer_txaction_id,fi_date_posted,transaction_status_id,mc_code,provider_txn_type,latitude,longitude,sync_status,sec_account_id,associated_sms_id,account_key,id_on_client,sync_delete_status,matching_bill_id,mapped_account_number,additional_description,category_id,data_processing_flag,derived_description,final_description,derived_merchant,final_merchant,tentative_location_flag,tentative_latitude,tentative_longitude,mongo_merchant_id,parent_category_id,raw_description,formatted_description,associated_sms_client_id,account_client_id)
    @id = id.to_i
    @account_id = account_id.to_i
    @upload_id = upload_id.to_i
    @txaction_type_id = txaction_type_id.to_i
    @txid = txid.to_i
    @finanalytics_txid = finanalytics_txid.to_i
    @date_posted = Time.parse(date_posted)
    @sequence = sequence.to_i
    @sic_code = sic_code.to_i
    @amount = amount.to_f
    @raw_name = raw_name
    @filtered_name = filtered_name
    @cleaned_name = cleaned_name
    @merchant_id = merchant_id
    @memo = memo
    @check_num = check_num
    @ref_num = ref_num
    @balance = balance.to_f
    @created_at = Time.parse(created_at)
    @updated_at = Time.parse(updated_at)
    @status = status
    @tagged = tagged.to_i
    @merged_with_txaction_id = merged_with_txaction_id.to_i
    @note = note
    @usd_amount = usd_amount.to_f
    @attachment_ids = attachment_ids
    @automatch = automatch.to_i
    @merchant_name = merchant_name
    @tag_names = tag_names
    @transfer_txaction_id = transfer_txaction_id.to_i
    @fi_date_posted = Time.parse(fi_date_posted)
    @transaction_status_id = transaction_status_id.to_i
    @mc_code = mc_code
    @provider_txn_type = provider_txn_type
    @latitude = latitude.to_f
    @longitude = longitude.to_f
    @sync_status = sync_status.to_i
    @sec_account_id = sec_account_id.to_i
    @associated_sms_id = associated_sms_id.to_i
    @account_key = account_key
    @id_on_client = id_on_client.to_i
    @sync_delete_status = sync_delete_status.to_i
    @matching_bill_id = matching_bill_id.to_i
    @mapped_account_number = mapped_account_number.to_i
    @additional_description = additional_description
    @category_id = category_id.to_i
    @data_processing_flag = data_processing_flag.to_i
    @derived_description = derived_description
    @final_description = final_description
    @derived_merchant = derived_merchant
    @final_merchant = final_merchant
    @tentative_location_flag = tentative_location_flag.to_i
    @tentative_latitude = tentative_latitude.to_f
    @tentative_longitude = tentative_longitude.to_f
    @mongo_merchant_id = mongo_merchant_id
    @parent_category_id = parent_category_id.to_i
    @raw_description = raw_description
    @formatted_description = formatted_description
    @associated_sms_client_id = associated_sms_client_id.to_i
    @account_client_id = account_client_id.to_i
end
end

A: Since you do not define accessor methods for object attributes, you should use instance_variable_get:
messages[0].instance_variable_get(:@id)
To be able to read id attribute (that is messages[0].id) you would want to add
attr_reader :id

to your model. If you will need to write this attribute, you would define attr_writer :id.
For both (read and write) there is a attr_accessor :id.


text:
Q: Scanf on nasm assembly program I am trying to write a simple program using scanf and printf, but it is not storing my values properly.
        extern printf
        extern scanf

        SECTION .data
  str1: db "Enter a number: ",0,10
  str2: db "your value is %d, squared = %d",0,10
  fmt1: db "%d",0
  location: dw 0h

        SECTION .bss
  input1: resw 1

        SECTION .text
        global main

   main:
        push ebp
        mov ebp, esp

        push str1
        call printf
        add esp, 4

        push location
        push fmt1
        call scanf
        mov ebx, eax            ;ebx holds input

        mul eax                 ;eax holds input*input

        push eax
        push ebx
        push dword str2
        call printf
        add esp, 12

        mov esp, ebp
        pop ebp
        mov eax,0
        ret

For some reason when I run the program, no matter what number I enter, the program prints 1 for both inputs.
I am using nasm, linked with gcc

A: You're making an incorrect assumption here:
call scanf
mov ebx, eax            ;ebx holds input

scanf actually returns "the number of items of the argument list successfully filled" (source). Your integer is in location.
By the way, you should probably make location at least 4 bytes (i.e. use dd instead of dw).


text:
Q: Spring MVC POST @RequestBody don't bind to JSON string in the http request this is my signature of the POST method of my Spring MVC controller
@RequestMapping(value="/createNewGame", method=RequestMethod.POST)
       public ModelAndView createNewGame(@RequestParam(value="phoneNumber") String param,@RequestBody final SampleDTO sampleDTO) {
        Map model2 = new HashMap();
           model2.put("firstname", "Peter");
           model2.put("secondname", "Schmitt");

           return new ModelAndView("jsonView", model2);
     }

instead this is the definition of the SampleDTO class:
public class SampleDTO implements Serializable{

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

I'm not able to execute the request for this method. I have this error from the client:
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.supports(Ljava/lang/Class;)Z

after execute this POST request with RestClient app with these parameters:
http://localhost:8080/SpringExample5/createNewGame.json?phoneNumber=6   (POST)

Content-Type application/json  (Header attribute)

{ "value": "a" }      (Body)

This is also the configuration of Spring in my web app:
<bean name="/gameController.json"
          class="com.alu.server.games.acquisition.controllers.GameController"/>

<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
    <property name="objectMapper">
            <ref bean="JacksonObjectMapper" />
       </property>
</bean>

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonHttpMessageConverter" />
        </list>
    </property>
</bean>

<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="objectMapper">
         <ref bean="JacksonObjectMapper" />
    </property>
</bean>

<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

Someone can help me in order to find the problem?
Thanks in advance !

A: In the setting I used I did specify the Media Type to be "application/json" both in the web service's annotation as well as the XML configuration for json message converter.
Please checkout my FAQ on the matter here for further details.


text:
Q: Debug Quasar V2 using WebStorm 2021 I have set the following in quasar.conf.js:
build: {
     devtool: 'source-map'
}

Then I run quasar serve in terminal and run debug using WebStorm with the following configuration but the breakpoint is not triggered.
What can be the issue?


text:
Q: LSTM tensorflow shape error? I have a Class for RNN that can classify the sentences into positive or negative for sentiment analysis. Because the length of sentences are different, so I used placeholder named text_len to be a vector of sentence lengths in one batch when feeding the training batch data:
class TextRNN:
def __init__(self, hidden_size, num_classes, text_length, vocab_size,
    embed_size, l2_lambda=0.001):

    self.input_data = tf.placeholder(tf.int32,[None,text_length],name="input_data")
    self.output_label = tf.placeholder(tf.float32,[None,num_classes],name="output_label")
    self.dropout_rate = tf.placeholder(tf.float32,name="dropout_rate")
    self.text_len = tf.placeholder(tf.int32, [None])

    with tf.name_scope("embedding"):
        self.W = tf.Variable(tf.random_uniform([vocab_size,embed_size],-1.0,1.0),trainable=True,name="W")
        self.word_embeddings = tf.nn.embedding_lookup(self.W, self.input_data)

    with tf.name_scope("hidden"):
        lstm_fw_cell=rnn.BasicLSTMCell(hidden_size)
        lstm_bw_cell=rnn.BasicLSTMCell(hidden_size)
        lstm_fw_cell=rnn.DropoutWrapper(lstm_fw_cell,output_keep_prob=self.dropout_rate)
        lstm_bw_cell=rnn.DropoutWrapper(lstm_bw_cell,output_keep_prob=self.dropout_rate)
        outputs,_=tf.nn.bidirectional_dynamic_rnn(lstm_fw_cell,lstm_bw_cell,inputs=self.word_embeddings,sequence_length=self.text_len,dtype=tf.float32)

In my main method:
for ex in range(1,3):
    with tf.Graph().as_default():
        sess = tf.Session()
        with sess.as_default():
            rnn = TextRNN(
            hidden_size=100,
            num_classes=2,
            text_length=160,
            vocab_size=len(vocab_processor.vocabulary_),
            embed_size=100,
            l2_lambda=0.001)

            global_step = tf.Variable(0, name="global_step", trainable=False)
            optimizer = tf.train.AdamOptimizer(1e-3)
            grads_and_vars = optimizer.compute_gradients(rnn.loss)
            train_op = optimizer.apply_gradients(grads_and_vars,global_step=global_step)

            sess.run(tf.global_variables_initializer())
            vocabulary = vocab_processor.vocabulary_

            initW = None
            initW = loadw2v.convert_glove(vocabulary, pretrained_embeddings, 100)
            sess.run(rnn.W.assign(initW))

            #training step
            def train_step(x_batch, y_batch, start_index, end_index):
                feed_dict = {rnn.input_data:x_batch,rnn.output_label:y_batch,rnn.dropout_rate:0.5,rnn.text_len:x_train_len[start_index:end_index]}
                _, step, loss, test = sess.run([train_op, global_step, rnn.loss, rnn.text_len], feed_dict)

because I want to feed a vector of sequence length into RNN model, so there is a rnn.text_len:x_train_len[start_index:end_index] when using tf.nn.bidirectional_dynamic_rnn, x_train_len[start_index:end_index] is a vector that saves the length of sequence, start_index is the index of batch start, end_index is the index of batch end. The error is:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1327, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1306, in _run_fn
    status, run_metadata)
  File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 88, in __exit__
    next(self.gen)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: seq_lens(45) > input.dims(1)
     [[Node: hidden/bidirectional_rnn/bw/ReverseSequence = ReverseSequence[T=DT_FLOAT, Tlen=DT_INT32, batch_dim=0, seq_dim=1, _device="/job:localhost/replica:0/task:0/cpu:0"](embedding/embedding_lookup, _arg_Placeholder_0_0)]]

I don't understand this error, any idea?


text:
Q: Non-string "Symbol" object in python? Does Python have a builtin type for representing symbolic values, when strings cannot be used?
A quick implementation of my own would look like
class Symbol:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name

Usecase
Such symbols are useful when a value – say a keyword argument or a list entry – needs to be initialized to a value that indicates that it hasn't been explicitly set.
If the values have constraints on allowed types, commonly None or some string would be used, but if any value is allowed, some other unique object is needed. My common method is to use an object() assigned to some private variable, but the symbol pattern is more convenient for debugging due to providing a meaningful printed representation.
As an alternative, one could use e.g. a tuple ('default value',) and compare against it with the is operator, but this wouldn't work e.g. for dictionary keys.
While the pattern is simple enough to copy/paste into each shell-script I am writing, a builtin solution with established behavior would be preferable.
Non-builtins
I know, that there are packages that provide a symbol type. An obvious one would be the symbol type of sympi, and there is https://pypi.org/project/SymbolType/. However, adding dependencies to avoid a 5-line pattern seems a heavy overkill, hence my question about a builtin type.

A: You could use the enum library:
https://docs.python.org/3/library/enum.html


text: Q: Request.Form.Count is 0 when calling aspx page i am trying to post to an aspx page using form post below is the code.Where as value is going but request.form.count is '0'. Therefore i am not able to call a method in requested page.Well this works on local host but not on iis.


text:
Q: Mutual effect of model variables I have a simple GUI I would like to implement via pure AngularJS - there are two (or more) groups of checkboxes like here: http://jsbin.com/cemitubo/2/edit
Here is the code from the link below:
HTML:

    <input type="checkbox" ng-model="tag.aaa"/>
    <input type="checkbox" ng-model="tag.ccc"/>

    <input type="checkbox" ng-model="tag.zzz"/>

  {{tag}}

JS:
angular.module('myApp', [])
.controller('MyController', function($scope){
  $scope.tag = {aaa: true};
});

Once A checkbox of one of the groups is checked all the checkboxes of the other groups should be unchecked (and the change obviously should be reflected in the model).
I tried to $watch the tag model variable and setting false to the variables of the other groups in $watch callback. The problem is that it fires the $watch callback each time tag is changed by $watch callback.
What is the proper AngularJS solution?
Thanks in advance!

A: Use ng-change instead $watch:
Something like:
  $scope.changed = function(item, type){
    console.log(item);

    if((type == 'aaa' || type == 'ccc') ){
      $scope.tag.zzz = !item;
    }
    else  if(type == 'zzz'){
      $scope.tag.aaa = !item;
      $scope.tag.ccc = !item;
    }
  }

HTML

    <input type="checkbox" ng-model="tag.aaa" ng-change="changed(tag.aaa,'aaa')"/>
    <input type="checkbox" ng-model="tag.ccc" ng-change="changed(tag.ccc,'ccc')"/>

    <input type="checkbox" ng-model="tag.zzz"  ng-change="changed(tag.zzz, 'zzz')"/>

Demo JSBIN


text:
Q: problem with filtering data from 2 tables in sql? I have 2 tables Project and Plan which has below feeds:
Project

*

*ProjectId

*ProjectName

*Status

Plan

*

*PlanId

*ProjectId

*PlanName

*Status

Each project can have Zero or more plans in the plan table.
I would like to get the list of all projects from the table with the count of plan against each project.
I have tried the below Linq query to join the table
var project=(from p in _dbContext.Projects
        join pl in _dbContext.Plan
            on p.ProjectId equals s.ProjectId
        into temp
        from j in temp.DefaultIfEmpty()
        select new ReturnDto
        {
            ProjectId = p.ProjectId,
            ProjectName = p.ProjectName,
            PlanCount = "(Need the count of plans against the project)"
        }).ToList();

Any help will be appreciated!

A:
get the list of all projects from the table with the count of plan

I think that you want to know for every Project the number of Plans that it has.
Whenever you have a one-to-many relation, and you want to get "Items with their zero or more subitems", like Schools with their Students, Customers with their Orders, or in your case Projects with their Plans, consider to use one of the overloads of Queryable.GroupJoin
I use the one with a parameter resultSelector to specify the results:
IQueryable<Project> projects = ...
IQueryable<Plan> plans = ...

var projectsWithPlanCount = projects.GroupJoin(plans,

    project => project.Id,       // from every Project take the primary key
    plan => plan.ProjectId,      // from every Plan take the foreign key to Project

    // parameter resultSelector: from every Project with its zero or more Plans, make one new:
    (project, plansOfThisProject) => new
    {
        // Select the project properties that you plan to use
        Id = project.Id,
        Name = project.Name,
        ...

        PlanCount = plansOfThisProject.Count(),
    });

Simple comme bonjour!


text:
Q: Cannot execute database statement from another php file using include What I'm doing wrong after adding class define to StoreUser.php file and calling it from  store.php file because it doesn't work any moore? It worked fine inside file StoreUser.php without class define and function see below.

$dbhost = "localhost";
$dbname = "riskinarviointilomake";
$dbuser = "root";
$dbpass = "";
//private $email;

if(isset($_GET["email"])){

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (!( $stmt = $conn->prepare("INSERT INTO users(unique_id,email,
  encrypted_password) VALUES(?,?,?)"))){

    echo "Table creation failed: (" . $conn->errno . ") " . $conn->error;
}
    $stmt->bind_param('sss', $unique_id,$email,$password);

    $unique_id=123457764;
    $password="df12467hh";

    $result = $stmt->execute();
    $stmt->close();
    $conn->close();

   }

  ?>

This doesn't work
class StoreUser{

$dbhost = "localhost";
$dbname = "riskinarviointilomake";
$dbuser = "root";
$dbpass = "";
//private $email;

public function store($email){
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (!( $stmt = $conn->prepare("INSERT INTO users(unique_id,email, encrypted_password) VALUES(?,?,?)"))){

    echo "Table creation failed: (" . $conn->errno . ") " . $conn->error;
}
    $stmt->bind_param('sss', $unique_id,$email,$password);

    $unique_id=123457764;
    $password="df12467hh";

    $result = $stmt->execute();
    $stmt->close();
    $conn->close();

 }

}
    <?php

    include 'StoreTest.php';

   if(isset($_GET['email'])){
     $email = $_GET['email'];
     $store = new StoreTest();
     $store->store($email);

   }

 ?>


text:
Q: How to bind object on DataGridRow In my DataGrid if I have the following binding I get the User_ID no problem. Each row is a User record. How do I change this to bind the actual User Object? So I can send it into my converter.
{Binding Path=DataContext.User_ID, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}"

A: Try to remove .User_ID from binding path :
{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}"

A: Remove the 'path' from the binding as follows:
{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}


text:
Q: How to connect with social websites from java application? when we use these api

*

*For Twitter: twitter4j

*For Facebook: fb-java-api

*For Linkedin: linkedin-j

we will be redirected to particular site
(if i use linkedin-j, it will redirect to linkedin and so to all api) and get user information like user name and password
to verify them to allow access. but my question is having username and password only once, we have to collect all the details from facebook,linkedin,twitter etc.

A: You usually get a secret token after you've successfully authenticated with the sites. Store it until you log out and use it for your API calls. You do not (shouldn't) get username and password from the site, if the user uses the site's login dialog.


text:
Q: To post an array of data pushed from UI using Angularjs I made an array to push data through UI, what I want is to send the created array using angularjs post.
Here is my code:-
$scope.clinicWorkingSchedules = [
        {   workingDay: '',
            workingHours: []
        }
      ]

  $scope.sendClinicTiming= function(id,workingDay,fromTime,toTime){

   var data={
          'id':id,
          'clinicWorkingSchedules':clinicWorkingSchedules
         };
   $http.post($scope.API_url,
    data, config)
    .success(function(data, status));

  };

id is going correctly, but not able to send array.
Any help is appreciated.
Thanks

A: $scope.clinicWorkingSchedules = [
        {   workingDay: '',
            workingHours: []
        }
      ]

  $scope.sendClinicTiming= function(id,workingDay,fromTime,toTime){

   var data={
          'id':id,
          'clinicWorkingSchedules':$scope.clinicWorkingSchedules
         };
   $http.post($scope.API_url,
    data, config)
    .success(function(data, status));

  };

A: $scope.clinicWorkingSchedules =
        {   workingDay: '',
            workingHours: {'fromTime':'', 'toTime':''}
        }

$scope.sendClinicTiming= function(id,workingDay,fromTime,toTime){

$scope.clinicWorkingSchedules.workingDay = workingDay;
$scope.clinicWorkingSchedules.workingHours.fromTime = fromTime;
$scope.clinicWorkingSchedules.workingHours.toTime= toTime;

   var data={
          'id':id,
          'clinicWorkingSchedules':$scope.clinicWorkingSchedules
         };
   $http.post($scope.API_url,
    data, config)
    .success(function(data, status));

  };

A: You forgot to add $scope before the array. The rest of your code is perfectly fine. Here is the code with changes.
var data={
    'id':id,
    'clinicWorkingSchedules': $scope.clinicWorkingSchedules
};


text:
Q: Get the current effective date from the list of records has past and future dates in SQL Server I'm having list of records with a column EffectiveOn in SQL Server database table. I want to fetch the currently applicable EffectiveOn respective to current date. Consider the following table
Id         Data        EffectiveOn
_____________________________________
1          abc         2020-04-28
2          xyz         2020-08-05
3          dhd         2020-10-30
4          ert         2020-12-28
5          lkj         2021-03-19

In the above table I have to fetch the record (Id: 3) because the current date (i.e., today) is 2020-11-19
Expected Resultset
Id         Data        EffectiveOn
_____________________________________
3          dhd         2020-10-30

I tried the following solution but I can't How do I get the current records based on it's Effective Date?
Kindly assist me how to get the expected result-set.

A: You can do:
select top (1) *
from mytable t
where effectiveon <= convert(date, getdate())
order by effectiveon desc

This selects the greatest date before today (or today, if available).

A: You can try using Row_number function
select id, data, effectiveon
(
    select ROW_NUMBER()over(order by effectiveon desc )sno,* from #table
    where effectiveon < cast(getdate() as date)
)a where sno=1


text:
Q: Update my HTML5 slider with up/down buttons I am new to HTML and I would like to update a slider based on button presses.  That is, each time I select "UP" or "Down" the slider traverses with the change in value of "range2"
I am combining a slider with buttons to allow setting the to be more precisely with the slider and/or more grossly with the buttons:

Here is how I construct the sliders and buttons:

Thermostat Setting

      <input id="tstatRange" type="range" style="width: 200px; height 40px" min="72.0" max="86.0" value="76" step = "0.5" list="increments" oninput="showMainTstatValue(this.value)" onchange="showMainTstatValue(this.value)">
      <datalist id="increments">
       <option>72</option>
       <option>74</option>
       <option>76</option>
       <option>78</option>
       <option>80</option>
       <option>82</option>
       <option>84</option>
       <option>86</option>
      </datalist>
      76.0°F

      <input type="button" onclick="sendMainTstatValue()" value = SUBMIT />

      <input type="button" class="button" value="UP" onclick="tstatUP()">

      <input type="button" class="button" value="DOWN" onclick="tstatDN()">

and here are my functions:

function showMainTstatValue(newValue)
{
  document.getElementById("range2").innerHTML = newValue;
}

function tstatUP()
{
 var newValue = document.getElementById("range2").innerHTML;
 newValue++;
 if(newValue > 86) newValue = 86;
 document.getElementById("range2").innerHTML = newValue;
}

function tstatDN()
{
    var newValue = document.getElementById("range2").innerHTML;
 newValue--;
 if(newValue < 72) newValue = 72;
 document.getElementById("range2").innerHTML = newValue;
}

function sendMainTstatValue()
{
 var newValue = document.getElementById("range2").innerHTML;
 var request = new XMLHttpRequest();
 var url = 'http://10.0.1.25:3480/data_request?id=action&output_format=xml&DeviceNum=3&serviceId=urn:upnp-org:serviceId:TemperatureSetpoint1_Cool&action=SetCurrentSetpoint&NewCurrentSetpoint='+newValue;
 request.open('GET', url);
 request.send();
}

A: Your slider is not updating the values entered by the button. Try to not only set the label's ("range2") innerHTML, but remember to set the actual slider's ("tstatRange") value in your tstatUP() and tstatDN() functions:
document.getElementById("tstatRange").value = newValue;


text:
Q: [Flutter - Mapbox GL]How to add Symbol on initial map load? I tried adding a Map marker using the mapController's addSymbol method but apparently the marker does not show on the map
void _onMapCreated(MapboxMapController controller) async {
  mapController = controller;

  deviceMarker = await mapController!.addSymbol(SymbolOptions(
      geometry: LatLng(deviceLongitude, deviceLatitude),
      iconImage: "assets/map_marker_device.png",
      iconSize: 0.1,
      iconOffset: const Offset(0, -150)));
}

A: You need to load the image first and then manually provide it to the controller; the string you pass to iconImage is arbitrary and just identifies the image you give it in MapboxMapController .addImage
Future<Uint8List> loadMarkerImage() async {
  var byteData = await rootBundle.load("assets/images/custom_marker.png");
  return byteData.buffer.asUint8List();
}

void _onMapCreated(MapboxMapController controller) async {
  var markerImage = await loadMarkerImage();

  controller.addImage('marker', markerImage);

  await controller.addSymbol(SymbolOptions(
      iconSize: 0.1,
      iconImage: "marker",
      geometry: location,
      iconOffset: const Offset(0, -150)));

}