text:
Q: Add cascade delete for all nested child in hierarchy chain I would like to get the following behavior, when deleting an object from a parent level of first level, all entities "child" were deleted automatically, say I have a Library class that has a list "areas", each area has a list of "corridors", and each corridor has a "ranks" list, each rank has a list of books. Did you understand that the level is going down?
Schematic model:
Library
-----> Area
----------> Corridors
---------------> Ranks
--------------------> Book

Classes:
class Library {
    public int Id {get;set;}
    public List<Area> Areas {get;set;}
}

class Area {
    public int Id {get;set;}
    public Library Library {get;set;}
    public List<Corridor> Corridors {get;set;}
}

class Corridor {
    public int Id {get;set;}
    public Area Area {get;set;}
    public List<Rank> Ranks {get;set;}
}

class Rank {
    public int Id {get;set;}
    public Corridor Corridor {get;set;}
    public List<Book> Books {get;set;}
}

class Book {
    public int Id {get;set;}
    public Rank Rank {get;set;}
    public string Name {get;set;}
}

I wish that when I erased Library, I would erase the children that were needed within the chain, cascade. I can do this with the following code, I made all my classes inherit from a common class that I called "Registry", and that all of them had a common property called "Library", and I configured it as follows:
modelBuilder.Model.GetEntityTypes()
    .Where(t => typeof(Registry).IsAssignableFrom(t.ClrType))
    .ToList()
    .ForEach(prop =>
    {
        modelBuilder
        .Entity(prop.Name)
        .HasOne(typeof(Library), "Library")
        .WithMany()
        .OnDelete(DeleteBehavior.Cascade);
    });

I tested with a 20 classes and ran, in the created migration, all 20 entities, have an FK pointing to Library, called "LibraryId" and with the property, "onDelete: ReferentialAction.Cascade", but I have a structure with 650 classes, it is completely impracticable to be inheriting all of them from the Registry class, I think there should be a simpler and more efficient way, but I do not know how to do it ...

A: For required relationships (non-nullable foreign key) it is not possible to save a null foreign key value, so cascade delete behavior is by default.
You can simply create hierarchy:
class Parent {
    public Guid Id {get;set;}
}

class Child {
    public Guid Id {get;set;}

    public Guid ParentId {get;set;}
    public Parent Parent {get;set;}
}

And Ef core knows that children should be deleted with Parent because ParentId is Required. Read Doc for more details

A: class Library {
public int Id {get;set;}
public List<Area> Areas {get;set;}
}

class Area {
public int Id {get;set;}
public Library Library {get;set;}
public int LibraryId {get;set;}
public List<Corridor> Corridors {get;set;}
}

class Corridor {
public int Id {get;set;}
public Area Area {get;set;}
public int AreaId {get;set;}
public List<Rank> Ranks {get;set;}
}

class Rank {
public int Id {get;set;}
public Corridor Corridor {get;set;}
public int CorridorId {get;set;}
public List<Book> Books {get;set;}
}

class Book {
public int Id {get;set;}
public Rank Rank {get;set;}
public int RankId {get;set;}
public string Name {get;set;}
}

Adding the RankId to the book class cause EF to use ondelete:cascade for Book and Rank. This goes for the other classes


text:
Q: How to VCS a large-scale, "atomic" refactoring? When migrating a project from one heavily-used library X to another library Y which is essentially equivalent but doesn't have the same API, it may be necessary to make a lot of changes. In the case I'm working on right now, ≈500 additions and deletions: not impossible, but I'd normally say, that's too many for a single commit! (I have in the past had quite some negative experience with too-big commits, and the arising merge conflicts.)
But with only a subset of the changes done, the project doesn't compile. Furthermore, the changes are essentially mechanical: for every function foo previously used from X, there's either a foo' in Y that does exactly the same thing (despite having a different name) or only a very simple wrapper needs to be written.
Is it sensible to first make all the changes and put them in a single commit, or should I better try to split it up somehow? How is this handled when multiple people are working on the refactoring and you can't really wait till it's all done before interacting via VCS – "single-use commits" that are squashed before merging into the master branch, or something else?

A: Splitting a large commit in those squashed single-use commits won't matter from the point of view of downstream merge conflicts - since they're squashed they'll still appear as a single large commit at merge time, including at conflict resolution.
I'd always use wrappers (instead of just re-using the function names). Each and all wrappers would incorporate a single/central control able to switch the entire product between the before and after refactoring. The switch stays in the before position in the VCS until the refactoring is complete. Developers working on the refactoring can turn it to after in their workspaces to work on their portions of the refactoring and turn it back to before when committing the work.
Adding or removing wrappers or wrapper invocations can be done in small/incremental commits, as needed.
This approach allows both the regular work and the refactoring to happen in the same branch, eliminating the need of going on a separate branch just for the purpose of refactoring, thus eliminates the merge altogether.
The great advantage is that you can combine 2 different CI executions (one for each position of the control switch) and get a very precise measurement of how close to target the refactoring is. That would be practically impossible if using a separate branch since a branch merge would still be unaccounted for (always undeterministic, especially for a large refactoring branch).
The above paragraph assumes a CI system capable to patch a small VCS change (flipping the control switch) at the beginning of its execution. If such CI system is not available a tiny branch - containing just the flipped control switch change - can be used instead. Such branch can be automatically sync'd after every commit in the main branch (should be a trivial sync). Yes, an upcoming branch merge would still be outstanding, but it's a deterministic one - a one-liner change.
When the measured after quality level is acceptable and the decision to accept the refactoring is made the control is switched to after in the VCS system and the cleanup work can begin: removing the wrappers, the old library and finally the control switch itself (which also can be done in small incremental commits).

A: If the transition is going to take on the order of months, it's better to find a way to architect your software so you can have both libraries in your main branch at the same time and make a gradual transition.  Use wrappers or feature flags or a microservice model.  This takes longer, but is worth it in terms of stability.
If it's going to take a few weeks or less, it's better to do a normal feature branch.  When I work on similar tasks with a colleague, we pair program for the initial branch creation, library replacement, and fixing of one file's unit and integration tests.  Then we push the branch and split up the remaining work, making commits after every file's worth of changes.
As far as merge conflicts go, what's important is that merges occur frequently, it doesn't particularly matter which direction.  If you merge from master into your feature branch once a day or so, you won't have a big scary merge at the end.  It's still the same overall number of merge conflicts.  That's unavoidable.  It's just spread out throughout the few weeks you're working on your changes, and happening closer to when you changed that actual file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting string objects to int/float using pandas import pandas as pd

path1 = "/home/supertramp/Desktop/100&life_180_data.csv"

mydf =  pd.read_csv(path1)

numcigar = {"Never":0 ,"1-5 Cigarettes/day" :1,"10-20 Cigarettes/day":4}

print mydf['Cigarettes']

mydf['CigarNum'] = mydf['Cigarettes'].apply(numcigar.get).astype(float)

print mydf['CigarNum']

mydf.to_csv('/home/supertramp/Desktop/powerRangers.csv')

The csv file "100&life_180_data.csv" contains columns like age, bmi,Cigarettes,Alocohol etc.
No                int64
Age               int64
BMI             float64
Alcohol          object
Cigarettes       object
dtype: object

Cigarettes column contains "Never" "1-5 Cigarettes/day","10-20 Cigarettes/day".
I want to assign weights to these object (Never,1-5 Cigarettes/day ,....)
The expected output is new column CigarNum appended which consists only numbers 0,1,2
CigarNum is as expected till 8 rows and then shows Nan till last row in CigarNum column
0                     Never
1                     Never
2        1-5 Cigarettes/day
3                     Never
4                     Never
5                     Never
6                     Never
7                     Never
8                     Never
9                     Never
10                    Never
11                    Never
12     10-20 Cigarettes/day
13       1-5 Cigarettes/day
14                    Never
...
167                    Never
168                    Never
169     10-20 Cigarettes/day
170                    Never
171                    Never
172                    Never
173                    Never
174                    Never
175                    Never
176                    Never
177                    Never
178                    Never
179                    Never
180                    Never
181                    Never
Name: Cigarettes, Length: 182, dtype: object

The output I get shoudln't give NaN after few first rows.
0      0
1      0
2      1
3      0
4      0
5      0
6      0
7      0
8      0
9      0
10   NaN
11   NaN
12   NaN
13   NaN
14     0
...
167   NaN
168   NaN
169   NaN
170   NaN
171   NaN
172   NaN
173   NaN
174   NaN
175   NaN
176   NaN
177   NaN
178   NaN
179   NaN
180   NaN
181   NaN
Name: CigarNum, Length: 182, dtype: float64

A: Try using this function for all problems of this kind:
def get_series_ids(x):
    '''Function returns a pandas series consisting of ids,
       corresponding to objects in input pandas series x
       Example:
       get_series_ids(pd.Series(['a','a','b','b','c']))
       returns Series([0,0,1,1,2], dtype=int)'''

    values = np.unique(x)
    values2nums = dict(zip(values,range(len(values))))
    return x.replace(values2nums)

A: OK, first problem is you have embedded spaces causing the function to incorrectly apply:
fix this using vectorised str:
mydf['Cigarettes'] = mydf['Cigarettes'].str.replace(' ', '')

now create your new column should just work:
mydf['CigarNum'] = mydf['Cigarettes'].apply(numcigar.get).astype(float)

UPDATE
Thanks to @Jeff as always for pointing out superior ways to do things:
So you can call replace instead of calling apply:
mydf['CigarNum'] = mydf['Cigarettes'].replace(numcigar)
# now convert the types
mydf['CigarNum'] = mydf['CigarNum'].convert_objects(convert_numeric=True)

you can also use factorize method also.
Thinking about it why not just set the dict values to be floats anyway and then you avoid the type conversion?
So:
numcigar = {"Never":0.0 ,"1-5 Cigarettes/day" :1.0,"10-20 Cigarettes/day":4.0}

Version 0.17.0 or newer
convert_objects is deprecated since 0.17.0, this has been replaced with to_numeric
mydf['CigarNum'] = pd.to_numeric(mydf['CigarNum'], errors='coerce')

Here errors='coerce' will return NaN where the values cannot be converted to a numeric value, without this it will raise an exception


text:
Q: Could I use the ID-based GitHub-provided noreply address in git? Would my contributions be counted if I use the ID-based GitHub-provided noreply address in git as the email and push changes ?
My ID-based GitHub-provided noreply address looks like this ID+username@users.noreply.github.com

