text:
Q: Parse a string Pandas I have the following string in a pandas dataframe:
app:fb,msg:something1, somethin2..
app:fdsfe,msg:Service Temporarily Unavailable
app:unknown,size:416746,msg:blabla

I want to parse this columns to have three distinct colum (app, msg, size); for now I do the following:
df["message_soft"] =  df['message'].str.extract(".*app:([\.'A-Za-z\s0123456789déèàç^êâôîè-]*),.*",expand=False)
df["message_content"] =  df['message'].str.extract('.*msg\:(.*).*', expand=False)
df["message_size"] =  df['message'].str.extract('.*size\:(\d{0,10})\,.*', expand=False)

My partern inside 'message', is often:
'app: [msg: [\.'A-Za-z\s0123456789déèàç^êâôîè-] ' --> So in message I can have a ","

but sometime I could have other fields in between:
'app: .., size: /d ,msg: .... ' --> So in message I can have a ","

My solution works but it's way to long (regex hurts !), and to not take into account the partern. Anyidea?


text:
Q: In a Python for loop, If you define a variable as an element for the for loop, will it overwrite the previous definition? So in this example, although you cant refer anymore to the previous loopRads, python obviously still knows it exist right? That is why when the radiobutton widget is invoked, it functions properly? So basically Python knows which loopRad you're referring to when you clicked on the radiobuttons?
colors = ['red', 'blue', 'gold']

def radCall(*args):
    radSel = radVar.get()

    if radSel == 0:
        root.configure(background=colors[0])
    elif radSel == 1:
        root.configure(background=colors[1])
    elif radSel == 2:
        root.configure(background=colors[2])

for col in range(3):
    loopRad = ttk.Radiobutton(root, text=colors[col], variable=radVar, value=col, command=radCall)
    loopRad.grid(row=5, column=col, sticky='w')

A: In loopRad = ttk.Radiobutton(root, text=colors[col], variable=radVar, value=col, command=radCall) you have redefined any previous value assigned to loopRad.
Not only that reassignment is the valid one inside the scope of the loop, it will also remain after it.
Furthermore, in Python, even if the variable loopRad was never declared before the line for col in range(3):, it would be still accessible outside the scope of the loop. That is not the case in some other languages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Boundary condition as $\lim_{x\rightarrow\infty} y(x) = 0$ for hermite differential equation solution? I have found that for the Hermite differential equation,
$$
y'' -2xy' +2\lambda y = 0
$$
Solutions exist in multiple forms:
$\bullet$ Popularly, the Hermite polynomials are solutions for $\lambda = 0,1,2,3...$:
$$
H_\lambda(x) = (-1)^\lambda e^{x^2}\frac{d^\lambda}{dx^\lambda}e^{-x^2}
$$
using the Rodrigues formula.
$\bullet$ Another way I found is by solving the d.e. with a series solution, which yields two linearly independent solutions:
$$
y_1(x) = 1 + \sum_{k=1}^{\infty}{(-1)^k \frac{2^k \lambda(\lambda - 2)(\lambda - 4)...(\lambda-2k+2)}{(2k)!}x^{2k}} \\
y_2(x) = x + \sum_{k=1}^{\infty}{(-1)^k \frac{2^k (\lambda-1)(\lambda - 3)...(\lambda-2k+1)}{(2k+1)!}x^{2k+1}}
$$
and the total solution is $y(x) = a_0y_1(x) + a_1y_2(x)$.
$\bullet$ I also used Sturm-Liouville theory to change the d.e. to this eigenvalue equation:
$$
-\frac{d}{dx}[e^{-x^2}y'] = 2\lambda e^{-x^2}y
$$
but haven't been able to derive any solution for $y(x)$ outside of the above.
My goal is to generate two linearly independent solutions that satisfy this boundary condition:
$$\lim_{x \rightarrow \infty} y(x) = 0$$
My hint was to use the Sturm-Liouville method and I was told the boundary condition would become obvious. At present I still don't know how to solve the Sturm-Louiville equation that I've verified in correct form above.
Guidance is tremendously appreciated!

A: As you mentioned, your equation can be written in the Sturm-Liouville normal form
$$
               -\frac{d}{dx}e^{-x^2}\frac{d}{dx}y=\lambda e^{-x^2}y.
$$
That puts the problem into the context of $L^2_{e^{-x^2}}(\mathbb{R})$. For $\lambda = 0$, the solutions are
$$
                 e^{-x^2}y'= C \\
                     y' = Ce^{x^2} \\
                     y = C\int_{0}^{x}e^{t^2}dt+D.
$$
Only one of the two solutions is in $L^2_{e^{-x^2}}(\mathbb{R})$ near $x=\infty$ or near $x=-\infty$. Therefore, the equation is in the limit point case at both endpoints $x=\pm\infty$. That means that, for every $\lambda\in\mathbb{C}$, there is only one solution $y$ of the eigenvalue equation that is in $L^2_{e^{-x^2}}[0,\infty)$. However, if both linearly independent solutions were to satisfy your condition, then they would definitely be in $L^2_{e^{-x^2}}[0,\infty)$. So what you want is impossible.


text:
Q: How can I get the URL of the currently connected MongoDB database from inside Meteor? Background: I am preparing a Meteor app for production, and in particular I am adding server logging. To do this I am using winston with the MongoDB plugin. This requires the URL to the database. These databases are different between production and development environments so I want to set it programatically.
I am trying to avoid running forking a script to run
# meteor mongo --url

I also don't have access to $MONGO_URL on the development server (it doesn't appear to be set, for instance in process.env.MONGO_URL)
I expect that there is something like below, but I couldn't find this in the documentation or via Google.
Meteor.MongoDB.getURL();

Sorry if this is something really obvious...it feels like it should be easy.

A: This works server side. It needs Meteor 1.0.4+ (I think. Added somewhat recently):
var collection = new Mongo.Collection("some_collection");

console.log(collection.rawCollection().db.options.url)

Keep in mind you can have multiple MongoDB's (at least at the collection level, or this is how the design is at least, anyway) so you need to query a collection for its Mongo URL.

A: I found the answer.
As mentioned in the question, the MONGO_URL environmental variable was undefined, but that appears to be either a misunderstanding or a bug in my IDE.
When I logged the value of process.env, I saw that MONGO_URL was indeed set, so I've used that.
In short:
process.env.MONGO_URL


text:
Q: What's the scenario of share session on server side? What's the scenario of share session on server side? And is there some approach to share the session on server side in JAVA EE platform?

A: On Java EE you must review the Servlet Specification, the object HttpSession provides the behavior for manage the session on the server side.
http://docs.oracle.com/javaee/5/tutorial/doc/bnagm.html
Although you can store any object in the session, this practice can be dangerous because the objects remain on session until it expires or the object is removed, so if your program doesn't manage well the objects that are stored in the session you can consume to many heap memory.
The objects of session are deleted when it expires, the expiration time is configured in the deployment descriptor web.xml or can be set by client. If you don't specify a time for session expiration then the default is 30 minutes, this 30 minutes are counted from the last request made by the user.
My recommendation is that you don't store objects in session, you must use the object HttpServletRequest and the mehtos setAttribute and getAttribute for pass objects between requests. I you need store a value on session you can store the ID of a product instead the whole product. A common use of the session is for store variables that must live for more than a request and you don't want to store it on cockles for security reasons.

A: As the problem does not explicitly say the objects between which session needs to be shared, I can suggest following options:
1) If you need to share session between different web apps on the same server (tomcat) , you can use:
<Host name="localhost" ...>
  <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
</Host>

2) If the server is not tomcat, please refer to SSO option for the respective server.
3) You can as well use a full fledged SSO product like CAS (http://www.jasig.org/cas) which will allow you to share sessions across apps across different servers but not between users.
4) If you need to share session between different users, all you need to do is pass on the session ids between different clients (typically browsers) based upon your share criteria like, people playing same game, accessing same bulletin board and can collaboratively changing the data. However, please understand most of the security infrastructure is built around mapping of session ids. If you choose to make the session ids explicitly accessible between multiple users, you would have to re-create lots of security filters yourself.
5) Alternatively, best approach will be to manage the state of the object differently from session. The state of the shared object can be shared across multiple sessions in much more standards compliant secure and auditable way.


text:
Q: How can i hit the rss feed url in jquery I want to hit this url using jquery
http://localhost:8161/admin/queueBrowse/sourcename?view=rss&feedType=rss_2.0

How can i do this by passing the parameters as view=rss&feedType=rss_2.0

A: To load that XML file via AJAX for processing with jQuery, you can use the following code:
$.get("http://localhost:8161/admin/queueBrowse/sourcename", {
        view: 'rss',
        feedType: 'rss_2.0'
    }, function (xml) {
        // process xml here

    }, "xml");

Documentation: http://api.jquery.com/jQuery.get/

A: you can use this..
$.ajax({
        type: "GET",
        url: "//localhost:8161/admin/queueBrowse/sourcename",
        data:{
              view: 'rss',
              feedType: 'rss_2.0'
             }
        dataType: "xml",
        success: xmlParser
    });

function xmlParser(xml){
//process XML
}


text:
Q: Use Sequelize to get Json from value I have to get value from 1 col which currently stores a JSON as TEXT:

col1: {"class":{"count":3,"number":25}}

So when I use sequlize orm with option:
..attributes: ['id', 'col1']..

it returns value in:
"{\"class\":{\"count\":3,\"number\":25}}"

How can I use something like:
..attributes: ['id', sequelize.json('col1')]..

to get data in JSON format?
Thanks

A: I don't know about sequelize.json...
You could use JSON.parse and a getter on the column.
 sequelize.define('your_table', {
   col1: {
     type: DataTypes.TEXT,
     get(val) { return JSON.parse(val) }
   }
 })