A: Short answer? Yes, your contributions will be counted.
Longer answer? Yes, they will be counted, but doing it this way may have ramifications for you in the future. For context, GitHub assigns contributions to accounts by the email address used to git commit. Therefore, if you change your GitHub username in the future, your GitHub-assigned email would change, and GitHub won't assign commits from your old GitHub email to your account anymore. (I know from personal experience.) If you're interested in keeping your email private but still having your changes counted, I might recommend attributing your commits to some email that you only use for git, but that you know won't change over time if you ever decide to change your username.
Edit: Under the old GitHub system with username@users.noreply.github.com emails, the commits would no longer be attributed after you changed your username. Because you have one of the new ID+username@users.noreply.github.com email addresses, you'll be fine even after changing username. GoodDeeds' answer notes this correctly.
See this documentation page for more information about GitHub private email addresses and how to set them up. Also, if you're interested, here is a GitHub blog post about securing your account further by rejecting pushes that contain a public email.

A: Your contributions will be counted by GitHub as usual. Ever since ID-based noreply addresses were introduced, your contributions continue to be counted even if you change your username in the future (unless GitHub changes its policy in the future). The relevant documentation can be found here, and further explanation is given here.


text:
Q: node-postgres: done() - undefined is not a function I am having a problem with my query function using node-postgres.
Selects, inserts and deletes all successfully perform the database query, but inserts and deletes trigger this error on the node server:
/vagrant/catalog/database/db.js:11
                done();
                ^
TypeError: undefined is not a function
    at null.callback (/vagrant/catalog/database/db.js:11:17)
    at p.handleReadyForQuery (/vagrant/catalog/node_modules/pg/lib/query.js:78:10)
    at null.<anonymous> (/vagrant/catalog/node_modules/pg/lib/client.js:111:24)
    at emit (events.js:117:20)
    at Socket.<anonymous> (/vagrant/catalog/node_modules/pg/lib/connection.js:47:12)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:765:14)
    at Socket.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:427:10)
    at emitReadable (_stream_readable.js:423:5)

Here is the query function:
var pg = require('pg');
var connectionString = 'postgres://vagrant:vagrant@localhost:5432/catalog';

module.exports = {
    query: function(text, values, callback) {
        pg.connect(connectionString, function(err, client, done) {
            client.query(text, values, function(err, result) {
                if (err) throw err;
                done();
                callback(err, result);
            });
        });
    }
};

Which is being called by endpoints such as:
app.delete(api + '/games/:id', function(req, res) {
    query('DELETE FROM videogame WHERE id=$1', [req.params.id], function(err, result) {
        if (err) throw err;
        return res.json({'success': true});
    });
});

Any idea what's causing this?

A: Solution was upgrading to 4.4.1.


text: Q: Get the war file name from an external properties file in the maven build When a web application is built using maven, I want to generate the war file with a name present in an external properties file.  What is the confguration required in pom.xml for this?


text:
Q: SQL subquery to get all rows of columns where other column value does not exist I have the following Accounts_Users table:
account_id | user_id
--------------------
1          | 60
2          | 60
3          | 60
1          | 50
3          | 50
3          | 40

And I want to retrieve all the user_id's which do not have rows with certain account_id For example if the account_id = 2 I want the result should be:
user_id
-------
50
40

Since user_id = 60 have record with account = 2.

How can I do it using subqueries or in any other way?

A: Subquery way:
select distinct user_id
from accounts_users
where user_id not in (
    select user_id
    from accounts_users
    where account_id = 2)

Join way:
select distinct a.user_id
from accounts_users a
left join accounts_users b on b.user_id = a.user_id
    and b.account_id = 2
where b.user_id is null

A: You use a subquery:
select distinct user_id
from Accounts_Users
where user_id not in (
  select user_id from Accounts_Users where account_id = 2
)


text:
Q: Scheduling post using python- graphAPI on facebook Is there any way to schedule a post using python-graph API for Facebook? I'm trying to code this in Python and I couldn't find any such parameter in put_object method in its documentation (https://facebook-sdk.readthedocs.io/en/latest/api.html)
Can you suggest me any other way to attach time with every post or a way where I can assign a post to a particular date and time on a calendar?


text:
Q: How to enable proximity sensor in android I have configured proximeter successfully in my code. Now I want to turn off & on screen programmatically. Code of sensor is working just fine and following method is also getting called.
@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WakeLock screenWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"screenWakeLock");

    if (event.values[0] == 0) {
        screenWakeLock.acquire();
        Log.e("onSensorChanged","NEAR");
    } else {
        if (screenWakeLock != null) {
               if(screenWakeLock.isHeld())
                  screenWakeLock.release();
               screenWakeLock = null;
        }
        Log.e("onSensorChanged","FAR");
    }
}

My problem is that screen is not getting turn off. I also have added required permission in code. What else could be the reason ???

A: Check the changes submitted for this code, https://github.com/jitsi/jitsi-android/compare/6d356fa637ae...7aba481d773f
getPowerManager().newWakeLock( 32, "proximity_off");

A: As from my understanding wakelock is useful to keep screen on. I wasn't successful to turn screen on & off using it.
So, first I dimmed screen brightness as low as possible and then made all GUI elements unclickable. This way I solved my problem.
Following is method:
@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    WindowManager.LayoutParams params = this.getWindow().getAttributes();

    if (event.values[0] == 0) {
        //TODO Store original brightness value
        params.screenBrightness = 0.004f;
        this.getWindow().setAttributes(params);
        enableDisableViewGroup((ViewGroup)findViewById(R.id.YOUR_MAIN_LAYOUT).getParent(),false);
        Log.e("onSensorChanged","NEAR");

    } else {
        //TODO Store original brightness value
        params.screenBrightness = -1.0f;
        this.getWindow().setAttributes(params);
        enableDisableViewGroup((ViewGroup)findViewById(R.id.YOUR_MAIN_LAYOUT).getParent(),true);
        Log.e("onSensorChanged","FAR");
    }
}

From here, I took reference to disable touch for entire screen's view.

A: Try this shortcut:
PowerManager manager = getPowerManager();
WakeLock lock = manager.newWakeLock( 32, "proximity_off");
lock.acquire();

The above code doesn't even need the proximity sensor changed events to be listened. 32 is for a hidden WakeLock field that is used by the InCallActivity of the Phone and other such similar applications.


text:
Q: No se despliega teclado al tocar input Estoy con una  app realizada en android studio ( java ) que al salir y volver a ingresar a la misma ya no funciona que se muestre el teclado en pantalla. Sucede en varios lados de la activity, que tiene varios fragment adentro. Si se desinstala la app y se vuelve a instalar, a veces funciona a la primera vez y otras no
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/et_listado_buscador"
            android:layout_width="341dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:hint="Buscador"
            android:inputType="textPersonName" />

        <ImageView
            android:id="@+id/img_button_maps"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_baseline_map_24" />

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_listado"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
Q: Set default option in dialogprompt I have this:
var dialog = new PromptDialog.PromptChoice<string>(
    new string[] { "Yes", "No" },
    "Are you sure?",
    "Sorry, that wasn't a valid option",
    3
);

How do I set the dialog's default option to No?


text:
Q: Delete Sierra installer from Launchpad How do I delete the "half-cooked" Sierra installer?  The App store and "About this mac" show that Sierra is downloaded, but I still have that installer hanging out in my Lauchpad.  How can i get rid of it?  Is it safe to do so?

A: I think there is one more way of doing it. You just have to go to the Application folder, select the application and press CMD + Delete. Once you do this, the particular application will disappear from your launchpad as well.