But Postgres (and I think MySQL, although I don't see it in the sequelize docs) have JSON field types. They'll be much better. You can query by both keys and values at arbitrary nesting. You can also create indexes. Again, they may only be possible with Postgres.
 sequelize.define('your_table', {
   col1: {
     type: DataTypes.JSONB,
   }
 })

A: I guess you need to set {raw: true} when you are making a find query in database. This will return json object

A: I had the same problem as you and here is my solution:
sequelize.define("your_table", {

col1: {
      type: Sequelize.STRING,
      get: function () {
                 return JSON.parse(this.getDataValue("col1"));
             }
     }
})


text:
Q: JPanel size not being set I'm currently working on an irc bot and today I would like to create a GUI for it.
I'm trying to create a column layout that has two parts, left and right.
The left side will show console output, the right will contain all the controls (joining channels, commands etc).
I'm having issues creating the two columns. I have a JPanel that is the whole width and height of the window and has a border of 10 pixels, and then I have two panels within that; left and right.
The left and right panels are for some reason taking the whole size of the window, and the right panel is overlapping everything.
Here's an example picture: http://i.imgur.com/lc4vHVH.png

The white is the right panel, it should only be half the size and have an identical but black panel on the left of it.
Here's my current code, sorry if it's messy, new to the whole Swing GUI.. Thanks for any help.
package tk.TaylerKing.GribbyBot;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import com.alee.laf.WebLookAndFeel;
import com.alee.laf.menu.WebMenuBar;
import com.alee.laf.menu.WebMenuItem;
import com.alee.laf.panel.WebPanel;
import com.alee.laf.rootpane.WebFrame;

public class GribbyBot extends WebFrame {
    private static final long serialVersionUID = 4641597667372956773L;
    public static HashMap<String, ArrayList<String>> connections = new HashMap<String, ArrayList<String>>();
    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(WebLookAndFeel.class.getCanonicalName());
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                GribbyBot gb = new GribbyBot();
                gb.setVisible(true);
            }
        });
    }
    public GribbyBot(){
        WebPanel panel = new WebPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.setPreferredSize(new Dimension(780, 580));

        WebMenuBar menu = new WebMenuBar();
        WebMenuItem file = new WebMenuItem("Exit");
        file.setMnemonic(KeyEvent.VK_E);
        file.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        menu.add(file);
        setJMenuBar(menu);

        WebPanel left = new WebPanel();
        left.setPreferredSize(new Dimension(380, 580));
        left.setBackground(Color.BLACK);

        WebPanel right = new WebPanel();
        right.setPreferredSize(new Dimension(380, 580));
        right.setBackground(Color.WHITE);

        add(panel);
        panel.add(left);
        panel.add(right);
        setTitle("GribbyBot");
        setSize(800, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
    }
}

On a side note, all the variables that are prefixed with "Web" are the same as Swing, but it's a custom GUI.

A: Override JComponent#getPreferredSize() instead of using setPreferredSize()
Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
If extremely needed in case of Performing Custom Painting then try in this way:
Sample code:
final JPanel panel = new JPanel(){
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        // your custom painting code here
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(40, 40);
    }
};

Why are using setPreferredSize() method whereas you can achieve this design easily using any proper layout such as BoxLayout, GridLayout, BorderLayout etc.
Read more about layout How to Use Various Layout Managers
EDIT
try JPanel panel = new JPanel(new GridLayout(1,2));


text:
Q: How to pass any selected option value from a view to a controller ASP.NET Core This is my code. I want to select a option and pass the value in controller.

                        Mobile Number
                        <input asp-for="MobileNumber" class="form-control" />

                         Gender
                          <select asp-for="Gender" id="inputState" class="form-control">
                            <option selected>Please Choose...</option>
                            <option>Male</option>
                            <option>Female</option>
                            <option>Other</option>
                          </select>

This is Controller Action. I want to get select option value this action.
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                model.Resolve(_scope);
                await model.UserCreate();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "User not create.");
            }
        }
        return View(model);
    }

A: Not sure about the full context of the CreateModel object, specifically what type is Gender, but I'm assuming it's string.
One thing that you are missing is defining values for the select options.
You need to do something similar to this in order to give a value for each option:
<select asp-for="Gender" id="inputState" class="form-control">
    <option selected>Please Choose...</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Other">Other</option>
</select>

Let me know if it helped!


text:
Q: Firebase vs BigQuery Active Users Discrepancies I've integrated my Firebase project with BigQuery. Now I'm facing a data discrepancy issue while trying to get 1 day active users, for the selected date i.e. 20190210, with following query from BigQuery;
SELECT COUNT(DISTINCT user_pseudo_id) AS 1_day_active_users_count
FROM `MY_TABLE.events_*`
WHERE event_name = 'user_engagement' AND _TABLE_SUFFIX = '20190210'

But the figures returned from BigQuery doesn't match with the ones reported on Firebase Analytics Dashboard for the same date. Any clue what's possibly going wrong here?
The following sample query mentioned my Firebase Team, here https://support.google.com/firebase/answer/9037342?hl=en&ref_topic=7029512, is not so helpful as its taking into consideration the current time and getting users accordingly.
N-day active users
/**
 * Builds an audience of N-Day Active Users.
 *
 * N-day active users = users who have logged at least one user_engagement
 * event in the last N days.
*/
SELECT
  COUNT(DISTINCT user_id) AS n_day_active_users_count
FROM
  -- PLEASE REPLACE WITH YOUR TABLE NAME.
  `YOUR_TABLE.events_*`
WHERE
  event_name = 'user_engagement'
  -- Pick events in the last N = 20 days.
  AND event_timestamp >
      UNIX_MICROS(TIMESTAMP_SUB(CURRENT_TIMESTAMP, INTERVAL 20 DAY))
  -- PLEASE REPLACE WITH YOUR DESIRED DATE RANGE.
  AND _TABLE_SUFFIX BETWEEN '20180521' AND '20240131';

A: So given the small discrepancy here, I believe the issue is one of timezones.
When you're looking at a "day" in the Firebase Console, you're looking at the time interval from midnight to midnight in whatever time zone you've specified when you first set up your project. When you're looking at a "day" in BigQuery, you're looking at the time interval from midnight to midnight in UTC.
If you want to make sure you're looking at the events that match up with what's in your console, you should query the event_timestamp value in your BigQuery table (and remember that it might span multiple tables) to match up with what's in your timezone.


text:
Q: 3d / 2.5d game library for iphone and pc I'm trying to make a 2d shooter game with 3d background.
The player and enemies are essentially just quads with textures.
The background will be simple 3d polygons with textures and some fog and light.
Therefore, I don't need a really powerful 3d library.
I tried Unity3D and Torque2D, but I don't like to use their GUI editors. I prefer to work with code.
So, is there a cross platform (mainly windows and iPhone) 3d / 2.5d game library, commercial or open source?
I assume it will be only limited to c, c++, and object-c due to apple's new ToS.

A: Cocos2D works on iPhone.

A: I recall that there is an Ogre3D port to iPhone, but I don't remember its name just now.

A: If you just want some simple images you can just use OpenGL ES. I've heard it's quite nice to program with it on iPhone. Also, take a look at parallax. If you want to do 2.5D games I think it's a must.
Good luck


text:
Q: Equation to distribute items unevenly I'm writing a javascript program that sends a list of MIDI signals over a specified period of time.
If the signals are sent evenly, it's easy to determine how long to wait in between each signal: it's just the total duration divided by the number of signals.
However, I want to be able to offer a setting where the signals aren't sent equally: either the signals are sent with increasing or decreasing speed. In either case, the number of signals and the total amount of time remain the same.
Here's a picture to visualize what I'm talking about
Is there a simple logarithmic/exponential function where I can compute what these values are? I'm especially hoping it might be possible to use the same equation for both, simply changing a variable.
Thank you so much!

A: Since you do not give any method to get a pulse value, from the previous value or any other way, I assume we are free to come up with our own.
In both of your cases, it looks like you start with an initial time interval: let's call it a. Then the next interval is that value multiplied by a constant ratio: let's call it r. In the first decreasing case, your value of r is between zero and one (it looks like around 0.6), while in the second case your value of r is greater than one (around 1.6). So your time intervals, in Python notation, are
a, a*r, a*r**2, a*r**3, ...

Then the time of each signal is the sum of a geometric series,
a * (1 - r**n) / (1 - r)

where n is the number of the pulse (1 for the first, 2 for the second, etc.). That formula is valid if r is not one, but if r is one then the sequence is a trivial sequence of a regular signal and the nth signal is given at time
a * n

This is not a "fixed result" since you have two degrees of freedom--you can choose values of a and of r.
If you want to spread the signals more evenly, just bring r closer to one. A value of one is perfectly even, a value farther from one is more clumped at one end. One disadvantage of this method is that if the signal intervals are decreasing then the signals will completely stop at some point, namely at
a / (1 - r)

If you have signals already sent or received and you want to find the value of r, just find the time interval between three consecutive signals, and r is the value of the time interval between the 2nd and 3rd signal divided by the time interview between the 1st and 2nd signal. If you want to see if this model is a good one for a given set of signals, check the value of r at multiple signals--if the value of r is nearly constant then this is a good model.


text:
Q: MotionEvent.ACTION_DOWN in Android is too sensitive. This event is received even if the screen is simply touched for a moment I have a layout(A table layout). Whenever the user performs a "down" gesture, a specific function needs to be called. However,the ontouchlistener captures the event immediately instead of waiting until the user performs a proper "pull down" gesture.
My code is :
homePageTableLayout.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                if ((event.getAction() == MotionEvent.ACTION_DOWN)) {
                    startSyncData();
                }
                return true;
            }
        });

Currently, what's happening is that the startSyncData() function gets called immediately.
The end result should be somewhat similar to the commonly used "pulltorefresh" library for android but in this usecase, I don't have to update the view. I just have to post some data to the server.
I can't use the "pulltorefresh" library because it does not support "pulling" a tablelayout. I tried putting the tablelayout inside a scrollview but that only spoiled the UI.

A: Its not that easy. It works properly since you are catching MotionEvent.ACTION_DOWN. It doesn't mean a gesture like swipe down it means that user touched the screen (finger down, the touch or gesture just started). Now you need to catch MotionEvent.ACTION_UP (finger up, gesture or touch ends here) and decide if there was a gesture you need. http://developer.android.com/training/gestures/detector.html
http://developer.android.com/training/gestures/index.html

A: You can try doing it in ACTION_MOVE or ACTION_UP - if you need it to be done exclusively on swipe down gesture, this should help, introduce four global floats: x, y, x1, y1, then in ACTION_DOWN:
x = event.getX();
y = event.getY();

ACTION_MOVE or ACTION_UP:
x1 = event.getX();
y1 = event.getY();

and then in ACTION_UP:
if (y1 > y) {        //pointer moved down (y = 0 is at the top of the screen)
    startSyncData();
}