A: Remove Applications from Launchpad One at a Time
There are two ways to do this, one is through the Launchpad itself, and the other is through the Terminal using the command line:
Method 1) Using Launchpad – Mac App Store apps only
Hold down the Option key, and once the icons start jiggling click the "X" shown in the corner of icons that you want to delete. This removes the app from Launchpad, and does not uninstall them, but this is limited to apps installed from the Mac App Store. If you want to remove an app not installed through the Mac App Store, you have to use the method below:
Method 2) Using the Terminal – removes any application
Launch the Terminal and enter the following command, replacing "APPNAME" with the name of the application you want to remove from Launchpad:
sqlite3 ~/Library/Application\ Support/Dock/*.db "DELETE from apps WHERE title='APPNAME';" && killall Dock

For example, removing TmpDisk would be:
sqlite3 ~/Library/Application\ Support/Dock/*.db "DELETE from apps WHERE title='TmpDisk';" && killall Dock

Launchpad will automatically refresh, open it to see the changes.


text:
Q: XSD overrides SSIS I have a XML I'm reading into tables.  I have this XSD:
        <xs:element name="ListingDescription"
                        type="xs:string"
                        minOccurs="0"
                        maxOccurs="1">
            <xs:annotation>
                <xs:documentation>
                    This is a longer description of the listing.
                </xs:documentation>
                <xs:appinfo>
                    <retsid>101950</retsid>
                </xs:appinfo>
            </xs:annotation>
        </xs:element>

for some reason I this case xs:string defaults to 255, and the data in the associated XML is larger than that.  I attempted to update the XMLSource stage in the SSIS package with larger lengths, but the xsd keeps overriding that back to 255.  How to I fix up xs:string into something that can feed into a nvarchar(4000)?
thanks


text:
Q: SonarQube 5.1.1 "Unable to set search root context for components" I've recently upgraded to SonarQube 5.1.1 from 3.7.4. The upgrade appeared to go well.  When I navigate to the home page, I see the projects that existed before.  I navigate to a particular project and see its issues.  However, when I drilldown, say to the Major issues, and click on a source file link, I receive the following message instead of any marked up source code:
"Unable to set search root context for components"
SonarQube is running on linux with jdk1.7.0_09.  The database is Oracle 11g. Any idea what's happening?

A: I think that is problem is "normal". In fact, in 5.0 release notes, you can see this

http://docs.sonarqube.org/display/SONAR/Release+5.0+Upgrade+Notes
Noteworthy
    After the migration, source syntax-highlighting won't be available on a project until it has been successfully analyzed

In tried to launch analyze from a new project, and i saw source code ! So, now, i've to launch analyse for all projects :\


text:
Q: Android: how to get own profile picture like in native Messaging app I'm writing an application for SMS messaging and I want to show profile picture of all senders (it is not a problem) and picture of my profile for sent messages. The same implementation was done in native Messaging app.
Could you please advice how I can get own profile picture?

A: I found a solution for my question:
public static Bitmap getProfilePhoto(Context context) {
        Bitmap profilePhoto = null;
        ContentResolver cr = context.getContentResolver();
        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, ContactsContract.Profile.CONTENT_URI);
        if (input != null) {
            profilePhoto = BitmapFactory.decodeStream(input);
        } else {
            profilePhoto = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_contact_picture);
        }

        return profilePhoto;
    }

A: Read up here
http://developer.android.com/reference/android/provider/ContactsContract.Profile.html
and then
look into CursorLoader's and cursors, write one to query for the photo uri or photo thumbnail uri.
Update
I found similar questions that should help you
Get profile picture of specific phone number from contacts information
Get user/owner profile contact URI and user image with API 8 onwards


text:
Q: Bypass Page.VerifyRenderingInServerForm I am trying to render a Wizard control to a HTML string on the click of a Button (using Control.Render). I am already disabling event validation with the following, which works fine and enables me to render the entire Page to the string. I do this within the user control that contains the Wizard:
protected void Page_Init(object sender, EventArgs e)
{
    if (Request.Form["__EVENTTARGET"] != null
        && Request.Form["__EVENTTARGET"] == btnPrint.ClientID.Replace("_", "$"))
    {
        Page.EnableEventValidation = false;
    }
}

While this works, I'd like to render the Wizard control on its own. I understand that I can override Page.VerifyRenderingInServerForm in order to prevent the page from throwing an exception when I attempt to render this control on its own (without runat="server" form tags), like so:
public override void VerifyRenderingInServerForm(Control control)
{
    // base.VerifyRenderingInServerForm(control);
}

However, I don't want to override this completely. Is there a way I can bypass this dynamically, either:

*

*For the specific PostBack in which the button in question is clicked, or...

*Specifically for the Wizard control?

A: How about something like:
public override void VerifyRenderingInServerForm(Control control)
{
    if (!SkipVerifyRenderingInServerForm)
    {
        base.VerifyRenderingInServerForm(control);
    }
}

public bool SkipVerifyRenderingInServerForm
{
    get
    {
        object o = HttpContext.Current.Items["SkipVerifyRenderingInServerForm"];
        return (o == null) ? false : (bool) o;
    }
    set
    {
        HttpContext.Current.Items["SkipVerifyRenderingInServerForm"] = value;
    }
}

You could then set SkipVerifyRenderingInServerForm to true in your button click event handler.


text:
Q: A Minkowski like inequality for symmetric sums Let $(u_1, u_2, u_3, u_4)$ and $(v_1, v_2, v_3, v_4)$ be vectors in $\mathbb R_+^4$. Is the following inequality true? (Matlab simulations did not yield a counterexample.)
\begin{align*}
\left(\sum_{{4 \choose 3}} \sqrt{u_i u_j u_k}\right)^{2/3} + \left(\sum_{{4 \choose 3}} \sqrt{v_i v_j v_k}\right)^{2/3} \leq  \left(\sum_{{4 \choose 3}} \sqrt{(v_i+u_i) (v_j+u_j) (v_k+u_k)}\right)^{2/3}
\end{align*}
Here $\sum_{{4 \choose 3}}$ refers to $\sum_{1\leq i < j < k \leq 4}$.


text:
Q: jQuery load() callback failure in IE Hi guys before posting this, I've already gone and looked around many places trying to solve the problem but couldn't. This was the closest thing that I came across.
I am trying to dynamically create an iframe and load the content in to its src then use the callback to do something to it. As always, everything works in FF/Chrome except in IE.
I have something like this:
var iframe = $('#helloworld');
if (!iframe.exists()) {
    iframe = $('<iframe/>', {
        id : 'helloworld',
        src : "about:blank"
    }).css({
        width : "100%",
        height : "100%"
    });
}

...
iframe.load(options.src, function() {
    div.append(this);
    $(this).find('body').append(box);
    box.dialog({
        close: function( event, ui ) {
            iframe.load("about:blank");
            div.hide();
        }
    });
});

Similar to many other people's problem, it failed at the callback. From what I've read in other posts, it was due to invalid html coming back to the iframe, however, I've already checked that, and my html is valid.
This is what I am returning for my iframe, as you can see is already stripped to the bare minimum for testing purposes.
<!DOCTYPE html>
<html dir="ltr">

    <head>
        <title>Testing</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
        <style type="text/css">
        </style>
    </head>

    <body></body>

</html>

In IE, the jQuery is dying @ line 5951:
append: function() {
    return this.domManip(arguments, true, function( elem ) {
        if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
            this.appendChild( elem );
        }
    });
},

SCRIPT65535: Unexpected call to method or property access.
jquery-1.9.1.js, line 5951 character 5
Where this is supposedly to be my iframe, and it doesn't have appendChild method.
Any hint for me to further troubleshoot this problem?

A: You can not use load() like that with an iframe. If you want to know when the content is done loading in an iframe, use the onload event and set the src attribute.
iframe.on("load", function() {
    //code here
});

iframe.attr("src", options.src);

You will get your callback when the content is loaded.
Now to use the content in the iframe, you need to use contents()
iframe.contents().find("body")...

A: To my knowledge .load loads HTML into the specified node.
So iframe.load(options.src, /* */);
Will load the value of options.src as the HTML body for the iframe. I doubt you want that.
I think you want:
iframe.attr("src", options.src);
// or
iframe.attr("src", "about:blank");


text:
Q: SVG masking clipPath dont work properly in a container in Chrome I try to mask an element with a SVG clip-path and followed this workaround: https://sarasoueidan.com/blog/css-svg-clipping/
Everthing works well in Chrome and Firefox, its seems to be the best solution.
But when i put the content in a container to center it, chrome is having problems with the mask. Firefox is centering the content while in chrome the mask seems to stick on the left side of the browser.
You can see it in this is the Fiddle:           https://jsfiddle.net/mideyahdotch/wk58Lq7h/2/

<svg height="0" width="0">
 <defs>
  <clipPath id="svgPath">
    <path fill="#FFFFFF" stroke="#000000" stroke-width="1.5794"
    stroke-miterlimit="10" d="M0.4,467.35l1080-30.77V0.22L0.4-.28V467.35Z" />
  </clipPath>
 </defs>
</svg>

Anyone knows an answer to this issue?
Thanks for your support!
mideyah


text:
Q: silverlight runtime contextmenu the Question is that, is it possible to have a silverlight context menu in runtime (which its menu items can be manipulated, ie added or removed in runtime)?
as I searched, there are some types of adding Context menu in silverlight by xaml, But I didn' found any solution to add it in runtime

A: ContextMenu menu = new ContextMenu();

ContextMenuItem item1 = new ContextMenuItem();
item1.Content = "新建";

ContextMenuItem item2 = new ContextMenuItem();
item2.Content = "保存":

menu.Items.Add(item1);
menu.Items.Add(item2);

A: ContextMenu menu = new ContextMenu();
MenuItem item1 = new MenuItem();
item1.Header = "new";
item1.Click +=new RoutedEventHandler(item1_Click);
menu.Items.Add(item1);
you can use ↓
Telerik provide RadControl for SilveLight
RadMenu menu = new RadMenu();
RadMenuItem item1 = new RadMenuItem();
RadMenuItem item1_01 = new RadMenuItem();
item.Items.add(item1_01);
menu.Items.Add(item);
no matter RadMenu or RadMenuItem or ContextMenu ,
你都可以添加事件,他们都是继承与Sytem.window.Control;
forgive ^_^


text:
Q: In slave Mongodb 3.0.1, when I run "show dbs" command I'm getting the below error After clustering the Mongodb 3.0.1 in two machines. In slave mode when I run this command "show dbs" it is showing "not master" error.
Here is the error:
E QUERY Error: listDatabases failed:
        { "note" : "from execCommand", "ok" : 0, "errmsg" : "not master" }
at Error (<anonymous>)

Please tell me, how can I overcome this problem.

A: Please use rs.slaveOk() on the mongo console you are getting the error.


text:
Q: Prestashop - Integrate Bizum method I am trying to integrate the BIZUM payment method in a prestashop store and for this I have installed the payment method addon "redsys" and I am modifying it, for what I have done is take the file redsys.php from the module and modify it by this code
        /*
 * HOOK V1.7
 */
public function hookPaymentOptions($params) {

if (! $this->active) {
    return;
}

if (! $this->checkCurrency ( $params ['cart'] )) {
    return;
}

$this->createParameter($params);

$urlBizum = 'https://sis-t.redsys.es:25443/sis/realizarPago';

    $newOption2 = new \PrestaShop\PrestaShop\Core\Payment\PaymentOption();
    $newOption2->setCallToActionText ($this->l('Pago con Bizum' ))
        ->setAction ($urlBizum)
        ->setInputs([
            'Ds_SignatureVersion' => [
                'name' =>'Ds_SignatureVersion',
                'type' =>'hidden',
                'value' =>$this->version2,
            ],
            'Ds_MerchantParameters' => [
                'name' =>'Ds_MerchantParameters',
                'type' =>'hidden',
                'value' =>$this->paramsBase64,
            ],
            'Ds_Signature' => [
                'name' =>'Ds_Signature',
                'type' =>'hidden',
                'value' => $this->signatureMac,
            ],
            'Ds_Merchant_PayMethods' => [
                'name' =>'Ds_Merchant_PayMethods',
                'type' =>'hidden',
                'value' => 'z',
            ],
        ]);

    $payment_options = [$newOption2];

    return $payment_options;
}

The problem I have is that I get the redsys TVP screen ... and not the bizum I'm waiting for.
Thank you


text:
Q: Execute animations sequentially instead of simulatenously using class selector Self admitted newbie here, hope this will be a simple solution.
$(.classname).slideUp();

When I execute the above code, all of the elements slide up at the same time.  Instead, I would like them to perform the animation one after another.
Any help?  Thanks!

A: Try this:
var animInterval = 100; // 100ms interval between animation starts
$('.className').each(function (i, e) {
    setTimeout(function () {
        $(e).slideUp();
    },i * animInterval);
});


text:
Q: Can't reload PFQueryTableViewController as a container view I have a popover view that I added a PFQueryTableViewController too, as a childviewController. I have a button on the popover that, when pressed, should reload the tableview in the PFQueryTableViewController.
Here is the code in the buttonPressed method that should do this:
NotificationsTableViewController *note = (NotificationsTableViewController *)self.childViewControllers[0];
[note loadObjects];
[note.tableView reloadData];

The table is not reloaded, though, and the only way I can get it to reload is by instantiating a whole new controller and adding it to the popover, which is not something I want to end up doing.
Here is some more code:
//NotificationsPopoverController
@class NotificationsTableViewController;