A: MotionEvent.ACTION_MOVE repeatedly gets called. So if you want startSyncData() to run after moving a certain distance, calculate how much you want the user to move before running the method.
The key is that ACTION_DOWN is not a downwards movement on the screen, but it means the user pressed down onto the screen.
homePageTableLayout.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View view, MotionEvent event) {
            if ((event.getAction() == MotionEvent.ACTION_DOWN)) {
                startFlg = 1;
            } else if ((event.getAction() == MotionEvent.ACTION_MOVE)) {
                if (startFlg==1){
                    // Calculate distance moved by using event.getRawX() and event.getRawX() and THEN run your method
                    startSyncData();
                }
            }
            return true;
        }
    });


text:
Q: How to send a message from service worker to a Workbox class instance's "message" event? I have this in my window.js...
const wb = new Workbox('sw.js');

wb.messageSW({type:'START'});

wb.addEventListener('message', e=>{
   console.log(e);
});

...in my sw.js, I have...
self.addEventListener('message', (e)=>{
   if (e.data) {
       switch(e.data.type) {
           case 'START':
               //do some processing here...
               //...then how do I send a message to the client here so...
               //...that it will be received by the wb.addEventListener('message',... in window.js?
           break;
       }
   }
});

I tried sending via the MessagePort.postMessage() in e.ports[0] but it did not work. I feel this is something basic especially with the use of the Workbox class but I just can't get it to work.
My last resort is to use BroadcastChannel (with the polyfill) but I'm trying this one first as it may not need any polyfill for it to work.

A: You should be able to use the following to send a message from the service worker to all WindowClients (i.e. one or more instances of your web app, open in potentially multiple tabs):
const clients = await self.clients.matchAll({type: 'window'});
for (const client of clients) {
  client.postMessage({...});
}

That call to client.postMessage({...}) should trigger the handler in your web app that was registered via wb.addEventListener('message', ...).


text:
Q: Adding panels in jquery mobile page makes page scrolling on device stuck I am new to Jquery Mobile and Phonegap. I have created an app with multiple pages within one HTML page as mentioned by the Jquery Mobile site for developing apps in mobile.
I have also added panels for each pages. My problem is, after adding the panel, the scrolling up/down of the whole page becomes stuck. As in, you have to drag twice to scroll the page. This occurs when you run the app on iPhone/iPad and no problem on browser. This issue does not exist when the panel is removed from the page.
I have included the panel as a sibling of Header, Content and Footer, and also the panel is working fine.
What could be the reason? This is the panel html

Wallet
Settings
About Us
Logout

When i remove the above block from the page block, scrolling becomes fine.
Following are the styles applied..

Please help...

A: A panel must be a sibling to the header, content and footer elements inside a jQuery Mobile page. You can add the panel markup either before or after these elements, but not in between. A panel cannot be placed outside a page, but this constraint will be removed in a future version.
Here is an example of the panel before the header, content and footer in the source order:

Follow these instructions EXACTLY and all will be fine: http://jquerymobile.com/demos/1.3.0-beta.1/docs/panels/#
I used panel recently had no trouble whatsoever: http://radio.idev.ge
The problem was solved by adding 'data-position-fixed="true"' to the panels.


text:
Q: Using Exim and Google Apps email as smarthost I have a server setup to use exim4 and google apps as my smarthost. But I get errors when the to address is not the one I use to authenticate to google and it seems to drop all return addresses that are not the one it uses to authenitcate.
Example:
On the contact form of my server a user sets user@company1.com as their return address and uses the form to send a message.
I get an email sent to the admin's address admin@myCompany.com but the return address is also now admin@myCompany.com I have no idea of the return address the user set on the form.
I get around this by putting a bad email address in the form's default so Exim4 sends an error message to admin@myCompany.com with the user's email in the debug info.
Clearly I either have it set up wrong or do not understand how smarthosts work (probably both).

A: If you use Google as a smarthost, they will set the From: address to the address you used to authenticate to Google. They do this on purpose, presumably to prevent spam. If you need a smarthost to forward your mail without altering your headers, I recommend Mailhop Outbound - I used them before and never had any issues...

A: As the poster mentions above, Google definitely will be restricting the envelope sender and the header From, or else it would lead to widespread abuse.
This problem can solved at a couple of other places, one is your form script, where you can add the form sender in the data itself or else if you want to solve this in exim, I would suggest you write a system filter using the exim filter language which would strip out the From and envelope sender and put in the correct email address for the From and add the form email in a header like X-Form-Submitter-Email.


text:
Q: What is the connection between the science of testing, and Dune's idea of unlimited testing scales? Dune presents the idea that testing scales should never have a maximum level - it should always be possible to get a higher score or go to a more difficult level.  There's one memorable scene where someone is training on the sword-fighting robot and keeps winning and raising the level, until it's extremely dangerous.
Did Herbert base this idea on a philosophical concept from the real world?

A: Computerized adaptive testing works like that, but the idea is probably older than computerized testing, as I've heard it many times in regard to oral exams in university as well as job interviews: keep asking harder questions and determine the skill of the examinee by considering at what point he/she starts having problems.
There is an old and well-known physical exercise equivalent as well: high jump competitions work exactly like that: there is no fixed limit for how high you can jump - you just keep raising the bar until nobody can clear it.
In any case, "unlimited" is a bit of an exaggeration, as there are always limits. A swordfighting robot will certainly be limited by its basic construction in how dangerous it can be. The difficulty level of exam questions is limited by how smart the person who invents them and judges answers is. In highjumping, even if you ignore limits imposed by human anatomy, if you leave the ground fast enough, you'd jump straight out of Earth's gravity field, in which case the question of how high you jumped becomes meaningless.


text:
Q: Equivalent meaning of double arrow in logic I have come across this question, where I need to find a logically equivalent formula in which  formula in which ∧, ⇒and ⇐⇒ do not occur.
Here is the formula:
¬((p ∧ q) ⇐⇒ r)
I have figured out the first part, however I can't figure out how to find another way to express the ⇐⇒ r.
Any help would be appreciated.
Thank you

A: $\lnot((p \land q) \iff r)$
We can express $a \iff b \equiv (a \implies b) \land (b \implies a)$
So our above equation become $\lnot(((p\land q)\implies r) \land (r \implies (p \land q)))$
We can express $a \implies b \equiv \lnot a \lor b$
So,
$= \lnot(((p\land q)\implies r) \land (r \implies (p \land q)))$
$= \lnot((\lnot(p \land q) \lor r) \land (\lnot r \lor (p \land q)))$
$= \lnot((\lnot p \lor \lnot q \lor r) \land (\lnot r \lor p) \land (\lnot r \lor q))$
Using De Morgan's law,
$= \lnot(\lnot p \lor \lnot q \lor r) \lor \lnot(\lnot r \lor p) \lor \lnot(\lnot r \lor q)$


text:
Q: Correct method of authorizing scopes against Web Api and Mvc .NET 4 Applications I'm using identity server 4 as an authentication server, and have successfully demonstrated authenticating clients for access to my MVC web application and my Web API application, both running on IIS under .NET 4.7.
The problem I'm having is finding the correct approach for ensuring clients are only able to access the endpoints they should after the authentication process. EG, I have two clients, one with a write scope, and one without. How do I ensure the one without is only able to access endpoints that will read my data and not amend it?
The best method I've found so far is to use an authorization attribute like this:
https://github.com/IdentityModel/Thinktecture.IdentityModel/blob/master/source/WebApi/ScopeAuthorizeAttribute.cs
However, this is marked as obsolete and I'm unaware of the version based on OWIN middleware is mentions. Considering my MVC and Web Api applications are unable to be updated to .NET core applications, what would be the best approach?

A: Since the scope claims are available within the ASP.Net pipeline you can implement your own access control filter quite easily. It may be that that particular library is obsolete but the practice of enforcing scope in an MVC/WebAPI filter is certainly entirely valid.


text:
Q: Restrict user from downloading particular apps from play store I want to develop one app which tracks what are the applications user downloads from play store.Some particular apps like facebook,whatsApp should not be downloaded to user mobile.Is it possible to create this kind of tracking application in android?

A: Yes, you can track what gets downloaded, but you can't prevent it.
You could listen for ACTION_PACKAGE_ADDED from PackageManager and either warn the user or have your app "phone home" to tell you about it.


text:
Q: ModuleNotFoundError: No module named 'geo' I am using the following libraries:
import pandas as pd
import numpy as np
import googlemaps
from geopy.geocoders import Nominatim
import sys
from dateutil import parser
from geo import *
import re

I already installed in the prompt:
pip install GoogleMaps
pip install geopy
pip install geopandas
conda install -c conda-forge geopandas

However, I am still having the following error:
> ModuleNotFoundError                       Traceback (most recent call
> last) <ipython-input-1-456abdb5bc33> in <module>
>       5 import sys
>       6 from dateutil import parser
> ----> 7 from geo import *
>       8 import re

ModuleNotFoundError: No module named 'geo'

I really appreciate any help to solve this error

A: Have you tried
pip install geo-py

?
https://pypi.org/project/geo-py/


text: Q: How to install pip non-interactively with apt? I am installing pip using the command apt install python3-pip. During the installation, Do you want to continue? [Y/n] question appears on the command line. I want the command to take yes as the default answer and continue. Is this possible? Or any other way of installing pip non-interactively? I tried apt install --no-input python3-pip did not work.


text:
Q: Mail notification shows new email, quickly disappears and email is missing Any email I get pops up a notification in the upper-right corner of my screen, as per the native notification settings in the Apple Mail app. Every now and then I will get a quick notification indicating a new email, but then the email notification (and email) will quickly disappear. It's almost as if it was "recalled" by the email server and removed from my machine.
I haven't been able to find any consistency in the type of email that is received - I usually only get a glimpse of who sent it (always a company, never a personal one, at least not that I've noticed) and it's not like the ones that disappear are always from the same place or anything.
The emails in question are from one of my gmail accounts. I have no filters or manually-added spam blockers or blacklisted emails set up in that account, and I've got the email set up with IMAP into Apple's Mail client.
Anyone seen anything like this before? Any ideas of how to stop having these emails disappear?


text:
Q: open a file saved in internal storage using implicit intent app chooser What I am trying to achieve:
show app chooser to allow user to choose the app they want to use for viewing.
Click on recyclerview item to show app chooser.
given the app user pick, start the app and show the file.
user click on this recyclerview item

App will show app chooser to the user. Given selected app, user will be redirected to the selected app to view the  file.

Issues:
when I select an app, a toast from the app appears notifying something went wrong

additional details:
the file is stored in internal storage, within the app's files directory

What I've tried so far:
I've followed the reference provided by google regarding sharing files in internal storage with other app. ref
my code:

*

*code to execute the intent.

    override fun openFile(attachment: Attachment) {
            val filePath = File(requireContext().filesDir, "attachments/${attachment.type}")
            val newFile = File(filePath, attachment.name)
            val contentUri= try {
                FileProvider.getUriForFile(requireContext(), "applicationId.fileprovider", newFile)
            }catch (e:Exception){
                Log.e("DetailsFragment", "openFile FileProvider: ${e.message}")
                null
            }

            contentUri?.let {
                val extension = fileManager.getExtension(it)
                val mime = fileManager.getMime(extension!!)
                val title = "View in"
                val intent = Intent(Intent.ACTION_SEND)
                intent.setDataAndType(it, mime)
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                intent.clipData = ClipData.newRawUri("", it)
                val selector = Intent.createChooser(intent, title)

                Log.i(
                    "DetailsFragment",
                    "openFile - uri: ${it}, extension: ${extension}, data: ${intent.data}, mime: ${intent.type}"
                )
                try {
                    requireActivity().setResult(Activity.RESULT_OK, selector)
                    requireActivity().startActivity(selector)
                } catch (e: Exception) {
                    Log.e("DetailsFragment", "openFile - errorMsg: ${e.message}")
                }
            }

*

*Logcat from openFile(). (No exception in logcat)

    openFile - uri: content://applicationId.fileprovider/files/attachments/jpg/IMG_20221124_143655.jpg, extension: jpg, data: content://applicationId.fileprovider/files/attachments/jpg/IMG_20221124_143655.jpg, mime: image/jpeg

*

*manifest

    <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">

            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />

    </provider>

*

*xml/file_paths

    <paths>
        <files-path
            name="files"
            path="." />
    </paths>


text:
Q: Adding heading to ModernCV template I need a bold heading above the "Dear Sir or Madam," in the Cover Letter made with the moderncv template, like this:

Obviously there must be a new line above and under the newly created heading, but I could not edit the picture that way easily.
I am new to LaTeX and I do not even know where I can find the part which controlls the letter heading.
Thats the project's github page: ModernCV I use the classic design.

A: With version 2.0.0 of moderncv the title of the letter is defined in macro \makeletterhead.
To get the result you want you need to patch this macro with the following code:
\patchcmd{\makeletterhead}{%search
          \raggedright%
  \@opening\\[1.5em]%
        }{%replace
          \raggedright%
  \textbf{\@title}\\[1.5em]
  \@opening\\[1.5em]%
        }{%success
  }{%failure
  }

It adds \title you have to define before as bold heading before the opening text.
With the complete MWE
\documentclass[11pt,a4paper,sans]{moderncv}

% moderncv themes
\moderncvstyle{classic} % casual, classic, banking, oldstyle and fancy
\moderncvcolor{blue}

\usepackage[utf8]{inputenc}

\usepackage[scale=0.75]{geometry}

% personal data
\name{John}{Doe}
\title{Resumé title}
\address{street and number}{postcode city}{country}
\phone[mobile]{+1~(234)~567~890}
\phone[fixed]{+2~(345)~678~901}
\phone[fax]{+3~(456)~789~012}
\email{john@doe.org}
\homepage{www.johndoe.com}
\social[linkedin]{john.doe}
\social[twitter]{jdoe}
\social[github]{jdoe}
\extrainfo{additional information}
\photo[64pt][0.4pt]{example-image-a}
\quote{Some quote}

\setlength{\footskip}{66pt}

\makeatletter % needed for @ <==========================================
\patchcmd{\makeletterhead}{%search
          \raggedright%
  \@opening\\[1.5em]%
        }{%replace
          \raggedright%
  \textbf{\@title}\\[1.5em]
  \@opening\\[1.5em]%
        }{%success
  }{%failure
  }
\makeatother % needed for @ <===========================================

\begin{document}

%-----       letter       ---------------------------------------------------------
% recipient data
\recipient{Company Recruitment team}{Company, Inc.\\123 somestreet\\some city}
\title{Heading should look like this} % <===============================
\date{January 01, 1984}
\opening{Dear Sir or Madam,}
\closing{Yours faithfully,}
\enclosure[Attached]{curriculum vit\ae{}}
\makelettertitle

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis ullamcorper
neque sit amet lectus facilisis sed luctus nisl iaculis. Vivamus at neque
arcu, sed tempor quam. Curabitur pharetra tincidunt tincidunt. Morbi
volutpat feugiat mauris, quis tempor neque vehicula volutpat. Duis
tristique justo vel massa fermentum accumsan. Mauris ante elit, feugiat
vestibulum tempor eget, eleifend ac ipsum. Donec scelerisque lobortis
ipsum eu vestibulum. Pellentesque vel massa at felis accumsan rhoncus.

Suspendisse commodo, massa eu congue tincidunt, elit mauris pellentesque
orci, cursus tempor odio nisl euismod augue. Aliquam adipiscing nibh ut
odio sodales et pulvinar tortor laoreet. Mauris a accumsan ligula.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
inceptos himenaeos. Suspendisse vulputate sem vehicula ipsum varius nec
tempus dui dapibus. Phasellus et est urna, ut auctor erat. Sed tincidunt
odio id odio aliquam mattis. Donec sapien nulla, feugiat eget adipiscing
sit amet, lacinia ut dolor. Phasellus tincidunt, leo a fringilla
consectetur, felis diam aliquam urna, vitae aliquet lectus orci nec
velit. Vivamus dapibus varius blandit.

Duis sit amet magna ante, at sodales diam. Aenean consectetur porta risus
et sagittis. Ut interdum, enim varius pellentesque tincidunt, magna
libero sodales tortor, ut fermentum nunc metus a ante. Vivamus odio leo,
tincidunt eu luctus ut, sollicitudin sit amet metus. Nunc sed orci
lectus. Ut sodales magna sed velit volutpat sit amet pulvinar diam
venenatis.

Albert Einstein discovered that $e=mc^2$ in 1905.

\[ e=\lim_{n \to \infty} \left(1+\frac{1}{n}\right)^n \]

\makeletterclosing

\end{document}

you get then the following resulting letter:


text:
Q: Написать функцию из условия Сегодня на собеседовании был пример:

sum(a)(b)(c)=a + b + c;

Нужно написать функцию sum так что бы строка sum(a)(b)(c)=a + b + c; выполнялась, и сделать это нужно с помощью замыкания.
Как это сделать, и что значит sum(a)(b)(c) (несколько кавычек подряд у функции)?

A: Похоже, что хотели тоже, что и от героя этой статьи:
http://habrahabr.ru/post/226325/
Т.е. в идеале решение должно быть таким:
var sum = function (orig) {
      var inner = function (val) {
        return sum(parseInt(val + '', 10) === val ? orig + val : orig);
      };

      inner.valueOf = function () { return orig; };

      return inner;
    };

Плюсы этого решения очевидны: оно применимо к любому числу слагаемых, не только 3. Пример с тремя слагаемыми даётся, чтобы понять как человек подходит к решению проблемы: локально или глобально.

A:

function sum(a){
  return function(b){
    return function(c){
      return b+a+c;
    }
  }
}
alert(sum(1)(2)(3));

A: function sum(x) { return function(z) { return function(y) {return x+z+y;} } }
Но что то мне подсказывает, что они хотели более элегантное решение, которое мне в голову пока не приходит.

A: function sum(a)
{
    return function(b) {
        return function(c) {
            return a + b + c;
        }
    }
}

Видимо имелось в виду вот это.
функция которая возвращает функцию, которая возвращает функцию, и ты вызываешь функцию у функции которая вернула функцию =)


text:
Q: Jquery variable output My problem is driving me nuts.
I have declared som variables like this
var tip01 = "This is my first tip";
var tip02 = "This is my second tip";

Depending on the value in my querystring I want to write out my tips.
my querystring: ex ?myQSvalue=01
var myQSvalue = getQueryString('myQSvalue');
var myTip = 'tip' + myQSvalue;

 $("#output").html(myTip);

But the output is: tip01 insted of This is my first tip.
How can I achieve this and output the content in my declared varable?
Thank you.

A: rather than different variabes, you should be using an array
var myTips = [];
myTips[0] = "This is my first tip";
myTips[1] = "This is my second tip";

Then pass an index on the querystring ?myQSvalue=0
And read from the array:
var myQSvalue = parseInt(getQueryString('myQSvalue'),10);
$("#output").html(myTips[myQSvalue]);

A: I'd suggest defining the tips in an array instead, but you should be able to use:
$("#output").html(window[myTip]);

A: The correct approach has already been pointed out by Jamiec, but just for future reference, you can refer to global variables as properties of the global context:
var myQSvalue = getQueryString('myQSvalue');
var myTip = 'tip' + myQSvalue;

 $("#output").html(window[myTip]);

A: Thanks for all your help. I went with the array approach and it works great.
But the $("#output").html(window[myTip]); didn´t work for me.
In some cases that approach would be handy.


text:
Q: bc calculation with large float number I have a large number and I want to make bc calculation.
Example:
T_Mab = 6.00899e+09

and I wanna print it like this:
echo 'T_Mab =   '${T_Mab}' [s] = '${T_Mab}/31557600' [year]' | bc -l

It is giving me "syntax error". So how can I do it?