@protocol PopDelegate <NSObject>

-(void) changedQue;
@end

@interface NotificationsPopoverController : PDPopoverController

@property (nonatomic, assign) id<PopDelegate>  myDelegate;

@property NotificationsTableViewController *noti;

When my button is pressed I call [self.myDelegate changedQue];
//NotificationsTableViewController.h
@interface NotificationsTableViewController : PFQueryTableViewController <PopDelegate>

//NotificationsTableViewController.m
-(void)changedQue
{
    NSLog(@"Did it work?");

    [self.tableView reloadData];
    [self loadObjects];

}

The log statement is not printed for some reason, not sure why...

A: I haven't understand the flow completely yet. I think somewhere you will have to add self.note.myDelegate = self;. Hm... I think your have implemented delegate wrongly. Can you paste more complete code on both the view controller.
As per Jacob, add self.myDelegate = self.noti; right after the child view noti solves the problem.


text:
Q: Выбрать 50% от результирующей таблицы select 50 percent skills / stage from personal order by skills / stage;

skills - колонка
stage - колонка
A: Можно 2 запросами. Сначала выбрать количество всех:
select count(skills) from `personal `;

Присваиваем переменной, значение делим на 2. А потом выборка по лимиту:
select 50 percent skills / stage from personal order by skills / stage limit 0,переменная;


text:
Q: A group theoretic question involving derivatives Let $f: (\mathbb{R},+) \rightarrow (\mathbb{R_0},.)$ be a homomorphism which is differentiable as a function from $\mathbb{R} \to \mathbb{R}$
Show that:
a) $f(x) > 0 \quad\forall x \in \mathbb{R}$
b) $\exists a \in \mathbb{R}: f(x) = e^{ax} \quad \forall x \in \mathbb{R}$
For the first one, I think we can do the following:
$$f(x) = f\left(\frac{x}{2}+\frac{x}{2}\right) = \left(f\left(\frac{x}{2}\right)\right)^2 >0$$
Is this correct?
For the second one, can anyone give me a hint? I do not know how to implement the differentiability. I tried $$f'(x) = f'(x/2)$$ by using the chain rule on the expression above. I must somehow be able to show that $f'(x) = af(x)$, since then I can write $f(x) = e^{ax}$
Thanks in advance.

A: It is easy to see that $f(0)=1$ (identity to identity).
\begin{align*}
f^{'}(x) & = \lim_{h \to 0} \frac{f(x+h)-f(x)}{h}\\
& = \lim_{h \to 0} \frac{f(x) \cdot f(h)-f(x)}{h}\\
& = f(x)\lim_{h \to 0} \frac{f(h)-1}{h}\\
& = f(x) \, f^{'}(0)
\end{align*}
Now let $f^{'}(0)=a$. Solve the differential equation
$$f^{'}(x) = af(x).$$


text:
Q: SQL query to find table which contain specific data In am testing a application which is created using asp.net and sql server 2005.
In a form I enter a value as 'hungry minds' for a publisher field. but when i dont know in which table it is stored. Is there any query to find the table which contain the data 'Hungry minds'

A: set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create PROC [dbo].[SearchAllTables]
(
    @SearchStr nvarchar(100)
)
AS
BEGIN

--exec SearchAllTables 'sdsd'

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM    INFORMATION_SCHEMA.TABLES
            WHERE       TABLE_TYPE = 'BASE TABLE'
                AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) >
@TableName
                AND OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME
(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND TABLE_NAME  = PARSENAME(@TableName, 1)
                    AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar','ntext')
                    AND QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(Cast(' +
@ColumnName + ' AS NVARCHAR(Max)), 3630)
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE Cast(' + @ColumnName + ' AS NVARCHAR(Max)) LIKE ' +
@SearchStr2
                )
            END
        END
    END

    SELECT ColumnName, ColumnValue FROM #Results
END

A: No, not without some trickery. You're generally expected to know the details of your schema.
What you can do is to write a script of some sort to query system tables to construct queries for finding it.
By that I mean most DBMS' have system tables which contain database metadata like table names and column names. For example, DB2/z has SYSIBM.SYSTABLES and SYSIBM.SYSCOLUMNS.
I'm not sure what the SQLServer equivalents are off the top of my head since, as mentioned, I generally know the details of my schema :-)
You can use these tables to construct queries for querying the "real" tables.


text:
Q: Book(s): Space Opera - Young Man becomes Captain, Homemade AI becomes Real Girl I believe I read this either in the late 1990's or early 2000's. I may have stumbled across it as an online story (similar to how "John Dies at the End" was originally posted online), but I remember liking it so much I bought additional titles (chapters?) in the series / story.
Things that I remember:

*

*Hero/Captain starts out as a kid and built his own artificial intelligence/assistant program. She is smart and sassy, and aids him in winning some sort of contest or war game.

*Hero becomes young officer on a crew. During an early battle everyone senior to him is killed, and he becomes captain.- Ship is lost and on it's own deep in space, and he fights a number of heroic battles. Earns the love of the crew.

*At some point, he is on a rescue(?) mission on another ship and his lady AI sacrifices herself to save him. He thinks she's dead, but in reality she loads herself into a real human body and escapes.

*In a subsequent chapter/book, she's in her own ship still looking for him. She's built her own male AI, and has purchased access to some sort of galactic TV where she can watch some 100 billion channels and shows.

I know that's pretty thin, but I've been trying to rediscover this one for several years. By chance, does anyone else recognize it?

A: It's a stretch, but some elements remind me of the Spinward Fringe series by Randolph Lalonde; there are some differences in places as well though. Looks like the first stories came out in 2008 so a bit more recent than you recall. Indie publishing, at least initially, and the first book is free to download on Amazon so reading that one for free and then buying later parts would potentially fit.
Lead character is Jonas Valent. He's an adult at the start of the novel, left the the military a few years beforehand, but is using military simulations for recreation and outperforms the actual trainees and officers. He gets reinstated and bumped direct to captain on a long-range scout mission without contact with his home. Fairly typical for the type of story, he performs well and is hugely popular despite a lack of training or experience for the role.
He has a computer/AI called Alice; she's noted to have been with him and modified since he was young, and far more capable and self-aware than usual. In one of the sequels she is released into a ships computer after he is captured and helps him escape, and he thinks she's been left behind when the ship is destroyed. She is downloaded into a human body, manages to escape herself, and eventually ends up finding him and becoming a surrogate daughter.
Not sure about the male AI or galactic TV - the series is up to double figures and I lost track of the later plot details.


text:
Q: Upgrade a Windows UAP app from Windows 8.1 Silverlight Phone I have a Windows 10 app that is intended to replace and older Windows Windows Phone 8.1 Silverlight app. So if the previous app is already installed and is updated from the store, the new Win 10 uap app will replace it. However, I want to keep some of the Application Settings properties from the Silverlight app and transfer them over to the Windows 10.
My idea was that, when starting the Win 10 app for the first time, I would check for the application settings file that was from the previous 8.1 silverlight and read the desired properties.
I changed my AppxManifest file in the Win 10 app to use same Publisher Id, PhoneProductId and PhonePublisher id as the Silverlight. However, when I run the Win 10 app I get a prompt that my previous silverlight app will be uninstalled first (and hence I would lose the application settings file). Is there a proper way to upgrade from Silverlight 8.1 to Win 10 universal without losing the file?

A: Update the Silverlight App to migrate user settings from Local to Roaming. Even when the Silverlight App gets deleted the user settings will persist in the cloud for a month or so. Because the UWP will use the same App ID these settings will be available for the UWP app.


text:
Q: DecodeError: Error parsing message with type 'tensorflow.GraphDef' - while saving tensorflow retrieval model I am trying to load weights from an epoch checkpoint while training a Tensorflow Recommenders Deep Retrieval model and then save the model.
When trying to save the model, it gives the following error:
[libprotobuf ERROR google/protobuf/wire_format_lite.cc:581] String field 'tensorflow.TensorShapeProto.Dim.name' contains invalid UTF-8 data when parsing a protocol buffer. Use the 'bytes' type if you intend to send raw bytes.
---------------------------------------------------------------------------
DecodeError                               Traceback (most recent call last)
/tmp/ipykernel_8016/3029885622.py in <module>
      1 brute_model.save(destination_path)

/opt/conda/lib/python3.7/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in _as_graph_def(self, from_version, add_shapes)
   3525           data = pywrap_tf_session.TF_GetBuffer(buf)
   3526       graph = graph_pb2.GraphDef()
-> 3527       graph.ParseFromString(compat.as_bytes(data))
   3528       # Strip the experimental library field iff it's empty.
   3529       if not graph.library.function:

DecodeError: Error parsing message with type 'tensorflow.GraphDef'

Here, brute_model is the index generated by tfrs.layers.factorized_top_k.BruteForce(query_model).index_from_dataset(tf.data.Dataset.zip((unique_labels.batch(50), unique_labels.batch(50).map(candidate_model))))


text:
Q: JavaScript Express returning empty JSON Folks,
  I have a function that creates an Object that I would like to return back to the browser.  For some reason, the browser is getting an empty Object without the contents:
{
    pName: [ ]
}

Here is the object via console.log(require('util').inspect(projectObject, false, 10));
{ pName:
    [ foo:
        [ nodejs:
            [ staging:
                [
                    { name: 'i-4a14c51a', id: 'i-4a14c51a' },
                    { name: 'i-19fc094a', id: 'i-19fc094a' },
                ],
              production:
                [
                    { name: 'i-5f14c50f', id: 'i-5f14c50f' },
                    { name: 'i-b1fb0ee2', id: 'i-b1fb0ee2' },
                ]
            ]
       ],
...

I would imagine the reason its not returning the object is because it thinks that the first entity is empty.
Where am I making the mistake? The result needs to look liks:
"hosts": [
{
  "projectA": [
     {
       "foo": [
          {
            "nodejs": [
          {
        "production": [
                       {
                         "name": "Her blog",
                         "cmd": "ssh username@blog2.example.com"
                       }
                    ]
                  }
                ]
              }
            ]
           }
        ]
     },
  ]

A: I believe your problem is here:
{ pName:
    [ foo: // <-- invalid JSON
        [ nodejs:
            [ staging:
...

If that's the output of an inspector I'd have a look at exactly how the projectObject is being constructed (are you creating an array and then assigning something to a property on it? In which case create an object instead).
I'm afraid I'm not sure how I'm expected to get to the requested result with the information available however.


text:
Q: inline-block breaks with many children If I create a container div and then some div children (say three), and set the parent to display: inline-block, I get something like this jsfiddle-good

CSS
#container {
    border: 1px solid blue;
    padding: 2px;
    display: inline-block;
}

.child {
    width: 100px;
    border: 1px solid black;
    float: left;
    margin: 2px;
}

HTML

child 1

child 2

child 3

That's good! I want that. The problem arises when I have many children (say 30) jsfiddle-bad

Why is that white-space spearing, and how do I get the container div to size down properly?

A: that space was there because the boxes could not fit in that space so I just added 10 to the width and no more space. here is a link to the code if need be:
http://jsfiddle.net/AnDrewpa18/t5Nth/
HTML

child 1

child 2

child 3

child 1

child 2

child 3

child 1

child 2

child 3

child 1

child 2

child 3

child 1

child 2

child 3

child 2

child 2

child 2

child 2

child 2

child 2

CSS
#container {
    border: 1px solid blue;
    padding: 2px;
    display: inline-block;
}
.child {
    width: 110px;
    border: 1px solid black;
    float: left;
    margin: 2px;
}


text:
Q: Random serialization exceptions using Socket I'm trying to send data back and forth between only two computers using a Socket. The data is in the form of serialized Packet objects.
When testing the program on another computer on my local network, I'm getting random SerializationExceptions so that no data goes through.
The program consistently sends different data, so when it makes another pass at sending it again, it will sometimes go through and sometimes hit the same SerializationException again. If I catch the exception and leave it running, all data eventually makes it through, but it takes several tries.
The exception says: "The input stream is not a valid binary format. The starting contents (in bytes) are [byte data]"
Not sure exactly where my problem lies. The larger amounts of data I send (~100kb max) always go through. The smaller ones (50-70 bytes) have trouble. Here's everything to do with my serialization and reading/writing data.
Socket defined as such:
SocketMain = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Send & Read methods. I'm aware this is probably a horrible way to do so and might end up being my issue. Suggestions?:
    public void SendPacket(Packet P)
    {
            using (MemoryStream MS = new MemoryStream())
            {
                BinaryFormatter BF = new BinaryFormatter();
                BF.Serialize(MS, P);
                SocketMain.Send(MS.ToArray());
            }
    }

    public void ReadPacket()
    {
        byte[] BufferArray = new byte[131072];
        int BytesReceived = SocketMain.Receive(BufferArray);

        byte[] ActualData = new byte[BytesReceived];
        Buffer.BlockCopy(BufferArray, 0, ActualData, 0, BytesReceived);

        using (MemoryStream MS = new MemoryStream(ActualData))
        {
            BinaryFormatter BF = new BinaryFormatter();
            HandlePacket((Packet)BF.Deserialize(MS));
        }
    }

Example Packet object. This is one of my smaller ones. I think this might be the one that is causing the issue, but I don't know how I could tell.
[Serializable()]
public class Packet4BlockVerify : Packet, ISerializable
{
    public byte Index;
    public string MD5Hash;

    public Packet4BlockVerify(int Index, string MD5Hash): base(4)
    {
        this.Index = (byte)Index;
        this.MD5Hash = MD5Hash;
    }

    protected Packet4BlockVerify(SerializationInfo info, StreamingContext context)
    {
        this.ID = info.GetByte("ID");
        this.Index = info.GetByte("Index");
        this.MD5Hash = info.GetString("MD5Hash");
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("ID", this.ID);
        info.AddValue("Index", this.Index);
        info.AddValue("MD5Hash", this.MD5Hash);
    }
}

Does anyone see anything wrong?

A: You are not reading  all the bytes you sent. Your receive call:
int BytesReceived = SocketMain.Receive(BufferArray);

returns any number of bytes. You will need to pre-pend the bytes you send with the size of the remaining bytes, read that then continue reading till you have all your bytes before trying to deserialize.
TCP sends a continuous byte stream so your receive call reads arbitrary sized chunks. One of the overloads you can specify the number of bytes you want to receive so after reading the number bytes you are expecting you could use that. e.g.
// Warning untested! (but you get the idea)

// when sending
var payload = MS.ToArray();
var payloadSize = payload.Length;
mySocket.Send(BitConverter.GetBytes(payloadSize));
mySocket.Send(payload);

// when recieving
mySocket.Recieve(myBuffer, sizeof(int), SocketFlags.None);
var payloadSize = BitConverter.ToInt32(myBuffer, 0);
mySocket.Recieve(myBuffer, payloadSize, SocketFlags.None);
// now myBuffer from index 0 - payloadSize contains the payload you sent


text:
Q: Cross compile for specific CXXABI and GLIBCXX version I wanna cross compile a software for an ARM target running on Linaro 14.04.
When I cross compile from my Ubuntu 18.04 using arm-linux-gnueabihf-g++, and I try to run it on target, I obtain this error :

./main: /usr/lib/arm-linux-gnueabihf/libstdc++.so.6: version
  `CXXABI_1.3.9' not found (required by ./main)
./main: /usr/lib/arm-linux-gnueabihf/libstdc++.so.6: version `GLIBCXX_3.4.21'
  not found (required by ./main)

My problem is that I can't upgrade any library on target.
So my question is, can I specify a specific version of GLIBC and CABI at the compilation time ?
Thanks a lot

A: You'll need to find a compiler of the same version as the target's libstdc++ was part of.
These ABI versions sometimes (not always) increase when new symbols are added to libstdc++.
Your best bet is in any case always to install the same OS version on your build machine. That is guaranteed to have the same toolchain version (although cross-compilers might differ there slightly).
Old answer follows. There is no package for GCC-4 so you'll have to install an older Ubuntu version.

It seems Ubuntu 18.04 has several GCC versions:
https://packages.ubuntu.com/search?keywords=arm-linux-gnueabihf&searchon=names&suite=bionic&section=all
I'd try the newest one that works for your target. You can also compare the so version of libstdc++.so.X.Y.Z and make sure you use a GCC version with libstdc++ so version of maximum the one on your target machine.
If you're curious, the file defining these symbol versions can be found here: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/config/abi/pre/gnu.ver.
Looking further in that file, I found this commit: https://github.com/gcc-mirror/gcc/commit/c19175577e1cbf749590889441ad5dd03bb2c9d7
It adds the version of symbols you are missing, and Github marks this as being present in GCC 5. Unfortunately, Ubuntu 18.04 does not have a pre-5 GCC toolchain.


text:
Q: Redirect links in S3 static website hosting to new URL without .html ending I am prettifying my URLs to remove the .html at the end of my links. So far, so good, I don't need help with that. I am trying to provide a redirect, in case someone has an old link with the .html still present. So I want to redirect:
example.com/articles/dmg-me.html
to
example.com/articles/dmg-me

I have put in the following as a redirection rule in my S3 bucket but it does not work.
<RoutingRules>
  <RoutingRule>
    <Condition>
      <KeyPrefixEquals>.html</KeyPrefixEquals>
    </Condition>
    <Redirect>
      <HostName>gameboyessentials.com</HostName>
      <ReplaceKeyPrefixWith></ReplaceKeyPrefixWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>

I have other redirects in that same XML file who do work.


text:
Q: How to insert merged row as first column in verticle text format I am using the code below and the pdf output. I want Tested on as vertical text from IEMOCAP to CREMA. Also Trained on from  IEMOCAP to CREMA with alone below it. How to do that?
Please suggest something to make this table more professional like can I change something to the fonts and size?
\documentclass[12pt]{report}
\usepackage{booktabs,siunitx}
\usepackage{multirow}

\usepackage{rotating, makecell}
\begin{document}

\begin{table*}[ht]
    \caption{Cross-Corpus performance of the proposed method on four datasets}
    \label{cross}
    \setlength\tabcolsep{0pt}
    \begin{tabular*}{\linewidth}{@{\extracolsep{\fill}} ll cccc }

        \toprule
        \multicolumn{6}{c}{Trained On}\\
        &Dataset & IEMOCAP & EmoDB & RAVDESS & CREMA\\
        \midrule

        \multirow{7}{*}{\rothead{Tested On}}&IEMOCAP && &&\\
        &EmoDB & &&&  \\
        &RAVDESS & &&&  \\
        &CREMA   & &&& \\
        \midrule[\heavyrulewidth]
        &Average & &&&  \\
        \bottomrule

        %\multicolumn{11}{l}{M:Male; F:Female}
    \end{tabular*}

\end{table*}

\end{document}

The output is shown below:

A: *

*Your question is not entirely clear and also ask for opinion based suggestions ...

*In the first step I limited myself to correct code wo, that it will work properly:

\documentclass[12pt, twocolumn]{report}
\usepackage{booktabs, makecell, multirow}
\usepackage{rotating}
\usepackage{siunitx}
\usepackage[skip=1ex]{caption}

\begin{document}
\begin{table*}[ht]
    \caption{Cross-Corpus performance of the proposed method on four datasets}
    \label{cross}
    \setlength\tabcolsep{0pt}
    \settowidth\rotheadsize{Tested On}
    \begin{tabular*}{\linewidth}{@{\extracolsep{\fill}} ll cccc }
        \toprule
        &           &   \multicolumn{4}{c}{Trained On}          \\
        \cmidrule{3-6}
        &  Dataset  & IEMOCAP   & EmoDB & RAVDESS   & CREMA     \\
        \midrule
\multirow{4}{*}[1ex]{\rothead{Tested On}}
        & IEMOCAP   &           &       &           &           \\
        & EmoDB     &           &       &           &           \\
        & RAVDESS   &           &       &           &           \\
        & CREMA     &           &       &           &           \\
        \midrule
        & Average   &           &       &           &           \\
        \bottomrule
    \end{tabular*}
\end{table*}
\end{document}

*

*For further help you need to provide content for least on table body row. The best this one, where the cells contents are the longest.

*Usually help, if you read packages documentation or make yourself more familiar with writing of tables by reading some introductory text. For example wiki: tables.


text:
Q: SetTint of UIButton won't hold I'm loading the image of UIButton via web as:
NSURL *imageURL = [NSURL URLWithString:[ruleImageArr objectAtIndex:0]];
NSData *data = [NSData dataWithContentsOfURL:imageURL];
[self.classicBackgroundButton setImage:image forState:(UIControlStateNormal)];

Which is working fine. So when user taps on it I want the button to setTint. Here is how I'm doing it:
- (IBAction)classicBackgroundButtonPressed:(id)sender {
    [self.classicBackgroundButton setTintColor:[UIColor greenColor]];
}

But it's not working. Can't seems to figure out whee the problem is?
I've searched it around on stackOverFlow but its mostly how I can replace the UIButton image on tap. These images are loading from web and selecting them should highlight them to give a feel that this button is selected. Any Help would be apperciated.

A: UiImage must have template rendering mode in order to work with tint. Something like this:
UIImage *imageTint = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[button setImage:imageTint forState:UIControlStateNormal];

A: you could use another UIControlState to manage this.
NSURL *imageURL = [NSURL URLWithString:[ruleImageArr objectAtIndex:0]];
NSData *data = [NSData dataWithContentsOfURL:imageURL];
[self.classicBackgroundButton setImage:image forState:(UIControlStateSelected)];
[self.classicBackgroundButton setImage:image forState:(UIControlStateHighlighted)];
[self.classicBackgroundButton setImage:image forState:(UIControlStateNormal)];

A: Use this instead
- (IBAction)classicBackgroundButtonPressed:(UIButton *)sender {

    [sender setTintColor:[UIColor greenColor]];
}


text:
Q: Upgraded to Mojave and now MacOS won't allow me to have the same password locally as my iCloud account I upgraded a new to me MacBook Pro (Mid 2015) to Mojave and the checkbox was pre-checked to use iCloud to unlock MacOS. This setting keeps me from having the same local and iCloud password.  How do I turn off this "feature"? Since the Mojave security update the checkbox to disable this "feature" is gone from the Change Password dialog in Users and Groups.

A: Apple is making it hard for you to reuse the password from the setup assistant only.

*

*Just enter a new password to get past this.

Then if you require them to be the same, go and immediately change the password in System Preferences. Apple doesn't store or check the passwords other than the initial setup, so you can reuse your passwords as much as you wish.
The only wrinkle I haven't tested lately is if you have enabled FileVault and iCloud escrows your FileVault unlock keys might still be entangled with your account password.

I was going to comment on your question, but it got too long for a comment and it is opinion, so I'll share that here after answering how to get around things as best I know.
As for your comment about moving to windows, you are correct - we all have to pick our poison. No commercial software fails to make design and security decisions like this one that they don't bend on.
If we were to delve into this - the question I have for anyone (and myself) is:

What's your use case for not having an iCloud password that's distinct from one Mac local admin password?

The security model in 2019 is using secure storage and long unique passwords to contain when a breach happens. Having a different password for cloud unifying - highly confidential and attackable information and a much shorter one you type day in and day out seems like a very reasonable baseline for everyone. Especially if you can take a second step and choose to unify both easily if you don't want to have two to remember.
On the other side - Imagine if Apple let the default setup keep the same password on iCloud and the Mac and your Mac FileVault backup was the same password you forgot. All your eggs are in one basket. I think they have had this happen and made the decision to inconvenience people in the name of having the discussion we are having (or I'm attempting to have) to raise the security of Mac users.
I get you might be momentarily inconvenienced or angry, but perhaps you'll reconsider after thinking through what the long term effects of implementing what used to be are for you and your community. Anyhow - I'll get off my soapbox and hope I didn't anger anyone with some opinion here.


text:
Q: How send multipart/fom-data with Volley and get a response in a JSON Object? I have a functionnal Android app send request with Volley and get response in JsonObject. Now, I need to include an image in my request and I don't have any idea how I can do that, and still receive my response in a JsonObject.
Thank you for helping.
Fabien.

A:         JsonMultipartRequest<Upload> request = new JsonMultipartRequest<Upload>(Method.POST, apiUrl, mListener, mErrorListener);

        request.addFile("photo", image_path);

        RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        mRequestQueue.addRequest(request);
        mRequestQueue.start();

JsonMulitpartRequest is extended class of MultipartRequest where Override the below method to make it JSON object parseNetworkResponse
This is using library VolleyPlus


text:
Q: R featurePlot returning NULL I am trying to run various types of featureplot (part of the caret library) on my data for visualisation/ understanding of distribution. However when I try to run many of the commands, the result is NULL.
> featurePlot(x=feat, y=lab, plot="density")
NULL

Where feat is a matrix of my features (all numeric) and lab a binary column of labels (numeric). I have been able to use the "pairs" command with success but for some reason unable to use "ellispe" or "density". Has anyone else encountered this problem?
Thanks

A: I guess you have to install the ellipse package.
> install.packages("ellipse")

Hope this will help.


text:
Q: PHP DateTime microseconds always returns 0 this code always returns 0 in PHP 5.2.5 for microseconds:
<?php
$dt = new DateTime();
echo $dt->format("Y-m-d\TH:i:s.u") . "\n";
?>

Output:
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:26.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:28.000000

Any ideas?

A: \DateTime::createFromFormat('U.u', microtime(true));

Will give you (at least on most systems):
object(DateTime)(
  'date' => '2015-03-09 17:27:39.456200',
  'timezone_type' => 3,
  'timezone' => 'Australia/Darwin'
)

But there is a loss of precision because of PHP float rounding. It's not truly microseconds.
Update
This is probably the best compromise of the createFromFormat() options, and provides full precision.
\DateTime::createFromFormat('0.u00 U', microtime());

gettimeofday()
More explicit, and maybe more robust. Solves the bug found by Xavi.
$time = gettimeofday();
\DateTime::createFromFormat('U.u', sprintf('%d.%06d', $time['sec'], $time['usec']));

A: Right, I'd like to clear this up once and for all.
An explanation of how to display the ISO 8601 format date & time in PHP with milliseconds and microseconds...
milliseconds or 'ms' have 4 digits after the decimal point e.g. 0.1234. microseconds or 'µs' have 7 digits after decimal. Seconds fractions/names explanation here
PHP's date() function does not behave entirely as expected with milliseconds or microseconds as it will only except an integer, as explained in the php date docs under format character 'u'.
Based on Lucky's comment idea (here), but with corrected PHP syntax and properly handling seconds formatting (Lucky's code added an incorrect extra '0' after the seconds)
These also eliminate race conditions and correctly formats the seconds.
PHP Date with milliseconds
Working Equivalent of date('Y-m-d H:i:s').".$milliseconds";
list($sec, $usec) = explode('.', microtime(true));
echo date('Y-m-d H:i:s.', $sec) . $usec;

Output = 2016-07-12 16:27:08.5675
PHP Date with microseconds
Working Equivalent of date('Y-m-d H:i:s').".$microseconds"; or date('Y-m-d H:i:s.u') if the date function behaved as expected with microseconds/microtime()/'u'
list($usec, $sec) = explode(' ', microtime());
echo date('Y-m-d H:i:s', $sec) . substr($usec, 1);

Output = 2016-07-12 16:27:08.56752900

A: This has worked for me and is a simple three-liner:
function udate($format='Y-m-d H:i:s.', $microtime=NULL) {
    if(NULL === $microtime) $microtime = microtime();
    list($microseconds,$unix_time) = explode(' ', $microtime);
    return date($format,$unix_time) . array_pop(explode('.',$microseconds));
}

This, by default (no params supplied) will return a string in this format for the current microsecond it was called:

YYYY-MM-DD HH:MM:SS.UUUUUUUU

An even simpler/faster one (albeit, with only half the precision) would be as follows:
function udate($format='Y-m-d H:i:s.', $microtime=NULL) {
    if(NULL === $microtime) $microtime = microtime(true);
    list($unix_time,$microseconds) = explode('.', $microtime);
    return date($format,$unix_time) . $microseconds;
}

This one would print out in the following format:

YYYY-MM-DD HH:MM:SS.UUUU

A: This seems to work, although it seems illogical that http://us.php.net/date documents the microsecond specifier yet doesn't really support it:
function getTimestamp()
{
        return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
}

A: You can specify that your input contains microseconds when constructing a DateTime object, and use microtime(true) directly as the input.
Unfortunately, this will fail if you hit an exact second, because there will be no . in the microtime output; so use sprintf to force it to contain a .0 in that case:
date_create_from_format(
    'U.u', sprintf('%.f', microtime(true))
)->format('Y-m-d\TH:i:s.uO');

Or equivalently (more OO-style)
DateTime::createFromFormat(
    'U.u', sprintf('%.f', microtime(true))
)->format('Y-m-d\TH:i:s.uO');

A: This function pulled from http://us3.php.net/date
function udate($format, $utimestamp = null)
{
    if (is_null($utimestamp))
        $utimestamp = microtime(true);

    $timestamp = floor($utimestamp);
    $milliseconds = round(($utimestamp - $timestamp) * 1000000);

    return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}

echo udate('H:i:s.u'); // 19:40:56.78128

Very screwy you have to implement this function to get "u" to work... :\

A: Try this and it shows micro seconds:
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );

print $d->format("Y-m-d H:i:s.u");

A: date_create

time: String in a format accepted by strtotime(), defaults to "now".

strtotime

time: The string to parse, according to the GNU » Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.

A: Working from Lucky's comment and this feature request in the PHP bug database, I use something like this:
class ExtendedDateTime extends DateTime {
    /**
     * Returns new DateTime object.  Adds microtime for "now" dates
     * @param string $sTime
     * @param DateTimeZone $oTimeZone
     */
    public function __construct($sTime = 'now', DateTimeZone $oTimeZone = NULL) {
        // check that constructor is called as current date/time
        if (strtotime($sTime) == time()) {
            $aMicrotime = explode(' ', microtime());
            $sTime = date('Y-m-d H:i:s.' . $aMicrotime[0] * 1000000, $aMicrotime[1]);
        }

        // DateTime throws an Exception with a null TimeZone
        if ($oTimeZone instanceof DateTimeZone) {
            parent::__construct($sTime, $oTimeZone);
        } else {
            parent::__construct($sTime);
        }
    }
}

$oDate = new ExtendedDateTime();
echo $oDate->format('Y-m-d G:i:s.u');

Output:
2010-12-01 18:12:10.146625

A: How about this?
$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Sample Output

2013-07-17 08:23:37:0.88862400

A: This should be the most flexible and precise:
function udate($format, $timestamp=null) {
    if (!isset($timestamp)) $timestamp = microtime();
    // microtime(true)
    if (count($t = explode(" ", $timestamp)) == 1) {
        list($timestamp, $usec) = explode(".", $timestamp);
        $usec = "." . $usec;
    }
    // microtime (much more precise)
    else {
        $usec = $t[0];
        $timestamp = $t[1];
    }
    // 7 decimal places for "u" is maximum
    $date = new DateTime(date('Y-m-d H:i:s' . substr(sprintf('%.7f', $usec), 1), $timestamp));
    return $date->format($format);
}
echo udate("Y-m-d\TH:i:s.u") . "\n";
echo udate("Y-m-d\TH:i:s.u", microtime(true)) . "\n";
echo udate("Y-m-d\TH:i:s.u", microtime()) . "\n";
/* returns:
2015-02-14T14:10:30.472647
2015-02-14T14:10:30.472700
2015-02-14T14:10:30.472749
*/

A: String in a format accepted by strtotime()
It work!

A: Inside of an application I am writing I have the need to set/display microtime on DateTime objects.  It seems the only way to get the DateTime object to recognize microseconds is to initialize it with the time in format of "YYYY-MM-DD HH:MM:SS.uuuuuu".  The space in between the date and time portions can also be a "T" as is usual in ISO8601 format.
The following function returns a DateTime object initialized to the local timezone (code can be modified as needed of course to suit individual needs):
// Return DateTime object including microtime for "now"
function dto_now()
{
    list($usec, $sec) = explode(' ', microtime());
    $usec = substr($usec, 2, 6);
    $datetime_now = date('Y-m-d H:i:s\.', $sec).$usec;
    return new DateTime($datetime_now, new DateTimeZone(date_default_timezone_get()));
}

A: PHP documentation clearly says "Note that date() will always generate 000000 since it takes an integer parameter...". If you want a quick replacement for date() function use below function:
function date_with_micro($format, $timestamp = null) {
    if (is_null($timestamp) || $timestamp === false) {
        $timestamp = microtime(true);
    }
    $timestamp_int = (int) floor($timestamp);
    $microseconds = (int) round(($timestamp - floor($timestamp)) * 1000000.0, 0);
    $format_with_micro = str_replace("u", $microseconds, $format);
    return date($format_with_micro, $timestamp_int);
}

(available as gist here: date_with_micro.php)

A: Building on Lucky's comment, I wrote a simple way to store messages on the server. In the past I've used hashes and increments to get unique file names, but the date with micro-seconds works well for this application.
// Create a unique message ID using the time and microseconds
    list($usec, $sec) = explode(" ", microtime());
    $messageID = date("Y-m-d H:i:s ", $sec) . substr($usec, 2, 8);
    $fname = "./Messages/$messageID";

    $fp = fopen($fname, 'w');

This is the name of the output file:
2015-05-07 12:03:17 65468400

A: Some answers make use of several timestamps, which is conceptually wrong, and overlapping issues may occur: seconds from 21:15:05.999 combined by microseconds from 21:15:06.000 give 21:15:05.000.
Apparently the simplest is to use DateTime::createFromFormat() with U.u, but as stated in a comment, it fails if there are no microseconds.
So, I'm suggesting this code:
function udate($format, $time = null) {

    if (!$time) {
        $time = microtime(true);
    }

    // Avoid missing dot on full seconds: (string)42 and (string)42.000000 give '42'
    $time = number_format($time, 6, '.', '');

    return DateTime::createFromFormat('U.u', $time)->format($format);
}

A: date('u') is supported only from PHP 5.2. Your PHP may be older!

A: This method is safer than the accepted answer:
date('Y-m-d H:i:s.') . str_pad(substr((float)microtime(), 2), 6, '0', STR_PAD_LEFT)

Output:
2012-06-01 12:00:13.036613

Update: Not recommended (see comments)


text:
Q: Ubuntu 17.10 to 18.04 encrypted /home 1. What will happen when upgrading Ubuntu 17.10 with encrypted /home to Ubuntu 18.04?
Bionic Beaver Release Notes
Other base system changes since 16.04 LTS:
The installer no longer offers the encrypted home option using ecryptfs-utils. It is recommended to use full-disk encryption instead for this release.
Launchpad Bug #1756840
2. Will 18.04 be able to use encrypted  (ecryptfs) /home ?
edit: 3 is now a standalone Question

A: I did a trial install of 18.04 Beta Lubuntu on a system with an encrypted home.  This system has separate / and /home partitions, so I was doing a "Something Else" install, formatting and installing to /, and not touching /home.
Every other time I've done this (with older versions of the installer) on the screen where you put in your username, at the bottom 3 options appeared, one of which was "encrypt your home directory" or words to that effect.  This option was always ticked and grayed out (because the installer knew that the home directory was encrypted).  This didn't happen this install - the option was not offered at all- and when the install was complete, I couldn't log in.
To fix this, I had to reboot, switch to a terminal login (Ctrl+Alt+F1), and install ecryptfs-utils.  Another reboot and I could log in.
There was another user on the same PC with a different encrypted home. I could never manage to log in that account.  I finally deleted the user, re-added them with encrypted home, and reloaded their home directory from backup.
This was all quite a hassle and I probably won't be encrypting home directories any more.

A: It is not offered as a default option. It is still supported, and ecryptfs is available. You can't set it up during normal install.
It will be possible to use old /home folders encrypted with ecryptfs, and you can manually create new.
As always, a good backup is recommended, especially when upgrading a system..


text:
Q: MongoDB aggregation: How to flatten an object? I have the following document:
{
  value: {
   a: 1,
   b: 'yellow',
   c: {'foo': 'baz'}
  }
}

How can I transform it to
{
   a: 1,
   b: 'yellow',
   c: {'foo': 'baz'}
}

Note: I don't want to project each and every field manually. I'm looking for an automatic way to do it
Thanks!

A: I think you are looking for $replaceRoot. Try this playground.
 {
    "$replaceRoot": {
      "newRoot": "$value"
    }
  }

More info in docs.


text:
Q: 'DoCmd.TransferSpreadsheet' to export to Excel I need to EXPORT an access table from ACCESS to EXCEL. There are 618499 rows. I tried simple method: right-click - export - excel. It worked only when I choose export with format (without format created blank excel document), but it is not convenient because I'll have to create 10 documents. I tried to use this code but it became red and did not work:
DoCmd.TransferSpreadsheet(
    [acExport],
    [acSpreadsheetTypeExcel12Xml],
    [tab_1],
    ["C:\Users\admin\Desktop\import_2014\final.xlsx"],
    [True])

*

*What should I change in it?

*How should I type it in a module.

*Or maybe you can offer another simple solution.

A: All VBA code must be in a sub or function, that is in a module.
Get rid of all those [], and if you want to put each parameter into a new line, use the line concatenation symbol _
DoCmd.TransferSpreadsheet _
    acExport, _
    acSpreadsheetTypeExcel12Xml, _
    "tab_1", _
    "C:\Users\admin\Desktop\import_2014\final.xlsx", _
    True

EDIT
Either use Call:
Call DoCmd.TransferSpreadsheet(acExport, acSpreadsheetTypeExcel12Xml, _
    "tab_1", "C:\Users\admin\Desktop\import_2014\final.xlsx", True)

or omit the parentheses:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
    "tab_1", "C:\Users\admin\Desktop\import_2014\final.xlsx", True


text:
Q: send post json request using volley response is not getting properly I am using volley to send a post json request in that I am passing json object request am not getting any response properly.i dint found which place has issue.The parameter i have send is correct one.but the response is not coming.kindly send positive feedback.
 Request:     {"first_name":"abdul","confirm_password":"nbnbnbnb","phone":"684888444","email":"dhjs@kjf.in","last_name":"sdfhj","devicetype":"1","devicetoken":"1","country_code":"+91","password":"nbnbnbnb","deviceid":"1"}

signurl=Utils.url+"mobileapi115/customerRegistration/dGF4aV9hbGw=/";
        signurl = signurl.trim().replaceAll("\\s+", "");
        System.out.println("reg" + signurl);
 try {

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("first_name",Fname.getText().toString().trim());
            jsonObject.put("last_name",lname.getText().toString().trim());
            jsonObject.put("email",email.getText().toString().trim());
            jsonObject.put("phone",phone.getText().toString().trim());
            jsonObject.put("password",pass.getText().toString().trim());
            jsonObject.put("confirm_password",cpass.getText().toString().trim());
            jsonObject.put("deviceid","1");
            jsonObject.put("devicetoken", "1");
            jsonObject.put("devicetype", "1");
            jsonObject.put("country_code","+91");

            String obj=jsonObject.toString();

            Log.e("params", obj + "");

            queue = Volley.newRequestQueue(SignupActivity.this);

             JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, signurl, obj, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    try {
                        Log.e("mmm", " " + response.toString());
                        JSONObject info=response.getJSONObject("detail");
                        int status=response.getInt("status");
                        System.out.println("stat"+status);
                        if(status==200){
                            String status_description=response.getString("status_description");
                            Toast.makeText(SignupActivity.this,status_description,Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Log.e("TAG", "Response " + response.toString());
                }

            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                Log.e("err",""+volleyError.getMessage());
                }
            });
            System.out.println("req"+jsonObjectRequest);
            queue.add(jsonObjectRequest);

        } catch (JSONException e) {
              e.printStackTrace();

        }

}


text:
Q: Embeddings of Hirzebruch surfaces $\mathbb{P}(\mathcal{O}_{\mathbb{P}^1}\oplus\mathcal{O}_{\mathbb{P}^1}(n))$ Let $X_n=\mathbb{P}(\mathcal{O}_{\mathbb{P}^1}\oplus\mathcal{O}_{\mathbb{P}^1}(n))$ be the $n-$th Hirzebruch surface. We know that for $d>0$ and higher $k>>0$ the linear system $$\mathcal{L}_{d,k}=|\mathcal{O}_{X_n}(d)\otimes \pi^*\mathcal{O}_{\mathbb{P}^1}(k)|$$ is very ample, where $\pi:X_n \rightarrow \mathbb{P}^1$ is the projective bundle structure.
Does anybody know an explicit description of the embedding given by $\mathcal{L}_{d,k}$ in an affine patch $U_0 \subset X_n$, where for example $U_0=\mathbb{C}\times (\mathbb{P}^1\setminus [0,1])$ with coordinates $(x,y)$?
I mean an explicit description as in the case of a Veronese embedding, for example.


text:
Q: Text widget not showing full text when long text in the line its hide and showing ellipse In text widget when text overflowing not taking its given width and show ellipse.
issue it gets  hides long text and showing ellipse
I have some text long or in between  the text line so that I have wrap text widget with Expanded and changed the text widget property to overflow.ellipses . but long text gets hide and shows only ellipses
Any other way to show long text with ellipse inside the given width
not showing full text
Expanded(
child: Text(
                                  name ?? " ",
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 15),
                                 ),

Expected like this
I also tried changing softwrap=false  but no changes with ellipse

A: It happens when your text contains white space(that is simple space). If text-overflow is used then it will apply the text-overflow effect right after the white space of text which is so long that it would not fit in the first line.
Since white space is creating the problem we can simply replace white space with an invisible character which is blank space. There is a difference between white space and blank space. The Unicode of white space is \u0020 and the Unicode of blank space is \u00A0.
You just have to use the string replaceAll method to replace white space with blank space : -
name.replaceAll(RegExp(' '), '\u00A0'),

Full code : -
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TextOverFlow',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: const TextOverFlow(),
    );
  }
}

class TextOverFlow extends StatefulWidget {
  const TextOverFlow({Key? key}) : super(key: key);
  @override
  // ignore: library_private_types_in_public_api
  _TextOverFlowState createState() => _TextOverFlowState();
}

class _TextOverFlowState extends State<TextOverFlow> {
  String name = "Dean Palmer Sophie Roberts ghifkkddffd";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("TextOverFlow"),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.only(right: 50, left: 50),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const CircleAvatar(
                  backgroundColor: Color.fromARGB(255, 196, 192, 192),
                  radius: 30,
                  child: Text(
                    'AR',
                    style: TextStyle(color: Colors.black, fontSize: 25),
                  ),
                ),
                const SizedBox(
                  width: 20,
                ),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        name.replaceAll(RegExp(' '), '\u00A0'),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style:
                            const TextStyle(color: Colors.black, fontSize: 20),
                      ),
                      const Text(
                        'textOveflow@gmail.com',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.black, fontSize: 20),
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  width: 30,
                ),
                const Icon(
                  Icons.call,
                  size: 35,
                )
              ],
            ),
          ),
        ));
  }
}