A: You cannot just write whatever you want to display and dump them to bc. Another issue is that bc does not accept scientific notations. Check [How to get bc to handle numbers in scientific (aka exponential) notation? for details.
Assuming that the number is already converted to the correct form as in the answers in the linked question, you can write it like this in bash.
T_Mab=6008990000
echo "${T_Mab} [s] = $(bc -l <<< ${T_Mab}/31557600) [year]"

Here-strings are added since bash 3.0, if you are using older version, just use $(echo ${T_Mab}/31557600|bc -l).
With all these said, you really should consider bc alternatives as suggested in the second answer of the linked question if you don't need arbitrary precision.

A: The syntax error is because bc doesn't read "e" notation, and can be reproduced with a greatly simplified example:
$ bc -l <<<"6.00899e+09"

(standard_in) 1: syntax error

We'll need to change to a syntax it does understand; we can do that in Bash:
v=6.00899e+09
v=${v/e/*10^}    # 6.00899*10^+09
v=${v/^+/^}      # 6.00899*10^09
bc -l <<<"($v)"

6008990000.00000

Or simply launder through a tool that does understand the notation:
printf '%f\n' "$v" | bc -l


text:
Q: Passing variables inside steps to html file in yaml Is it possible to assign a variable and pass it to an html that executes within the same step?
jobs:
Run_Test:
    steps:
      - name: Step one
        (...)
      - name: Step two
        if: always()
        uses:  dawidd6/action-send-mail@v3.6.0
        with:
          server_address: (...)
          server_port: (...)
          username: (...)
          password: (...)
          subject: ${{ github.job }} execution finished ${{ job.status }}
          body: |
            Executed by: ${{ github.actor}}
            Job name: ${{ github.job }}
            Repository: ${{ github.repository }}
            Status: ${{ job.status }}
          html_body: file:///some/route/to/file/main.html
          to: (...)

I need to display the variables inside the body in the html file in html_body

Executed by: ${{ github.actor}}

Job name: ${{ github.job }}

Repository: ${{ github.repository }}

Status:${{ job.status }}

Is this possible or is there any way to do it?

A: The file:// functionality is specific to action-send-mail and doesn't support variable substitution in the file, but you can of course just give the content directly:
body: |
  Executed by: ${{ github.actor}}
  Job name: ${{ github.job }}
  Repository: ${{ github.repository }}
  Status: ${{ job.status }}
html_body: |

Executed by: ${{ github.actor}}

Job name: ${{ github.job }}

Repository: ${{ github.repository }}

Status:${{ job.status }}


text:
Q: chop or rtrim not removing last character I want to chop off the last comma but its not working.
earlier today exact these lines were working in a different code block.
if($added_attr > $original_attribute)
    {

        for($i = $original_attribute;$i<$added_attr;$i++)
        {
             echo $attribute_data .= "('$id','$attr_changed[$original_attribute]','$attr_val[$original_attribute]'),";
        }

        $attribute_data = chop($attribute_data , ",");
        $sql_new_insert = "INSERT INTO product_attribute_value(iProductId,iAttributeId,vValue)".
                        "VALUES ".$attribute_data;
    }

Well, this is surprise as this is working now with out a edit to any character. Even in morning it same thing happened, rtrim,chop,substr did not worked for 30 min. though my problem is solved now, any solution this problem will be helpful. Thank you.

A: $attribute_data = array();
for($i = $original_attribute;$i<$added_attr;$i++)
{
   $attribute_data[] = "('$id','$attr_changed[$original_attribute]','$attr_val[$original_attribute]')";
}
echo implode(',',$attribute_data);

http://php.net/manual/en/function.implode.php
You can try this way


text:
Q: Flashcards with Latex I have the following problem:
I would like to have a flashcard software in which I can write Latex formulas without to have installed Latex itself (Miktex etc) on my device. I suppose this is possible since XMind has also Latex integrated without having to install anything. As far as I could see Anki needs Latex to be installes? Any other options.
Further it would be cool to have this also on my mobile device.
Any suggestions?
Based on this https://en.wikipedia.org/wiki/List_of_flashcard_software
I see only Mnemosyne to be a solution but do I have to install Latex in this case?


text:
Q: IE JavaScript Mystery I have the following JavaScript function
function headerBanner(){
    var current = $('.bannerImages img:nth-child('+bannerIndex+')').css('display', 'none');
    if(bannerIndex== $('.bannerImages img').size()){
        bannerIndex= 1;
    }else{
        bannerIndex= (bannerIndex*1)+1;
    }
    var next =  $('.bannerImages img:nth-child('+bannerIndex+')').css('display', 'block');
}

In every browser on the planet, with the exception of IE (8, 7 or less), the above code is working correctly. In Internet Explorer it's going through it and having no effect. I've put alerts at every line of the function and they all fire, even in IE, but the banner simply doesn't change. Is there any reason as to why this is so?
The HTML attached for this function is the following:

A: Try using the script debugger in the IE8 developer tools and put some breakpoints in to check the value of bannerIndex.  If it's possible that it's not a number you may want to use parseInt() to convert it to a number and IsNaN() to ensure that it is, rather than relying on arithmetic operations to normalize it for you.

A: One thing I found with hide() and show() was that, sometimes, if you set the display to none, show() will not work. So, I always create the element then call a hide(0) on it first thing when document is ready.
Also, did you check the length of $('.bannerImages img:nth-child('+bannerIndex+')') to make sure it's not 0?
Last thing, $('.bannerImages img').size() isn't 1, right? It would make sense if $('.bannerImages img').size() is 1 and bannerIndex is 1, then it will not change anything when it go through your headerBanner();
ps: I'm sure you won't make some simple mistake such as bannerIndex was started from 0 instead of 1...
Oh, btw, there is a firebug for IE, which u need to include a script in your header

A: try this:
DEMO: http://jsbin.com/ipudo/4
$(function(){
    $('.bannerImages img:gt(0)').hide();
    setInterval(function(){
      $('.bannerImages :first-child').fadeOut()
         .next('img').fadeIn()
         .end().appendTo('.bannerImages');},
      3000);
});


text:
Q: Unexpected behavior AutoMapper mapping nested collection I'm trying to map types with nested collection using Mapper.Map(from, to); and I have encountered a number of issues.
Initially I had the issue where a property on my destination field which doesn't exist on my source type
 int Id {get; set; }

was always set to 0 regardless of what ForMember map I used (Ignore() or UseDestinationValue()). I discovered that I had to create a mapping for my collection types:
Mapper.CreateMap(List<source>, List<destination>)

This resulted in the id field not being set to 0, but now all values in my source collection are no longer copied to my destination collection. Below is an example of what I mean:
public class TestModel
{
    public virtual List<NestedTestModel> Models { get; set; }
}

public class NestedTestModel
{
    public int Value { get; set; }
}

public class TestEntity
{
    public int Id { get; set; }
    public virtual List<NestedTestEntity> Models { get; set; }
}

public class NestedTestEntity
{
    public int Id { get; set; }
    public int Value { get; set; }
}

[Test]
public void TestMappingFromCalibrationModelToCalibrationModelEntity()
{
    Mapper.CreateMap<TestModel, TestEntity>()
        .ForMember(x => x.Id, x => x.UseDestinationValue());
    Mapper.CreateMap<NestedTestModel, NestedTestEntity>()
        .ForMember(x => x.Id, x => x.UseDestinationValue())
        .ForMember(x => x.Value, y => y.MapFrom(z => z.Value));
    Mapper.CreateMap<List<NestedTestModel>, List<NestedTestEntity>>();

    TestModel from = new TestModel();
    from.Models = new List<NestedTestModel>
    {
        new NestedTestModel { Value = 3 }
    };

    TestEntity to = new TestEntity
    {
        Models = new List<NestedTestEntity>
        {
            new NestedTestEntity { Id = 1, Value = 2 }
        }
    };

    var actual = Mapper.Map<TestModel, TestEntity>(from, to);

    // this only works if Mapper.CreateMap<List<NestedTestModel>, List<NestedTestEntity>>();
    Assert.AreEqual(1, actual.Models[0].Id);

    // Results in
    // Expected: 3
    // But was:  2
    Assert.AreEqual(3, actual.Models[0].Value);

}

A: AutoMapper supports collections so
Mapper.CreateMap(List<source>, List<destination>);

Is not required.
All you need is just:
Mapper.CreateMap<sourceNested, destinationNested>();
Mapper.CreateMap<source, destination>();

Then map like this:
var res = Mapper.Map<IEnumerable<source>, IEnumerable<destination>>(source);

When mapping TestModel to TestEntity TestEntity.Id will always be 0 as it's type is int and default value for int is 0.


text:
Q: my checkbox doest not match the count of data I made checkbox the data from database and still work, when I click multiple checkbox, the count of data clicked is matches
result console.log

the problem when I sending data to filter.php with method post
the count of data received is not matches

event click jquery
$(document).ready(function() {
                $('#t_pendaftar').DataTable();
                    $('#filter').click(function () {
                     var data = { 'venue[]' : []};
                     var arr = $('.treas:checked').map(function () {
                        data['venue[]'].push($(this).val());
                     }).get();
                     console.log(data);
                     $.post("filter.php",{data : data});
                 });
                });

filter.php
<?php var_dump($_POST['data']);   if(!empty($_POST['data'])) {
    foreach($_POST['data'] as $check) {
            print_r($check);
     } }   ?>

thank you for attention

A: You can convert json string from javascript object by using JSON.stringify.
PHP can refer post data from by decoding json string.
You can get expected results as below code that applied these things.
jQuery:
$(document).ready(function() {
    $('#t_pendaftar').DataTable();
    $('#filter').click(function () {
        var data = { 'venue' : []};
        var arr = $('.treas:checked').map(function () {
            data['venue'].push($(this).val());
        }).get();
        data = JSON.stringify(data);
        $.post("filter.php", {data : data});
    });
});

filter.php:
if (!empty($_POST['data'])) {
    $data = json_decode($_POST['data'], true);
    foreach($data['venue'] as $check) {
        print_r($check);
    }
}


text:
Q: How to implement SOLID principles into an existing project I apologize for the subjectiveness of this question, but I am a little stuck and I would appreciate some guidance and advice from anyone who's had to deal with this issue before:
I have (what's become) a very large RESTful API project written in C# 2.0 and some of my classes have become monstrous.  My main API class is an example of this -- with several dozen members and methods (probably approaching hundreds).  As you can imagine, it's becoming a small nightmare, not only to maintain this code but even just navigating the code has become a chore.
I am reasonably new to the SOLID principles, and I am  massive fan of design patterns (but I am still at that stage where I can implement them, but not quite enough to know when to use them - in situations where its not so obvious).
I need to break my classes down in size, but I am at a loss of how best to go about doing it.  Can my fellow StackOverflow'ers please suggest ways that they have taken existing code monoliths and cut them down to size?

A: There's a classic book by Martin Fowler - Refactoring: Improving the Design of Existing Code.
There he provides a set of design techniques and example of decisions to make your existing codebase more manageable and maintainable (and that what SOLID principals are all about). Even though there are some standard routines in refactoring it is a very custom process and one solution couldn't be applied to all project.
Unit testing is one of the corner pillars for this process to succeed. You do need to cover your existing codebase with enough code coverage so that you'd be sure you don't break stuff while changing it. Actually using modern unit testing framework with mocking support will lead encourage you to better design.
There are tools like ReSharper (my favorite) and CodeRush to assist with tedious code changes. But those are usually trivial mechanical stuff, making design decisions is much more complex process and there's no so much tool support. Using class diagrams and UML helps. That what I would start from, actually. Try to make sense of what is already there and bring some structure to it. Then from there you can make decisions about decomposition and relations between different components and change your code accordingly.
Hope this helps and happy refactoring!

A: It will be a time consuming process.  You need to read the code and identify parts that do not meet the SOLID principles and refactor into new classes.  Using a VS add-in like Resharper (http://www.jetbrains.com) will assist with the refactoring process.
Ideally you will have good coverage of automated unit tests so that you can ensure your changes do not introduce problems with the code.
More Information
In the main API class, you need to identify methods that relate to each other and create a class that more specifically represents what actions the method performs.
e.g.
Let's say I had an Address class with separate variables containing street number, name, etc.  This class is responsible for inserting, updating, deleting, etc.  If I also needed to format an address a specific way for a postal address, I could have a method called GetFormattedPostalAddress() that returned the formatted address.
Alternatively, I could refactor this method into a class called AddressFormatter that takes an Address in it constructor and has a Get property called PostalAddress that returns the formatted address.
The idea is to separate different responsibilities into separate classes.

A: Single Responsibility Principle - A class should have only one reason to change. If you have a monolithic class, then it probably has more than one reason to change. Simply define your one reason to change, and be as granular as reasonable. I would suggest to start "large". Refactor one third of the code out into another class. Once you have that, then start over with your new class. Going straight from one class to 20 is too daunting.
Open/Closed Principle - A class should be open for extension, but closed for change. Where reasonable, mark your members and methods as virtual or abstract. Each item should be relatively small in nature, and give you some base functionality or definition of behavior. However, if you need to change the functionality later, you will be able to add code, rather than change code to introduce new/different functionality.
Liskov Substitution Principle - A class should be substitutable for its base class. The key here, in my opinion, is do to inheritance correctly. If you have a huge case statement, or two pages of if statements that check the derived type of the object, then your violating this principle and need to rethink your approach.
Interface Segregation Principle - In my mind, this principle closely resembles the Single Responsibility principle. It just applies specifically to a high level (or mature) class/interface. One way to use this principle in a large class is to make your class implement an empty interface. Next, change all of the types that use your class to be the type of the interface. This will break your code. However, it will point out exactly how you are consuming your class. If you have three instances that each use their own subset of methods and properties, then you now know that you need three different interfaces. Each interface represents a collective set of functionality, and one reason to change.
Dependency Inversion Principle - The parent / child allegory made me understand this. Think of a parent class. It defines behavior, but isn't concerned with the dirty details. It's dependable. A child class, however, is all about the details, and can't be depended upon because it changes often. You always want to depend upon the parent, responsible classes, and never the other way around. If you have a parent class depending upon a child class, you'll get unexpected behavior when you change something. In my mind, this is the same mindset of SOA. A service contract defines inputs, outputs, and behavior, with no details.
Of course, my opinions and understandings may be incomplete or wrong. I would suggest learning from people who have mastered these principles, like Uncle Bob. A good starting point for me was his book, Agile Principles, Patterns, and Practices in C#. Another good resource was Uncle Bob on Hanselminutes.
Of course, as Joel and Jeff pointed out, these are principles, not rules. They are to be tools to help guide you, not the law of the land.
EDIT:
I just found these SOLID screencasts which look really interesting. Each one is approximately 10-15 minutes long.

A: What I've done when presented with this type of thing (and I'll readily admit that I haven't used SOLID principles before, but from what little I know of them, they sound good) is to look at the existing codebase from a connectivity point of view.  Essentially, by looking at the system, you should be able to find some subset of functionality that is internally highly coupled (many frequent interactions) but externally loosely coupled (few infrequent interactions).  Usually, there are a few of these pieces in any large codebase; they are candidates for excision.  Essentially, once you've identified your candidates, you have to enumerate the points at which they are externally coupled to the system as a whole.  This should give you a good idea of the level of interdependency involved.  There usually is a fair bit of interdependency involved.  Evaluate the subsets and their connection points for refactoring; frequently (but not always) there ends up being a couple of clear structural refactorings that can increase the decoupling.  With an eye on those refactorings, use the existing couplings to define the minimal interface required to allow the subsystem to work with the rest of the system.  Look for commonalities in those interfaces (frequently, you find more than you'd expect!).  And finally, implement these changes that you've identified.
The process sounds terrible, but in practice, it's actually pretty straightforward.  Mind you, this is not a roadmap towards getting to a completely perfectly designed system (for that, you'd need to start from scratch), but it very certainly will decrease the complexity of the system as a whole and increase the code comprehensibility.

A: OOD - Object Oriented  Design
SOLID - class design
Single Responsibility Principle - SRP - introduced by Uncle Bob. Method, class, module  are responsible only for doing single thing(one single task)
Open/Closed Principle - OCP - introduced by Bertrand Meyer. Method, class, module are open for extension and closed for modification. Use a power of inheritance, abstraction, polymorphism, extension, wrapper. [Java example], [Swift example]
[Liskov Substitution Principle] - LSP - introduced by Barbara Liskov and Jeannette Wing. A subtype can replace supertype without side effects
Interface Segregation Principle - ISP - introduced by Uncle Bob. Your interface should be as small as possible
[Dependency Inversion Principle(DIP)] - DIP - introduced by Uncle Bob. Internal class, layer should not be depended on external class, layer. For example when you have aggregation[About] dependency you should rather use some abstraction/interfaces. [DIP vs DI vs IoC]
6 principles about packages/modules(.jar, .aar, .framework):
what to put inside a package

*

*The Release Reuse Equivalency

*The Common Closure

*The Common Reuse

couplings between packages

*

*The Acyclic Dependencies

*The Stable Dependencies

*The Stable Abstractions

[Protocol Oriented Programming(POP)]


text:
Q: Array is empty still renders correct data when rendered for first time but after refresh is empty The code is
router.get('/', function(req, res, next){
var successMsg = req.flash('success')[0];
Section.findOne({'sectionId': 'K111'}, function(err, doc){
    var result = [];
    studentsList = doc.studentsList;

    studentsList.forEach(function(ele){
        Student.findById(ele, function(errs, docs){
            result.push(docs);
        });
    });

    console.log(result);

    res.render('shop/index', {students: result, successMsg: successMsg, noMessages: !successMsg});
});

});
Here I am using mongoose for data retrieval from MongoDb.
The result array is empty even after pushing the docs after findById(). The data is correctly rendered for first time when nodejs server starts but after refresh there is not data rendered.

A: You must learn promises or you can use recursion:
router.get('/', function(req, res, next) {
    var successMsg = req.flash('success')[0];
    Section.findOne({'sectionId': 'K111'}, function(err, doc){
        var result = [];
        studentsList = doc.studentsList;

        function onDone () {
            console.log(result);

            res.render('shop/index', {
                students: result,
                successMsg: successMsg,
                noMessages: !successMsg
            });
        }

        function findNext(i) {
            if (i == studentsList.length)
                return onDone();

            var ele =  studentsList[i];
            Student.findById(ele, function(err, docs) {
                if (err)
                    return next(err); // Break and go to error handler

                result.push(docs);
                findNext(i + 1);
            });
        }

        findNext(0);
    });
}


text:
Q: mysql using tee in stored procedure I'm new to MySQL (or SQL in general)
I'm trying to get MySQL to write the timestamp into a file with stored procedure using TEE command (I don't think I can use "select into outfile" because I don't want to delete the file, I want to add a line to it...):
mysql> DELIMITER $$
mysql> CREATE PROCEDURE test_to_file()
    -> begin
    -> TEE /home/ubuntu/test.txt;
    -> SELECT NOW();
    -> end $$

However, I get an error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/home/ubuntu/test.txt;
SELECT NOW();
end' at line 3
Thanks for the help

A: Disclaimer: I am not certain that whatever you are trying to do is necessarily a good idea... but there is a simple solution for this.
Create a table using the CSV Storage Engine.
You can then append to the file by simply inserting into this table.

Using tee is a client-side feature.  It doesn't write to the server at all, unless you happen to be running the mysql client on the server machine... in which case, it's only writing to the server machine by coincidence.


text:
Q: Cakephp 3 Not Recognizing Custom Validation Rule Method and Validation Messages Not Showing First issue is I have the following validators and public function in my table
UsersTable.php
   $validator
        ->scalar('name')
        ->maxLength('name', 45)
        ->requirePresence('name', 'create')
        ->notEmptyString('name', 'You must enter a name for the user.');

   $validator
       ->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));

   public function checkExistingUser($value,$context)
{
    return $this->find('all', ['conditions' => ['Users.name' => $context['data']['name'], 'Users.user_type_id' => $context['data']['user_type_id']]])->count() < 1 ;

}

When I save the form below I receive the message "Method checkExistingUser does not exist". Why doesn't it recognize the method when it's clearly defined in the table model? Am I missing something?
add.ctp
<?php echo $this->Form->create($user);?>
    <fieldset>
            <legend><?php echo __('Add User'); ?></legend>
    <?php
            echo $this->Form->control('name', ['type' => 'text']);
        echo $this->Form->control('user_type_id');
    echo $this->Form->control('owner', array('type' => 'text', 'label' => "Owner Name"));
    echo $this->Form->control('owner_contact', array('type' => 'text', 'label' => "Owner Contact (phone, email etc)"));
    echo $this->Form->control('description', ['type' => 'textarea']);
            echo $this->Form->control('ia_exception', array('type' => 'text', 'label' => "IA Exception Number"));
            echo $this->Form->control('is_manual', array('type' => 'checkbox', 'label' => "Password Updated Manually"));
            echo $this->Form->control('Environment', ['type' => 'select', 'multiple' => 'true', 'label' => 'Environment(s)']);
    ?>
    </fieldset>
<div class="buttons">
<?php
echo $this->Form->button('Save', ['type'=> 'submit', 'name' => 'submit']);
echo $this->Form->button('Cancel', ['type' => 'button', 'name'=>'cancel', 'onClick' => 'history.go(-1);return true;']);
echo $this->Form->end();
?>
</div>

UsersController.php
    function add() {

            $user = $this->Users->newEntity();

            if ($this->request->is('post')) {
                    $user = $this->Users->patchEntity($user, $this->request->data);

                    if ($this->Users->save($user)) {
                            $this->Flash->set('The user has been saved');
                            return $this->redirect(array('action' => 'index'));
                    } else {
                            $this->Flash->set('The user could not be saved. Please, try again.');
                    }
            }
            $userTypes = $this->Users->UserTypes->find('list');
            $changeSteps = $this->Users->ChangeSteps->find('list');
            $environments = $this->Users->Environments->find('list');
            $this->set(compact('user','userTypes', 'changeSteps', 'environments'));
    }

Second issue is when I try to submit my form to check that the validator is working correctly for an empty name field I don't receive the message 'You must enter a name for the user'. Instead I receive a message stating 'This field is required'. Why is it not showing my message from notEmptyString? And where is 'This field is required' coming from?

A: For the first issue, I had to add a provider in my validator.
I changed
 $validator
   ->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));

To this
  $validator
       ->add('name', 'custom', ['rule' => 'checkExistingUser', 'provider' => 'table', 'message' => 'This user already appears to be in the system.', 'on' => 'create']);

A: Be careful with custom methods for validation during patching, because Cake expects string to be returned, otherwise it will rendere default meassage.
So for example, if we use a custom validation function during patching
 // in a Controller
 $this->Users->patchEntity($user, $data, ['validate' => 'custom');

Same applies for closures.
 // in UserTable.php
 public function validationCustom(Validator $validator) {
        $validator = $this->validationDefault($validator);
        $validator
        ->minLength('password',8,'At least 8 digits');
        $validator->add('password',
            'strength_light',[
                'rule' => 'passwordCheck',
                'provider' => 'table',
                'message' => 'At least a number and a capital letter'
            ]
            );
        return $validator;
    }
    public function passwordCheck ($value = "") {
        return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}/",$value);
}

This will return default message and not the custom one ("At least..") because we set a callable not-cakephp function as rule for custom validation, so the message should be returned by the called function:
 public function passwordCheck ($value = "") {
     if (!preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}/",$value))
         return "At least a number and a capital letter";

    }


text:
Q: Pauli Exclusion and Black Holes Pauli exclusion principle states that 2 identical electrons cannot be in the same state, where state includes a spacial component.
I have heard that, in order to avoid being in the same state, in a white dwarf, the De Broglie wave length of the electrons becomes shorter and shorter, meaning that they have a higher and higher momentum/ energy. Eventually, when the gravitational pressure is too high, they form neutron stars, since neutrons have smaller De Broglie Wave lengths due to their higher mass.
My question is, by applying more and more pressure, can we confine more and more identical neutrons/ other fermions in an arbitrarily small space, eventually forming a black hole? Or, at some point, fermions must be converted into bosons?

A:
My question is, by applying more and more pressure, can we confine more and more identical neutrons/ other fermions in an arbitrarily small space, eventually forming a black hole? Or, at some point, fermions must be converted into bosons?

Black holes are classical entities.Fermions and bosons are quantum  mechanical entities. Questions that mix the two frames will not have a definite answer until/when gravity is quantized.
In the standard model, fermions can couple up and become bosons, as for example pions are made up out of two fermions, a quark and an antiquark. So this could be a hypothesis in some specific quantization model.
At the moment cosmological models work with effective quantization of gravity, which replaces the point singularities into a fuzzy quantum mechanical region. In such a region it is not forbidden to keep the logic of higher and higher energy for the energy carriers, in your question fermions, because there is no limit to how many energy levels there can be in the fuzzy quantum mechanical region, as for example at the beginning of the Big Bang, and thus be able to fulfill the Pauli exclusion.


text:
Q: Passing an Enum to a method as a parameter in Java? I am trying to call a docx4j method "setAlgn" in the interface CTTextParagraphProperties, which, per the docx4j jar I am using and the compiler takes an Enum type as a parameter. I am passing the actual argument STTextAlignType.CTR which I believe should resolve to the value 'ctr' (citation: http://grepcode.com/file/repo1.maven.org/maven2/org.docx4j/docx4j/3.0.1/org/docx4j/dml/STTextAlignType.java?av=f, I am running this same code).
Here is my code:
import java.lang.Enum;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFChildAnchor;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSimpleShape;
import org.apache.poi.xssf.usermodel.XSSFShapeGroup;
import org.apache.poi.xssf.usermodel.XSSFTextBox;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.docx4j.dml.*;

        public static XSSFTextBox createTextBox(XSSFSheet sh, String message, int row1, int col1, int row2, int col2, boolean is_bold, boolean is_italics, boolean is_underline, boolean centered, int fontSize){

        //Various apache-poi stuff
        XSSFWorkbook wb = sh.getWorkbook();
        XSSFDrawing drawing = sh.createDrawingPatriarch();
        XSSFClientAnchor clientanchor = new XSSFClientAnchor(0,0,0,0,(short)col1,row1,(short)col2,row2);
        XSSFChildAnchor childanchor = new XSSFChildAnchor(0,0,0,0);
        XSSFShapeGroup group = drawing.createGroup(clientanchor);
        XSSFTextBox textbox = group.createTextbox(childanchor);
        XSSFRichTextString richMessage = new XSSFRichTextString(message);
        XSSFFont textFont = wb.createFont();
        textFont.setFontHeightInPoints((short)fontSize);
        textFont.setFontName("Verdana");
        if(is_bold){
            textFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        }
        textFont.setItalic(is_italics);
        if(is_underline){
            textFont.setUnderline(XSSFFont.U_SINGLE);
        }
        if(centered){
        //Here is the code in question.
        textbox.getCTShape().getTxBody().getPArray(0).getPPr().setAlgn(STTextAlignType.CTR);
        }
        richMessage.applyFont(textFont);
        textbox.setText(richMessage);
        return textbox;
    }

My compiler returns the following error message:
com\tem\POIStuff.java:1105: error: method setAlgn in interface CTTextParagraphProperties cannot be applied to given types;
                    textbox.getCTShape().getTxBody().getPArray(0).getPPr().setAlgn(STTextAlignType.CTR);

Ultimately, my question is how can I get the "setAlgn" method to accept 'STTextAlignType.CTR' as an Enum and not as object type 'STTextAlignType'? Thank you in advance very much for your help!

A: The problem is actually on the first line of your code snippet! Your issue is with
import java.lang.Enum;

CTTextParagraphProperties.setAlgn does take a class of type Enum, but it's not that kind of Enum. It has to be a org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType.Enum
I'd suggest you switch your imports to be:
import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType;
import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType.Enum;

You can then set the alignment with things like STTextAlignType.L and it'll work fine


text:
Q: php include_once reverse alphabaticly? I'm currently using this piece of code to load news feeds to my webpage by adding a new html file for every article how can i include files in reverse alphabetical order, So that 2013-02-07 goes before 2013-02-08?
<?php
   foreach (glob("news/*.html") as $filename)
{
    include_once $filename;
}  ?>

A: $files = glob('news/*.html');
rsort($files);
foreach ($files as $f) {
    include $f;
}

This actually does a reverse lexicographical sort (since the file names are strings), but that luckily works in this case since the dates are in highest to lowest magnitude order. More information: rsort.
Note: I'm assuming your dates are formatted like YYYY-MM-DD. If they're formatted without leading zeroes, this solution will not work. You will have to extract the date from each file name, change it to some kind of intermediary type (unix timestamp, or a lexicographically sortable string) and then sort on that. For example '2013-3-1' > '2013-12-1' is considered true, but '2013-03-01' > '2013-12-01' is false.


text:
Q: Assembly Language "CMP" I am working on my first project for my Machine Organization class. The program flips the screen from left to right. This works fine and I have no issues with this. However, in addition to flipping the screen, my professor has also asked us to display all uppercase C's in red on grey. I have attempted to do this within the loopRow LOOP. There are no errors when assembling, however, it does not work. I have also tried comparing to the ASCII code value but this did not work either. Any suggestions?
MyCode SEGMENT
        ASSUME CS:MyCode, DS:MyData

MainProg  PROC

    MOV     AX, MyData
    MOV     DS, AX
    MOV     AX, 0B800h
    MOV     ES, AX

    MOV BX, (25 * 160)

    loop25:

      SUB BX, 160
      CALL flipRow

      CMP BX, 0
    JNE loop25                ;if not equal to 0, numLoops - 1 and repeat

    MOV     AH, 4Ch
    INT     21h

MainProg ENDP

flipRow  PROC

    MOV DI, BX
    ADD DI, 158
    MOV SI, BX

 loopRow:

    MOV AX, ES: [DI]
    MOV CX, ES: [SI]
    MOV ES: [DI], CX
  CMP CX, 'C'                                 ;compare CX to 'C'
  JNE next                                    ;if != C go to next
    MOV ES: [DI + 1], BYTE PTR 01111100b
  next:
    MOV ES: [SI], AX
  CMP AX, 'C'                                 ;compare AC to 'C'
  JNE next2                                   ;if != C go to next2
    MOV ES: [SI + 1], BYTE PTR 01111100b
  next2:
    DEC DI
    DEC DI
    INC SI
    INC SI

  CMP SI, DI
  JL loopRow
    RET
flipRow ENDP

MyCode ENDS

A: The usual advice applies: learn to use a debugger.
That said, your problem is that you are comparing CX and AX, which contain the character and the attribute as well. You really want to compare just the character, so use CMP CL, 'C' and CMP AL, 'C' respectively.


text:
Q: How to search an array and get back it's "=>" value? I have an input:
$url = $params[0];

I have an array:
$dictionary = array(
    "stock" => 1,
    "user" => 2,
    "zone" => 3);

How can I use the input to search the left values of this array (stock, user, zone, etc.) and get back the value on the right (1, 2, 3, etc.)?

A: Pretty simple, just access it like this
$dictionary[$url]

A: You can use this $url variable as a key to get the => value associated with it.

 $dictionary = array(
            "stock" => 1,
            "user" => 2,
            "zone" =>3);

$url = $params[0];

$yourDesiredValue = $dictionary[$url];

A: Since you are searching, you will want to check if the value (I presume $url) is set within the array and return it if true.
$value = false;
if (isset($dictionary[$url])) {
  $value = $dictionary[$url];
}

Then, $value will be false if the search fails, but contain the number if the search is successful.


text:
Q: Getting Sum of an SQL table column until the sum reaches 5000 I am working on an sql query for a table with two columns Amount and Date which should return sum of Amount column values until reaches 5000 and it should also return the value in Date column at which Sum(Amount) reaches 5000 sorted by Date
For example I have the following data in my SQL TABLE
   ID Amount  Date
    1 1000    5/5/2014
    2 1000    5/1/2014
    3 900     5/3/2014
    4 1500    5/4/2014
    5 2000    5/4/2014
    6 2500    5/5/2014

In the above table the sum of Amount should be calculated after sorting it by Date and should return the sum of Amount and its associated Date once it reaches 5000 mark.
after sorting the data it becomes something like following
   ID Amount  Date
    2 1000    5/1/2014
    3 900     5/3/2014
    4 1500    5/4/2014
    5 2000    5/4/2014
    1 1000    5/5/2014
    6 2500    5/5/2014

The query should Return the following results
TotalAmount  Date
5400         5/4/2014

The above result is because the sum reached 5000 at ID=5 Amount=200 and Date=5/4/2014
May I know a better way to deal with it in SQL Server

A: For SQL Server, you can use SUM() OVER() and just get the first row where the total sum is >= 5000;
WITH cte AS (
  SELECT id, date, SUM(amount) OVER (ORDER BY date,id) totalamount
  FROM mytable
)
SELECT TOP 1 totalamount, date
FROM cte
WHERE totalamount >= 5000
ORDER BY date, id;

An SQLfiddle to test with.


text:
Q: JavaScript equivalent to .NET's Enum.HasFlag() My .NET backend handle enum authorization with HasFlag()
Enum Foo {
  0: Zero,
  1: One,
  2: Two,
  3: Three,
  ..
}

5.HasEnum(Foo.One) is falsy because 5 is equal to 3 + 2
6.HasEnum(Foo.One) is truthy because 6 is equal to 3 + 2 + 1

How to handle it in JavaScript ?
I'm receiving a rôle (that is > 0 and < 1048), how to know if it has 32 rôle ?


text:
Q: Use const int by reference to create static array I am trying to cretate an array of doubles in pi_sequence and then return a pointer to it. Then I want to print out its values. I tried this but I get the error storage size of ests is not constant:
#include <iostream>
#include <stdlib.h>

double* pi_sequence(const int& len)
{
  static double ests[len];
  ests[0] = 1.11;
  ests[1] = 2.22;
  return ests; // address of?
}

int main() {

  double* ests = pi_sequence();
  std::cout << "will write to file: " << ests[0]  << std::endl;

}

A:
Use const int by reference to create static array

Is not possible. The length of all arrays which have non-dynamic storage must be a compile time constant.
You can have a static vector:
assert(len >= 2);
static std::vector<double> ests(len);
// ...
return ests.data();


text:
Q: Using codecs in program As I've mentioned in my another question, I'm having trouble with Qt 5.1's multimedia module. The QMediaPlayer class can't play some MP3 files. I haven't tested other formats thoroughly.
I'm not sure if this is a codec related problem. But I'm interested in using codec directly in my program rather than relying on the backend support for playing media files. I'll be developing the application in Qt 5.1 for desktop Windows platform.
I have no idea about using codecs in programs. Any pointer will be greatly appreciated.

A: You can go to [FFMPEG]: http://www.ffmpeg.org/ to integrate the open-source codec to play your media file.


text:
Q: when generating text the text displays  how can I display the generated thing properly in tkinter python? from ctypes.wintypes import SIZE
from tkinter import * # import tkinter
import secrets

window = Tk() # creates window

window.title('PassGen') # changes title
window.geometry('600x400') # sets size
window.resizable(False,False) # prevents user from changing size

title = Label(window,text = 'PassGen', font=('Times',20)) # creates title
title.place(x=260,y=75) # displays title at desird location

v = DoubleVar()
scale = Scale(window, variable = v, from_ = 8, to = 16, orient = HORIZONTAL)
scale.pack(anchor=CENTER)
scale.place(x=235,y=170)

def s():
    if scale == 8:
        (secrets.token_hex(8))
    elif scale == 9:
        (secrets.token_hex(9))
    elif scale == 10:
        (secrets.token_hex(10))
    elif scale == 11:
        (secrets.token_hex(11))
    elif scale == 12:
        (secrets.token_hex(12))
    elif scale == 13:
        (secrets.token_hex(13))
    elif scale == 14:
        (secrets.token_hex(14))
    elif scale == 15:
        (secrets.token_hex(15))
    elif scale == 16:
        (secrets.token_hex(16))

def password():
    display = Text(window,height=1,width=32) # displays text
    display.insert('1.0', s) # inserts the pasword generator into the text
    display.place(x=80,y=153) # displays the ext in a specific place
    display.config(state='disabled') # prevents user from editing password

button = Button(window, text = 'Generate Password', command = password).place(x=350,y=150) # button for user to click and generate password.

window.mainloop()# displays window infinitely

when generating text the text displays <function s at 0x000001B240AB3E2> how can I display the generated thing properly in tkinter python?
I want the scale to control the length of the generated text but it displays <function s at 0x000001B240AB3E20> instead of something like dljvdlk2okd0d

A: You should do display.insert('1.0', s()) instead of just s (because originally you just pass a reference to s instead of whatever string it returns.
You should also return your results in s() like return secrets.token_hex() instead of just putting them in parathesis. Python doesn't have implicit return.

A: There are few issues in your code:

*

*it is better to use IntVar instead of DoubleVar for v

*need to return result from s()

*use s() instead of s in display.insert('1.0', s)
...
v = IntVar()  # use IntVar instead of DoubleVar
scale = Scale(window, variable = v, from_ = 8, to = 16, orient = HORIZONTAL)
...
def s():
    return secrets.token_hex(v.get())

def password():
    display = Text(window,height=1,width=32) # displays text
    ### use s() instead of s in below line
    display.insert('1.0', s()) # inserts the pasword generator into the text
    display.place(x=80,y=153) # displays the ext in a specific place
    display.config(state='disabled') # prevents user from editing password
...

Actually you don't need s() at all:
def password():
    display = Text(window,height=1,width=32) # displays text
    # call secrets.token_hex(v.get()) directly instead of s()
    display.insert('1.0', secrets.token_hex(v.get()))
    display.place(x=80,y=153) # displays the ext in a specific place
    display.config(state='disabled') # prevents user from editing password


text:
Q: Invalid column count in CSV input on line 1 error (Already checked other questions) So I've seen this question asked many times but I have not found an answer to my issue. I'm using phpmyadmin, I have 1 table with 2 columns and I have a .csv with 2 columns. My csv does not have headers and my columns are separated by ";", already changed it in phpmyadmin to "Columns separated with ;", but I still got the same error. Can anyone help?

edit: I'm using the "Import" option of phpMyAdmin to import my csv

edit2: So I decided to export my table to see how the csv was generated. It exports like this:
"1", "1001"
"2", "1002"
Do you know why? or how can I create an csv file with the same format?
export table

A: As it says in the manual

When importing data into a table from a CSV file where the table has an 'auto_increment' field, make the 'auto_increment' value for each record in the CSV field to be '0' (zero). This allows the 'auto_increment' field to populate correctly.

see https://docs.phpmyadmin.net/en/latest/import_export.html

A: So, what worked for me was: I exported the table as an csv and worked over that. After I was done, I imported this modified csv and it worked. It must've been what nbk said about termination, so I guess in a way that was the answer


text:
Q: How overlay bitmap and shape in layer-list properly I want make button with white border and bitmap at the left side:

I have xml for background:
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <corners android:radius="10.0dip"/>
            <stroke
                android:width="2px"
                android:color="@android:color/white"/>
        </shape>
    </item>
    <item>
        <bitmap
            android:gravity="left"
            android:src="@drawable/vk_login">
        </bitmap>
    </item>
</layer-list>

And result is:

I don't know how make border and cut corners from bitmap. What is best way to make background like first image?

A: I have create shape file as per your requirement:
1) Here is your drawable named as : btn_vk_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="#FABC38"></solid>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape>
    </item>
    <item>
        <bitmap
            android:gravity="left|center_horizontal"
            android:src="@drawable/vk_login"></bitmap>
    </item>
    <item>
        <shape>
            <corners android:radius="10dip" />
            <stroke
                android:width="2px"
                android:color="@android:color/white" />
        </shape>
    </item>

</layer-list>

2) In your layout layout xml you can define button like:
 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="100dp"
        android:background="@drawable/btn_vk_drawable"
        android:text="VK"
        android:ems="12"
        android:textAlignment="center" />

Using 9 patch :  btn_vk_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="#FABC38"></solid>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape>
    </item>
    <item>
        <!--<bitmap-->
        <!--android:gravity="left|center_horizontal"-->
        <!--android:src="@drawable/t"></bitmap>-->
        <nine-patch
            android:dither="true"
            android:src="@drawable/common_signin_btn_text_normal_dark.9" />
    </item>

</layer-list>

A: You just need to add padding in your code:
I have updated your code :-

<item>
    <shape>
        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />

        <corners android:radius="10.0dip" />

        <stroke
            android:width="2px"
            android:color="@android:color/black" />
    </shape>
</item>
<item>
    <bitmap
        android:gravity="left"
        android:src="@drawable/bg_casedetail_audio" >
    </bitmap>
</item>


text:
Q: How to create an event that calls the registered listener as soon as it's registered if event was already invoked? (C#) I want to create a special sort of delegate in my program which upon listener registration to it, I want to check if it's already been called, and if so - immediatley call the subscribing listener.
Looking at it atomically I was able to achieve it using the following:
private bool _wasEventCalled;
private event Action _someEvent;

public event Action SomeEvent
{
    add
    {
        if (value == null)
        {
            return;
        }

        // If already called, call immediatley
        if (_wasEventCalled)
        {
            value(this);
            return;
        }
        _someEvent += value;
    }
    remove
    {
        if (_someEvent == null)
        {
            return;
        }
        _someEvent -= value;
    }
}

private void InvokeEvent()
{
    _wasEventCalled = true;
    _someEvent.Invoke();
}

This works just fine, but I'm looking for a way to create a generic event which I can reuse - since this is a lot of code to write every time I want to use this behavior.

A: What you're describing is more or less the behavior of Task continuations, so you can just piggyback onto Task.
private TaskCompletionSource<bool> someEventSource =
    new TaskCompletionSource<bool>();

public event Action SomeEvent
{
    add
    {
        someEventSource.Task.ContinueWith(t => value?.Invoke());
    }
    remove
    {
        throw new NotImplementedException();
    }
}

private void InvokeEvent()
{
    someEventSource.TrySetResult(true);
}

Of note, tasks don't really support removing handlers, so you'd need to write your own class if that was important for you to have.