Output : -


text: Q: Python MySql : Where to put the MySql queries (design choice)? I'm writing a Python application that interacts with a MySql database. The basic way to do this is to connect to the database and execute the queries using the database's cursor object. Should I hardcode each query in the python code, or should I put each query in a stored procedure ? Which is the better design choice (keeping security and elegance in mind) ? Note that many of the queries are single-liners (select queries).


text:
Q: get/set C# Key Value pairs from JSON string (without JSON.NET) I had a working example parsing a JSON string in a KeyValue class.
For some reason now it is returning 0's and/or nulls.
public class KeyValue
{
        //example JSON string: {"SomeCoolPlayerName":{"id":32179899,"name":"SomeCoolPlayerName","profileIconId":547,"summonerLevel":30,"revisionDate":1396953413000}}
        public long id {get; set;}
        public string name {get; set;}
        public int profileIconId {get; set;}
        public long summonerLevel {get; set;}
        public long revisionDate {get; set;}

       // public List<int> champions {get; set;}
}

Could the JSON string have changed? It is getting populated when I debug I can see it so I added it as a comment above ^^
The web page code is pretty simple also:
    try
    {
        WebClient client = new WebClient();
        var strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" + SummonerName + "?api_key=blanked_on_purpose");
        JavaScriptSerializer ser = new JavaScriptSerializer();

        var KeyValue = ser.Deserialize<KeyValue>(strJSON);
        var summonerId = KeyValue.id;
        //var summonerLevel = KeyValue.summonerLevel;
        txtSummonerId.Text = summonerId.ToString();
    }

What must I do to get the summonerId correctly again?

A: In the JSON you gave, the id is not in the root object, but is nested under the name SomeCoolPlayerName. This can be represented by a dictionary pretty easily:
var strJSON = @"{""SomeCoolPlayerName"":{""id"":32179899,""name"":""SomeCoolPlayerName"",""profileIconId"":547,""summonerLevel"":30,""revisionDate"":1396953413000}}";
JavaScriptSerializer ser = new JavaScriptSerializer();

var dict = ser.Deserialize<Dictionary<string, KeyValue>>(strJSON);
// use this if you know the name
var summonerId = dict["SomeCoolPlayerName"].id; // 32179899
// or this if you know there's only one value in the dictionary
var summonerId = dict.Single().Value.id; // 32179899

A: Yes, the data has changed.  From the Change Announcement:

New API Version for Summoners
...
The response will be map of each summoner ID (or name) to the JSON object containing the requested summoner data.
...

You had to have changed the version number in your call to DownloadString().  It has been returning a Map since v1.3, and you are calling v1.4.  When API version numbers change, you should expect the response to change, and check the documentation to see if it has.
Now that your item is contained in a Map, you'll need to deserialize it to a Dictionary<string, KeyValue>.  According to the documentation, the key "is the summoner name in all lower case and with spaces removed".
string key = SummonerName.ToLower().Replace(" ", "");
var KeyValue = ser.Deserialize<Dictionary<string, KeyValue>>(strJSON)[key];

(Personally, I'd rename your KeyValue class to Summoner or SummonerDto to match the API.)


text:
Q: How to write jdbc inbound channel adapter programmatically to read data from DB and pass to output channel? I am new to spring integration and i want to write the below flow programmatically
I have below inbound channel adapter in which I query the DB and passing it to OutChannel
and from OutChannel to AccountOutputChannel. AccountOutputChannel has refernce of a class which calls onMessage when message is available on AccountOutputChannel
How can I do this all programmatically
<int-jdbc:inbound-channel-adapter id="jdbcInbound"
                                      channel="OutChannel"
                                      data-source="dataSource"
                                      query="SELECT * FROM Accounts"
                                      max-rows-per-poll="100"
                                      row-mapper="AccountRowMapper">
        <int:poller fixed-rate="1000"/>
    </int-jdbc:inbound-channel-adapter>

<int:channel id="OutChannel"/>

<int:bridge input-channel="OutChannel" output-channel="AccountOutputChannel"/>

<int:channel id="AccountOutputChannel">
   <int:dispatcher task-executor="executorPool"/>
</int:channel>

<int:service-activator input-channel="AccountOutputChannel" ref="AccountService" method="onMessage"/>

A: See similar question here: How to invoke Spring channel adapter from rest api?
The Inbound Channel Adapter is a thing by itself and it does its work via constant polling cycle. It just does not fit to your requirement.
Since you say you'd like to do something via REST call, then it is an event-driven by end-user action. Therefore you need to look into a <int-jdbc:outbound-gateway> instead which is going to receive a message via its input-channel and do some DB action and produce a reply for you.
See more in docs: https://docs.spring.io/spring-integration/reference/html/jdbc.html#jdbc-outbound-gateway.
In addition you may look into a @MessagingGateway contract to not deal with channels in your REST controller: https://docs.spring.io/spring-integration/reference/html/messaging-endpoints.html#gateway


text:
Q: JQuery Search / Filter listview bad Performance - manually trigger search I have implemented a JQuery listview and enabled the search within this list:

    City One

     Entry1

     Category

    City Two

     Entry1

     Category

...

The input field is provided by jquery automatically due to the data-filter attribute:
<input placeholder="Search" data-type="search" class="ui-input-text ui-body-c">

Unfortunately the performance on mobile devices - especially the older ones - is very very bad. There are about 300 Entries in the list and the keyboard input of the mobile device is lagging hard.
I would like to prevent this obvious lagging by adding a button and only start the search when the user tabbed this button. Atm the search is instantly, which means on every keyboard event.
Is there any way to achieve this or improve performance?


text: Q: Автоматическое скачивание файла на js Нужно сделать автоматическое скачивание файла при переходе на страницу, чтобы пользователь не нажимал "скачать". По типу перейти на главную страницу сайта и автоматическое скачивание пошло


text:
Q: how to use Group By in subquery select FirstName, LastName

from Customer AS A, Sale AS E

where A.CustomerID=E.CustomerID

AND group by sum(Total)

I keep coming up with an error, any help is much appreciated!

A: If you are wanting the sum(total) to appear in your outputted record set, it needs to be up in the SELECT portion of your query. Furthermore, your syntax is backwards. We put the fields that we want to group by in the GROUP BY, fields being aggregated using a function like sum, max, avg, etc go up in the SELECT. Lastly, the GROUP BY clause stands on it's own, the AND after your WHERE clause is not needed.
I believe you are wanting something like:
select FirstName, LastName, sum(total) as total_sum

from Customer AS A, Sale AS E

where A.CustomerID=E.CustomerID

GROUP BY FirstName, LastName


text:
Q: What is the most efficient way of merging [1,2] and [7,8] into [[1,7], [2,8]] Given 2 arrays [1,2] and [7,8] what is the most efficient way of merging that to form [[1,7], [2,8]]. I know we can do this:
a1 = [1,2], a2 = [7,8], a3=[];
for (var i=0; i<a1.length; i++) {
  a3.push([a1[i], a2[i]]);
}

I am dealing with a large array. So I want to see if there is a better way.

A: There is no way to do this faster than O(n) because every element must be touched once.

A: That is a good question!
First off, make sure that you assign a1,a2,a3 to the local scope via the var keyword, which it seems you forgot. Otherwise performance can suffer tremendously.
As for the code-performance comparison. You can test/see the results here:

pure JavaScript:
var a1 = [1, 2],
  a2 = [7, 8],
  a3 = [];
for (var i = 0; i < a1.length; i++) {
  a3.push([a1[i], a2[i]]);
}

JS/Native methods:
var a1 = [1, 2],
  a2 = [7, 8],
  a3 = [];
a3 = a1.map(function(e, i, a) {
  return [e, a2[i]]
})

Of course there are more possible implementations, but the point is that probably no other implementation can beat a for-loop and straightforward packing, in O(n)-time as kindly pointed out by Travis J.
Engine/Optimized: V8 JavaScript Engine via Chrome v29

A: You are basically searching for a function identical to Python's zip function, so check out the answers to an older SO question:
Javascript equivalent of Python's zip function

A: Nope, that's about as efficient as it gets.  It's running in O(n) time.  Really not much more you could ask.  If there's anything you could optimize, it would be transforming a1 into a map, but that's optimization for memory, and it sounds like you want to speed things up intstead.


text:
Q: Get view from url How do I get and call the view function assosiated with a given url?
I have a view performing some work and then (if all went well) passes on the request to another view (one of several possible) and returns the response rendered by this view.
Pseudocode:
class View1(view):
    def dispatch():
        do_common_tasks()
        if (foo):
            return render("template1")
        elif (bar):
            return url_to_view2.render()
        else:
            return url_to_view3.render()

Is this a valid approach?

A: You can use the resolve function to resolve a url path to a view. You would then call the function with the request object.
func, args, kwargs = resolve('/some/path/')
return func(request, *args, **kwargs)

Note that resolve may raise Resolver404.