text:
Q: Java SQL Many to Many relationship I have a table in MySQL called Orders with the details of the order.
I have another table that is called OrderItems.
OrderItems contains the fields: OrderID, ProductID, Qty
Now in java I have a class called Order which has a List.
Lets say I want to get all the Orders from my database including the OrderItems per Order. But I want to do it in the most efficient way possible.
My current solution(which I think might be slow) is:
Loop through a ResultSet of rows and define the OrderDetails, everytime I loop through a row I execute another PreparedStatement and loop through the OrderItems with OrderID of the current Order. I then add the items in the List and go to the next order.
But I can imagine that this process will be extremely slow and resource intensive. What are the most efficient ways to do this while still being normalized(3NF).
As per request I have written up an example of my solution
public List<Order> getAllOrders() throws SQLException{
    ArrayList<Order> list = new ArrayList<Order>(0);
    ResultSet x = qry("Select * from Orders");
    while(x.next()){
        Order r = new Order();
        //setOrderDetails
        r.setItems(getOrderItems(r));
    }
    return list;
}
public ArrayList<OrderItem> getOrderItems(Order r) throws SQLException {
    ArrayList<OrderItem> list = new ArrayList<OrderItem>(0);
    ResultSet x = qry("Select * from OrderItems where OrderID = "+r.getId()+";");
    while(x.next()){
        OrderItem  newItem = new OrderItem();
        newItem.setOrderId(r.getId());
        newItem.setProduct(null); //Uses some kind of inner join to get the product details
        newItem.setPrice(newItem.getProduct().getPrice());
        newItem.setQuantity(x.getInt(4));
    }
    return list;
}

Okay I have followed you guys' suggestions... It still takes on average more than 20 secondsHow it looks
Log:
Time took to connect: 3270ms
Start CustomerService: 38ms
Start ProductService: 1ms
Start OrderService: 2ms
Customer Size: 4
Qry All Customers: 149ms
Products Size: 420
Qry All Products: 391ms
Order already contains: ENALAPRILMALEAAT HCT 20/12,5MG ACTAVIS BV
Add Order(28 items) Took: 2350ms
Qry all orders(27 orders) took: 7929ms

This is really hard... it can take up to 20 seconds sometimes.(to qry all orders)
Here is another one still clocking 30 seconds to qry only 28 orders..(all with max 28 items each

Time took to connect: 7117ms
Start CustomerService: 35ms
Start ProductService: 1ms
Start OrderService: 1ms
Customer Size: 4
Qry All Customers: 126ms
Products Size: 420
Qry All Products: 700ms
Add Order(6 items) Took: 2117ms
Qry all orders(28 orders) took: 30150ms

A: In my opinion, your data (600 products with 4 new order a week) are not so huge that you should need a performance optimization right now. But if you should, you could optimize it if your code looked like the following (I just modified your code a bit):
public List<Order> getAllOrders() throws SQLException{
   ArrayList<Order> list = new ArrayList<Order>(0);
   PreparedStatement ps = connection.prepareStatement("Select * from OrderItems where OrderID = ?");        // (1)
   ResultSet x = qry("Select * from Orders");
   while(x.next()){
       Order r = new Order();
       //setOrderDetails
       r.setItems(getOrderItems(r, ps));
       list.add(r);
   }

   return list;
}

public ArrayList<OrderItem> getOrderItems(Order r, PreparedStatement ps) throws SQLException {
    ArrayList<OrderItem> list = new ArrayList<OrderItem>(0);
    ps.setString(1, r.getId());       // (2)
    ResultSet x = ps.executeQuery();  // (3)
    while(x.next()){
        OrderItem  newItem = new OrderItem();
        newItem.setOrderId(r.getId());
        newItem.setProduct(null); //Uses some kind of inner join to get the product details
        newItem.setPrice(newItem.getProduct().getPrice());
        newItem.setQuantity(x.getInt(4));
    }
    return list;
}

What has changed now?

*

*The prepared statement is now out of the loop and it will be reused (see change (1)). This should bring a huge performance gain compared to the previous prepared query because the query will be parsed only once.

*In (2) the param will be set for the current order.

*In (3) the query will be executed.

A: It's a late answer, but for those who have slow query times.
Try to set auto commit to false. When you actually create the connection in the code,
do connection.setAutoCommit(false); and then in the code put connection.commit(); after executing the query. I had the same problem trying to insert 150000 objects, which took about 23 minutes. After setting auto commit to false and then committing, it took me about 27 seconds. I hope it helps.
Here is a code example of the committing:
@Override
public void create(Member member) {
    try {
        Connection connection = localConnection.getConnection();
        PreparedStatement sqlInsert = connection.prepareStatement(memberDaoUtil.create());

        sqlInsert.setString(1, member.getMemberId());
        sqlInsert.setString(2, member.getName());
        sqlInsert.setString(3, member.getPersonalNumber());
        sqlInsert.setString(4, member.getUsername());
        sqlInsert.setString(5, member.getPassword());
        sqlInsert.setInt(6, member.getNumOfBoats());
        sqlInsert.setBoolean(7, member.isAdmin());

        sqlInsert.executeUpdate();
        connection.commit();
        sqlInsert.close();

    } catch(SQLException ex) {
        ex.printStackTrace();
    }
}

Then also in the constructor of the connection:
private LocalConnection(Connection connection) {
    this.connection = connection;
    try {
        connection.setAutoCommit(false);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Which you can see connection.setAutoCommit(false);
You can read in the link below what it does.
Understand Auto Commit


text:
Q: Appcenter android build fails to install in device I have configured my react-native app in appcenter for build and distribution. Everything was working fine and all of a sudden, build failed with the following error
> Task :app:stripReleaseDebugSymbols FAILED
Support for ANDROID_NDK_HOME is deprecated and will be removed in the future. Use android.ndkVersion in build.gradle instead.

> Task :app:mergeExtDexRelease

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:stripReleaseDebugSymbols'.
> No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-androideabi

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Followed this link https://github.com/microsoft/appcenter/issues/2144 and updated my grade file to
buildscript {
    ext {
        ndkVersion = "20.1.5948944"
    }

    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
   }

and gradle-wrapper.properties to
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip

after this the build worked but the app distributed after the build failed to installed on devices with "App Not Installed" error. I tried different versions and no success so far.

A: I was able to fix the issue with the following settings
in graddle-wrapper.properties updated the distributionUrl to
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip

in android/build.gradle updated gradle version to
classpath("com.android.tools.build:gradle:4.2.0")

Updated react-native version to 0.65.1
npm i react-native@0.65.1

updated all related packages to be compatible with this react-native version
npm update "react-native"

after this, I was able to build it in appcenter and was able to distribute and install the app

A: Had a similar issue. After checking which ndk versions are supported in VSAC via looking at build logs I updated android/build.gradle with following ndk version & it worked.
buildscript {
    ext {
        ...
        ndkVersion = "18.1.5063045"
    }
    ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Algorithm Efficiency; Growth Function and Big-O Representation So here's the algorithm:
Algorithm pow (a, n):
Input: two integers, a (base) and n (exponent)
Output: returns the equivalent of a^n

K ←  n
b ←  1
c ←  a

while k > 0 do
    if k mod 2 = 0 then
        k ←  k / 2
        c ← c * c
    else
        k ←  k − 1
        b ← b * c
return b

The exact growth function I'm not sure of, but it looks like log(n) + C; where C = the number of times that 'else' branch is executed. Any help here would be awesome! I've racking my head over this for too long to be useful...

A: this looks like homework so i'll keep my answer brief.
I think you should try show that the else branch is entered less than or equal to the other branch (everytime you have an odd number k and subtract one from it , you get an even number). And then show that the first branch is log(n), and so the second branch must be less than or equal to log(n), and 2*log(n) is also log(n)...


text:
Q: Is it possible to get the value of a SharePoint column in the worflow without any reference to the other table? Is it possible to get the value of a SharePoint column in the worflow without any reference to the other table?
Here is my scenario...
List 1
Title
Status
Reminder 1 Date
Reminder 2 Date
Reminder 3 Date
Send Date

List 2
Title
Owner
Supervisor
Manager

My workflow is attached to List 1. When an item in List 1 is created the workflow triggers as follows
Pause until Reminder 1
If Status = Open
Send Email to Owner
Pause until Reminder 2
If Status = Open
Send Email to Supervisor
If Status = Open
Send Email to Manager
Else
Terminate Workflow
Else
Terminate Workflow
Else
Terminate Workflow

My "referencing" looks like this
Field Data to Retrieve
Data source: List 2
Field from source: Owner
Return field as: Email Address
Find the List Item
Field: Title
Value: List2:Title

My problem is, I get the "Coercion Failed: Unable to transform the input lookup data into the requested type."
I assume this is because both the titles of the lists have no relation.
How do I reference a column without the need of the "find the list" items.

A: In my opinoon the error is realted to the blank lookup value available for the workflow when it is trying to send the email.
I think the Owner, Supervisor and Manager are the the Person or Group fields and one of them or all of them are not having a value , if that is the case then the value is not readable for the sharepoint workflow and it will throw the same error you are getting right now.
Have a look at this link for more idea about this.
http://social.msdn.microsoft.com/Forums/sharepoint/en-US/ac6913c4-396b-4e7c-a42f-ee78656c7532/coercion-failed-unable-to-transform-the-input-lookup-data-into-the-requested-type
Please correct me if I am wrong or misunderstand your question.
Thanks


text:
Q: ImageView of Image height and width? I am using image view in my app. I use this code for setting the bitmap
  setImageBitmap(bitmap);

and imageview makes my bitmap as drawable and use internally.
 public void setImageBitmap(Bitmap bm) {
    // if this is used frequently, may handle bitmaps explicitly
    // to reduce the intermediate drawable object
    setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
}

so i can get the drawable width and height, and i can get the imageview height and width,but imageview use `CENTER_FIT ScaleType to set Image in Imageview.
but I want to know the Image height and width  ,starting point,ending point consumes of Image in imageview .
so I can do some operations on the top of the image. is it possible?
`


text:
Q: How do I connect with SharePoint Online Web Services in order to access list and taxonomy data? I am using the SharePoint SOAP web services to try collecting list and taxonomy data from a site on SharePoint Online.
The following code works nicely when connected to a standalone SharePoint farm. However, when connecting to SharePoint Online, the call to GetList fails with a SOAPException:
"Server was unable to process request. ---> Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

Code:
using (ListService.Lists service = new ListService.Lists())
{
    service.Credentials = new System.Net.NetworkCredential("username", "password");

    XmlNode list = service.GetList("Doclib");
}

using (TaxonomyService.Taxonomywebservice taxonomy = new TaxonomyService.Taxonomywebservice())
{
    // Set credentials
    taxonomy.Credentials = System.Net.CredentialCache.DefaultCredentials;

    for (int termSetCounter = 0; termSetCounter < allTermSetIds.Count; termSetCounter++)
    {
        int lcid = System.Globalization.CultureInfo.CurrentUICulture.LCID;

        string termStoreId = String.Format("<termSetIds><termStoreId>{0}</termStoreId></termSetIds>", allSharedServiceIds[termSetCounter]);
        string termSetId = String.Format("<termSetIds><termSetId>{0}</termSetId></termSetIds>", allTermSetIds[termSetCounter]);

        // Get one term set from term store using Web Service
        string resultXML = taxonomy.GetTermSets(termStoreId, termSetId, lcid, oldtimestamp, clientVersion, out timeStamp);

    }
}

This blog post seems to indicate that the reason authenticating fails, is that Web Services against Office 365/SharePoint Online are not yet officially supported. There appears to be a workaround involving some shady gathering and pass-through of cookies from Internet Explorer, but this is a huge hack and I can't seem to get it working with a real-life application.
Microsoft does seem to have a list of Web Services available in SharePoint Online here, but this list does not seem to include the SOAP services mentioned above. I do not see any services that support taxonomy data either. Also, not even SharePoint Designer supports editing Taxonomy columns from the client-side. This does seem like a huge oversight, though.
Is there another way than Web Services to get access to list and taxonomy information from SharePoint Online sites? If not, is there any information available from Microsoft regarding when this will be supported?

A: You can connect to ShraPoint Online through the Client Object Model as show here:
http://blogs.msdn.com/b/cjohnson/archive/2011/05/03/authentication-with-sharepoint-online-and-the-client-side-object-model.aspx
You can download the code sample and build on top of it. Get back to me if you need any help.
I agree that you think this is a "hack" but it works right now :)

A: I have now received an answer from a Microsoft employee (SharePoint Solution Architect at an office in Scandinavia) regarding this question. The problem is that SharePoint Online uses Claims-based authentication, but the built-in .NET API officially only supports Default (NTLM) and Forms-based authentication. Microsoft (probably) does not plan to make any major changes to the API until the next major version of SharePoint is released, probably around 2013.
Therefore, at the present time, the official line for performing Claims-based authentication from .NET code is to use the workaround described above. You will end up with a CookieCollection object representing the Session ID for the current Claims-based authentication session, which can be used to create an authenticated ClientContext object or to authenticate any of the SharePoint web services...including TaxonomyClientService.  This will let you get the term set data necessary to use Managed Metadata programmatically.
The source code in the link is a good starting point, but you probably have to run it in a separate thread due to a COM issue.

A: The following example demonstrates how to authenticate SharePoint SOAP Services in SharePoint Online using SharePointOnlineCredentials class :
public static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
{
    var securePassword = new SecureString();
    foreach (char c in password) { securePassword.AppendChar(c); }
    var credentials = new SharePointOnlineCredentials(userName, securePassword);
    var authCookie = credentials.GetAuthenticationCookie(webUri);
    var cookieContainer = new CookieContainer();
    cookieContainer.SetCookies(webUri, authCookie);
    return cookieContainer;
}

Example
var webUri = new Uri("https://contoso.sharepoint.com/");
Lists list = new Lists();  //Lists SOAP Service
list.CookieContainer = GetAuthCookies(webUri,userName,password);

//Invoke GetListCollection operation
XmlNode result = list.GetListCollection();

//Process result
var docResult = XDocument.Parse(result.OuterXml);
XNamespace s = "http://schemas.microsoft.com/sharepoint/soap/";
var listEntries = from e in docResult.Descendants(s + "List")
              select new
                 {
                     Title = e.Attribute("Title").Value
                 };


text:
Q: Header on Netizen Theme i have one problem with the design of my site (theme: Netizen).
I don't find for fix the header (with site logo and cart) on the top when i scroll down you know, do you have a solution for modify this on css file?
Best.


text:
Q: OutOfMemoryError occurs using YouTube Android player api 1.2.2 Play video using youtube player sdk about 30~40 times causes Youtube application crashes, then a DeadObjectException will raise from my app due to the death of remote process. steps to reproduce:

*

*launch activity and initialize YouTubePlayer

*load and play a video for a few seconds

*release YouTubePlayer and exit activity

*repeat step 1-3 about 30~40 times

OutOfMemoryError log(full logs):
08-22 12:01:01.461 E/AndroidRuntime( 3017): FATAL EXCEPTION: main
08-22 12:01:01.461 E/AndroidRuntime( 3017): Process: com.google.android.youtube.player, PID: 3017
08-22 12:01:01.461 E/AndroidRuntime( 3017): java.lang.OutOfMemoryError: Could not allocate JNI Env
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.lang.Thread.nativeCreate(Native Method)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.lang.Thread.start(Thread.java:1063)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:921)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.util.concurrent.ThreadPoolExecutor.ensurePrestart(ThreadPoolExecutor.java:1556)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute(ScheduledThreadPoolExecutor.java:310)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.util.concurrent.ScheduledThreadPoolExecutor.schedule(ScheduledThreadPoolExecutor.java:527)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.util.concurrent.ScheduledThreadPoolExecutor.execute(ScheduledThreadPoolExecutor.java:616)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at reo.a(SourceFile:134)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at sgh.a(SourceFile:722)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at gan.a(SourceFile:310)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at gan.b(SourceFile:338)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at com.google.android.apps.youtube.embeddedplayer.service.service.jar.ApiPlayerService$2.run(SourceFile:215)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at android.os.Handler.handleCallback(Handler.java:739)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at android.os.Looper.loop(Looper.java:148)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at android.app.ActivityThread.main(ActivityThread.java:5417)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at java.lang.reflect.Method.invoke(Native Method)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
08-22 12:01:01.461 E/AndroidRuntime( 3017):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

and DeadObjectException
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976): java.lang.IllegalStateException: android.os.DeadObjectException
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at gix.surfaceCreated(SourceFile:189)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.SurfaceView.updateWindow(SurfaceView.java:582)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:177)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2055)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.Choreographer.doCallbacks(Choreographer.java:670)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.Choreographer.doFrame(Choreographer.java:606)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.os.Handler.handleCallback(Handler.java:739)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.os.Handler.dispatchMessage(Handler.java:95)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.os.Looper.loop(Looper.java:148)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.app.ActivityThread.main(ActivityThread.java:5417)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at java.lang.reflect.Method.invoke(Native Method)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976): Caused by: android.os.DeadObjectException
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.os.BinderProxy.transactNative(Native Method)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at android.os.BinderProxy.transact(Binder.java:503)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at com.google.android.apps.youtube.embeddedplayer.service.service.jar.ISurfaceHolderService$Stub$Proxy.a(SourceFile:110)
08-22 12:01:01.842 E/MonitoringInstrumentation( 2976):  at gix.surfaceCreated(SourceFile:186)

YouTube App version is 11.29.55 , Nexus 5 emulator with Marshmallow
, I've tested it with other versions of YouTube App like 10.25.57 and 10.40.58, the OOM still occurs.
At the very beginning when I encounter this issue I thought it was just caused by some incorrectly api method calls, but after so many hours research I figured out it should be a YouTube App's issue, hope someone can help me to resolve it, or at least avoid it.
The memory of process com.google.android.youtube.player is increasing while player initialization and video playing from Memory Monitor, and many YoutubeService instances created but not recycled from the dump file. Any idea?
I test it with a demo application based on the official YouTubeAndroidAPI sample and the OutOfMemory error occurs as well, I just replaced cueVideo(String) by loadVideo(String) in PlayerViewDemoActivity for auto-playing, and added YouTubePlayer#release() in onDestroy(), also I added a test code based on Espresso to reproduce the memory leak issue.
here is the test code, and here for full demo code.
package com.examples.youtubeapidemo.play;

import android.os.SystemClock;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;

import com.examples.youtubeapidemo.YouTubeAPIDemoActivity;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.pressBack;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

/**
 * for YouTubePlayerView testing
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PlayerViewTest {

    @Rule
    public ActivityTestRule<YouTubeAPIDemoActivity> mActivityTestRule =
            new ActivityTestRule<YouTubeAPIDemoActivity>(YouTubeAPIDemoActivity.class);

    @Test
    public void testYouTubeMemoryLeaks() {
        int count = 0;
        while(count < 100) {
            onView(withText("Simple PlayerView")).perform(click());
            SystemClock.sleep(10000); // waiting for video start playing
            pressBack();
            count++;
            Log.i("PlayerViewTest", "count: " + count);
        }
    }
}

A: I reduced the bug occurrence by putting youtube calls (like youtubePlayer.loadVideo(), cueVideo(), getCurrentTimeMillis() etc.) in a try catch block and catch the IllegalStateException exception then reinitialize youtube player.
and worked around it by catching these exceptions and restart activity,
see my answer on this thread :
Getting a lot of crashes from android youtube player api


text:
Q: Get iframe html or name from parent window I have a page that loads few iframe's within itself.
Each iframe can invoke parent function.
For example like this:
$(document).ready(function() {
  parent.test();
}

I want to be able to find which iframe invoked test function.
I've tried to play with calleer.called properties but the best I could get is the function that calling test().
In my case it was $(document).ready function.
Is there a way to get the name of iframe (or it's html name) which calling the function?

A: If you pass a parameter to the test function it will work:
$(document).ready(function() {
  parent.test('name of this iframe');
}

OR even better
$(document).ready(function() {
  parent.test(window.name);
}

Then you just need to use that value passed to the inside of the test function.


text:
Q: How to make a contenteditable of only lists? I'm trying to create a contenteditable editor where everything is a list. However if I simply give a ul tag contenteditable="true", the top list item can be deleted. How do I make it so that every new line is a list, and the top line li cannot be deleted. Thanks
Here's what I've got :

Type text here. Try deleting this list item.

A: The most trivial way of solving your problem would be insert an empty non-editable  into the first
 element.
This is also not absolutely fool-proof, but will protect the first
 element against most edit attempts.

Type text here. Try deleting this list item.

editable!


text:
Q: 2PC transactions (cross transactions) in GlassFish 5 Does someone know if GlassFish 5 has support to use global transactions with 2PC (XA protocol)? but without install extra tools.
I have looked for information in the page of GlassFish "The Open Source Java EE Reference Implementation" where I downloaded the app server (and in other pages) but I have not had luck.
I try doing transactions in two microservices that insert two values in the data base. I have configured the GlassFish's JNDI with "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" and it looks like working, but when I check the data base only is added a value of one service. (the global transactions with 2PC does not work). I begin to think that GlassFish does not have support for 2PC.
I have read that it can do it with tomcat, but i need to add tools like atomikos, bitronix, etc. The idea is can do it with glassfish with out install nothing more.
Regards.

A:
Does someone know if GlassFish 5 has support to use global transactions with 2PC (XA protocol)? but without install extra tools.

Glassfish 5 supports transactions using XA datasources. You can create a program that executes transactions combining operations on multiple databases. For instance, you can create a transaction that performs operations into Oracle and IBM DB2 databases. If one of operations in the transaction fails, the other operations (in the same and in the other databases) will be not executed or rollbacked.

I try doing transactions in two microservices that insert two values in the data base. I have configured the GlassFish's JNDI with "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" and it looks like working, but when I check the data base only is added a value of one service.

If your program invokes a REST/web service in a transaction, the operations performed by the other REST/webservice do not join to the transaction. An error in the program will not produce a rollback in the operations performed by the already invoked REST/webservice.


text:
Q: Сессии пользователя на php Пишу аторизацию пользователя через вк.
Получаю данные, если пользователь есть - обновляем, если нет, создаем.
Записываем все это в сессию пользователя.
Дальше нужно немного разъяснений из первых уст.
Как я понимаю (исправляйте, если что), сессия хранится пока пользователь не закроет браузер или 24 минуты при отсутсвии активности. Поэтому в куки планирую записать ай-ди пользователя в зашифрованном виде (расшифровка на сервере). Дальше если человек заходит с куками - берем его данные из базы и создаем с ними сессию.
Как это сделать я понимаю, но почитал инфу и все пишут, что нужно хранить идентификатор сессии? Что это значит, ведь сессия уничтожается или нет? Как правильно реализовать повторный вход, чтобы не делать ошибок?


text:
Q: ¿Como realizar un scroll down en la seccion de resultados de Google Maps con Selenium? Actualmente estoy realizando un scrapeo de varios sitios de interes (en el código ira farmacias) pero me estoy encontrando con el problema que al llamar los "results" no me carca nada más que los primero 10 o 7. He estado buscando por todos lados pero utilizan la sentencia (Self) yo no busco usarla.
Adjunto codigo y en donde pido su ayuda de colocar en que parte iria el scroll down.
Además he intentando tambien la sentencia donde es el scrapeo de reseñas y tampoco ha funcionado con mi código o tambien pueda ser que lo he colocado de forma equivocada.
Pido su ayuda para poder realizar un scroll down en los resultados.

#Abre el simulador del navegador de Chrome
driver = webdriver.Chrome(service = Service(".\chromedriver"))
wait = WebDriverWait(driver, 5)
#url = "https://www.google.com/maps"
#driver.get(url)
#time.sleep(5)
data = []
for x in range(len(mpio)):
    #Google maps
    query = mpio[x] + ", "+ depto[x]
    url = "https://www.google.es/maps/search/"+query.replace(" ", "+")+"/"
    driver.get(url)
    time.sleep(2)
    cancelbut=driver.find_element(By.CLASS_NAME,'gsst_a')
    cancelbut.click()
    buscador = "Farmacia cerca de " + mpio[x] +" ver ubicaciones"
    searchbox = driver.find_element(By.ID, "searchboxinput")
    searchbox.send_keys(buscador)
    searchbox.send_keys(Keys.ENTER)
    time.sleep(10)
    i = 0
    try:
        while (i<=20):

                results = driver.find_elements(By.XPATH,'//div[contains(@aria-label,"'+buscador+'")]//div[contains(@jsaction,"mouseover")]')
                ActionChains(driver).move_to_element(results[i]).click().perform()
                time.sleep(2)
                direccion = get_address()
                name = get_name()
                num = i + 1
                coordenadas = get_geocoder(driver.current_url)
                direccion = get_address()
                horarios = get_horarios()
                puntaje = get_puntaje()
                resenias = get_numresenias()

                if ((nomcorto[x].upper() in direccion.upper())==True):
                    datos = 1, num, depto[x], mpio[x], name, coordenadas, direccion, horarios, puntaje, resenias
                    data.append((datos))
                    print(1,num, depto[x], mpio[x], name, coordenadas, direccion, horarios, puntaje, resenias, sep = "-.-", end="\n")
                    i = i + 1
                    if(i==20):
                        element = driver.find_element(By.CLASS_NAME,"nhb85d-zuz9Sc-haAclf")
                        time.sleep(1)
                        element.click()
                        time.sleep(1)
                        element2 = driver.find_element(By.ID,"ppdPk-Ej1Yeb-LgbsSe-tJiF1e")
                        time.sleep(1)
                        element2.click()
                        time.sleep(1)
                        i = 0
                        continue
                elif((deptocorto[x].upper() in direccion.upper())==True):
                    datos = 2, num, depto[x], mpio[x], name, coordenadas, direccion, horarios, puntaje, resenias
                    data.append(datos)
                    print(2,num, depto[x], mpio[x], name, coordenadas, direccion, horarios, puntaje, resenias, sep = "-.-", end="\n")
                    i = i + 1
                    if(i==20):
                        element = driver.find_element(By.CLASS_NAME,"nhb85d-zuz9Sc-haAclf")
                        time.sleep(1)
                        element.click()
                        time.sleep(1)
                        element2 = driver.find_element(By.ID,"ppdPk-Ej1Yeb-LgbsSe-tJiF1e")
                        time.sleep(1)
                        element2.click()
                        time.sleep(1)
                        i = 0
                        continue
                elif((nomcorto[x].upper() in name.upper())==True):
                    datos = 3, num, depto[x], mpio[x], name, coordenadas, direccion, horarios, puntaje, resenias
                    data.append(datos)
                    print(3,num, depto[x], mpio[x], name, coordenadas, direccion, horarios, puntaje, resenias, sep = "-.-", end="\n")
                    i = i + 1
                    if(i==20):
                        element = driver.find_element(By.CLASS_NAME,"nhb85d-zuz9Sc-haAclf")
                        time.sleep(1)
                        element.click()
                        time.sleep(1)
                        element2 = driver.find_element(By.ID,"ppdPk-Ej1Yeb-LgbsSe-tJiF1e")
                        time.sleep(1)
                        element2.click()
                        time.sleep(1)
                        i = 0
                        continue
                else:
                    break
    except Exception as e:
        print(e)

    time.sleep(3)`

  [1]: https://i.stack.imgur.com/nbjEV.png


text:
Q: confusion in left shift operator in python I am trying to use left shift operator on the 16 bit binary representation of a integer
Code written is below:
def showbits(x):
    return bin(x)[2:].zfill(16)
i=5225
print "Decimal %d is same as binary" % (i)
print showbits(i)
for j in range(0,5,1):
    k=i<<j
    print "%d right shift % gives" % (i,j)
    print showbits(k)

Output:
Decimal 5225 is same as binary
0001010001101001
5225 right shift  0ives
0001010001101001
5225 right shift  1ives
0010100011010010
5225 right shift  2ives
0101000110100100
5225 right shift  3ives
1010001101001000
5225 right shift  4ives
10100011010010000

The main problem is that when it is shifting the leading '1', it is not vanishing but it is increasing one more bit...
Any solution for that?

A: You'd mask the resulting value, with & bitwise AND:
mask = 2 ** 16 - 1
k = (i << j) & mask

Here 16 is your desired bit width; you could use i.bit_length() to limit it to the minimum required size of i, but that'd mean that any left shift would drop bits.
The mask forms a series of 1 bits the same width as the original value; the & operation sets any bits to 0 outside of these:
>>> 0b1010 & 0b111
2
>>> format(0b1010 & 0b111, '04b')
'0010'

Some side notes:

*

*You are left shifting, not right shifting.

*You appear to have forgotten to a d in your debug print:
print "%d left shift %d gives" % (i,j)

There was a lone % there that combined with the g for gives to make %g (floating point formatting).

*You can use:
def showbits(x):
    return format(x, '016b')

to format an integer to a 0-padded 16-character wide binary representation without the 0b prefix.

A: Because Python does some magic to prevent this condition, known as an overflow, from happening. It does this by adjusting the type:
>>> i = 5225
>>> type(i)
<type 'int'>
>>> j = i << 16; type(j); bin(j)
<type 'int'>
'0b10100011010010000000000000000'
>>> j = i << 32; type(j); bin(j)
<type 'int'>
'0b101000110100100000000000000000000000000000000'
>>> j = i << 64; type(j); bin(j)
<type 'long'>
'0b10100011010010000000000000000000000000000000000000000000000000000000000000000'
>>> j = i << 128; type(j); bin(j)
<type 'long'>
'0b101000110100100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'

If you want to limit the bits you want to work with, do as Martijn suggests and use a 16-bit mask.
>>> j = 0xffff & (i << 12); type(j); bin(j)[2:].zfill(16)
<type 'int'>
'1001000000000000'
>>> j = 0xffff & (i << 13); type(j); bin(j)[2:].zfill(16)
<type 'int'>
'0010000000000000'
>>> j = 0xffff & (i << 14); type(j); bin(j)[2:].zfill(16)
<type 'int'>
'0100000000000000'
>>> j = 0xffff & (i << 15); type(j); bin(j)[2:].zfill(16)
<type 'int'>
'1000000000000000'
>>> j = 0xffff & (i << 16); type(j); bin(j)[2:].zfill(16)
<type 'int'>
'0000000000000000'


text:
Q: Android Multichoice Item Dialog with Search Functionality In my Android application I have a multi choice item dialog (similar to that shown in the image) that has a large number of items. So I plan to add a search box and as user types, the items are filtered accordingly. What is the best way to do this? Thanks

A: I did it like this, works fine for me.
private static final class ListItemWithIndex {
        public final int index;
        public final String value;

        public ListItemWithIndex(final int index, final String value) {
            super();
            this.index = index;
            this.value = value;
        }

        @Override
        public String toString() {
            return value;
        }
    }

    public static void showMultiChoiceDialogWithSearchFilterUI(final Activity _activity, final Object[] _optionsList,
            final int _titleResId, final OnClickListener _itemSelectionListener) {
        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(_activity);

        final List<ListItemWithIndex> allItems = new ArrayList<ListItemWithIndex>();
        final List<ListItemWithIndex> filteredItems = new ArrayList<ListItemWithIndex>();

        for (int i = 0; i < _optionsList.length; i++) {
            final Object obj = _optionsList[i];
            final ListItemWithIndex listItemWithIndex = new ListItemWithIndex(i, obj.toString());
            allItems.add(listItemWithIndex);
            filteredItems.add(listItemWithIndex);
        }

        dialogBuilder.setTitle(_titleResId);
        final ArrayAdapter<ListItemWithIndex> objectsAdapter = new ArrayAdapter<ListItemWithIndex>(_activity,
                android.R.layout.simple_list_item_1, filteredItems) {
            @Override
            public Filter getFilter() {
                return new Filter() {
                    @SuppressWarnings("unchecked")
                    @Override
                    protected void publishResults(final CharSequence constraint, final FilterResults results) {
                        filteredItems.clear();
                        filteredItems.addAll((List<ListItemWithIndex>) results.values);
                        notifyDataSetChanged();
                    }

                    @Override
                    protected FilterResults performFiltering(final CharSequence constraint) {
                        final FilterResults results = new FilterResults();

                        final String filterString = constraint.toString();
                        final ArrayList<ListItemWithIndex> list = new ArrayList<ListItemWithIndex>();
                        for (final ListItemWithIndex obj : allItems) {
                            final String objStr = obj.toString();
                            if ("".equals(filterString)
                                    || objStr.toLowerCase(Locale.getDefault()).contains(
                                            filterString.toLowerCase(Locale.getDefault()))) {
                                list.add(obj);
                            }
                        }

                        results.values = list;
                        results.count = list.size();
                        return results;
                    }
                };
            }
        };

        final EditText searchEditText = new EditText(_activity);
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(final CharSequence arg0, final int arg1, final int arg2, final int arg3) {
            }

            @Override
            public void beforeTextChanged(final CharSequence arg0, final int arg1, final int arg2, final int arg3) {
            }

            @Override
            public void afterTextChanged(final Editable arg0) {
                objectsAdapter.getFilter().filter(searchEditText.getText());
            }
        });

        final ListView listView = new ListView(_activity);
        listView.setAdapter(objectsAdapter);
        final LinearLayout linearLayout = new LinearLayout(_activity);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(searchEditText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, 0);
        layoutParams.weight = 1;
        linearLayout.addView(listView, layoutParams);
        dialogBuilder.setView(linearLayout);

        final AlertDialog dialog = dialogBuilder.create();
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
                dialog.dismiss();
                _itemSelectionListener.onClick(null, filteredItems.get(position).index);
            }
        });
        dialog.show();
    }

Just use the "showMultiChoiceDialogWithSearchFilterUI" function.
You might want to inflate the edittext and listview from an XML though, because on this solution the views creation is hardcoded.


text:
Q: Jquery Ajax On-Focusout On-Submit - Requires 2 Clicks Hello I have a jquery and ajax validation form, when you fill the values (wrong values) x@x.com and 1111111 in password it will give ajax validation notice (which is fine) but after that if you put in the values (correct values) example@example.com and 12345678 it requires two clicks to submit. Meaning if you put wrong values first and then put correct values then it will require two clicks to submit. following is the code. I have set the code below so you can copy and paste the code into files (filenames given before) and you will have a working model to work with.  I have hardcoded the php validate file so you guys can copy and paste the code and see how it works.
index.php
<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
?>

<!DOCTYPE HTML>

    <meta charset="UTF-8">

    <form method="post" name="loginform" action="success.php">
        <input type="email" class="homepage"  name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />

        <input type="password" class="homepage"  name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />

        <input type="submit" name="login" id="login" value="Submit">

    </form>

validatelogin.js
$(document).ready(function()
{
    /* ----------------- Login Validations Global Variables -----------------   */
    var user_email2 = "";
    var user_emailajax2 = "";
    var user_password2 = "";
    var user_passwordajax2 = "";
    var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

    /* ----------------- Define Validate Email */
    var validate_email_login = function()
    {
        var item5 = $("#user_email2").val();
        var item5 = item5.toLowerCase();
        if (item5.length < 6 || item5.length > 50)
        {
            $("#errormsg6").html("Email : 6 - 50 Characters");
            user_email2 = "";
        }
        else
        {
            $("#errormsg6").html("");
            user_email2 = item5;
            if (!emailformat.test(item5))
            {
                $("#errormsg6").html("Wrong Email Format");
                user_email2 = "";
            }
            else
            {
                $("#errormsg6").html("");
                user_email2 = item5;
                $.ajax(
                {
                    type: 'POST',
                    url: 'validatelogin.php?f=1',
                    data: "user_email2=" + item5,
                    success: function(msg)
                    {
                        if (msg == "ok")
                        {
                            user_emailajax2 = "";
                            $("#errormsg6").html("Email Does Not Exist");
                        }
                        else if (msg == "exists")
                        {
                            user_emailajax2 = item5;
                            $("#errormsg6").html("");
                        }
                    }
                });
            }
        }
    }

    /* ----------------- Define Validate Password */
    var validate_password_login = function()
    {
        var item5 = $("#user_email2").val();
        var item5 = item5.toLowerCase();
        var item6 = $("#user_password2").val();

        if (item6.length < 8 || item6.length > 20)
        {
            $("#errormsg7").html("Password : 8-20 Characters");
            user_password2 = "";
        }
        else
        {
            $("#errormsg7").html("");
            user_password2 = item6;
            if (user_email2 != "" && user_emailajax2 != "")
            {
                $.ajax(
                {
                    method: "POST",
                    url: "validatelogin.php?f=2",
                    data: "user_email2=" + item5 + "&user_password2=" + item6,
                    success: function(msg)
                    {
                        if (msg == "WrongPw")
                        {
                            user_passwordajax2 = "";
                            $("#errormsg7").html("Wrong Password");
                        }
                        else if (msg == "CorrectPw")
                        {
                            user_passwordajax2 = item6;
                            $("#errormsg7").html("");
                            /* window.location.href="manage-properties"; */
                        }
                    }
                });
            }
        }
    }

    /* ----------------- Run Functions */
    $("#user_email2").on('focusout', validate_email_login);
    $("#user_password2").on('focusout', validate_password_login);
    $("#login").on('click', validate_email_login);
    $("#login").on('click', validate_password_login);

    /* ----------------- Stop on Submit */
    $("#login").on('click', function()
    {
        if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
        {
            $("#errormsg8").html("Please Fill All Fields (Correctly)");
            console.log("submit false");
            return false;
        }
        else
        {
            $("#errormsg8").html("");
            console.log("submit true");
            return true;
        }
    });
});

validatelogin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if($_GET['f']==1) {
    if(isset($_POST['user_email2'])) {
        $user_email2 = strtolower($_POST['user_email2']);
        if($user_email2 == "example@example.com") {
            echo "exists";
        } else {
            echo "ok";
        }
    }
}

if($_GET['f']==2) {
    if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
        $user_email2 = strtolower($_POST['user_email2']);
        $user_password2 = $_POST['user_password2'];

        if($user_email2!="example@example.com" and $user_password2!="12345678") {
            echo "WrongPw";
        } elseif($user_email2=="example@example.com" and $user_password2=="12345678") {
            echo "CorrectPw";
        }
    }
}
?>

success.php
<?php
echo "Login Successful";
?>

Tried Solutions
1. Putting a delay on the submit button
2. On Keyup instead of on Focusout (this works but not what is required)
3. Give delay to keyup (could not get it to work with ajax - but its closer to what I require, but not exactly what I require
4. Triggering the click on submit on return true of ajax (also did not work)
I need some javascript expert to look into it and give me solution.

A: Okay, I don't want to be rude, but all that code is a bit of a disaster. You're calling the on click function 3 different times, you're making ajax calls to the server on every form change and on submit. Then you're actually making two separate ajax calls for the actual submit function.
The code below is a lot more compact, only ever makes one ajax call and should work. I'll explain a bit before each code block
Your form add an id so that jQuery can use serialize in the ajax call
<form method="post" id="loginform" name="loginform" action="success.php">
    <input type="email" class="homepage"  name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />

    <input type="password" class="homepage"  name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />

    <input type="submit" name="login" id="login" value="Submit">

</form>

validatelogin.php - This should only be one call to the server, do both functions in one, return the data as json rather than echoing single values, that way you get an object back that you can parse in your jQuery code.
<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
    $user_password2 = $_POST['user_password2'];
    $user_email2 = strtolower($_POST['user_email2']);
    if($user_email2 != "example@example.com") {
        $data['email_check'] = 'false';
    } else {
        $data['email_check'] = 'true';
    }
    $data = array;
    if($user_email2!="example@example.com" && $user_password2!="12345678") {
        $data['password_check'] = 'false';
    } else {
        $data['password_check'] = 'true';
    }
}
print(json_encode($data));

jQuery - I am not really sure why you're calling all these functions on blur and the multiple on clicks. Just do it in the one on click, call validate email, if that passes you move on to validate password and if that passes it makes the ajax call to actually check the details against the server.
Also avoid variable names like item5, errormsg6, to another developer that means nothing, and it won't to you in 6 months either. And don't tell people which element was wrong, ie "Incorrect password" just for security, just tell them their login details are wrong.
$(document).ready(function() {
  /* ----------------- Login Validations Global Variables -----------------   */
  var user_email2 = "";
  var user_emailajax2 = "";
  var user_password2 = "";
  var user_passwordajax2 = "";
  var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
  /* ----------------- Define Validate Email */
  var validate_email_login = function() {
    var email = $("#user_email2").val().toLowerCase();
      var errors = [];

    if (email.length < 6 || email.length > 50) {
        errors.push("Email : 6 - 50 Characters
");
    }

    if (!emailformat.test(email)) {
      errors.push("Wrong Email Format");
    }
    if( errors.length > 0 ) {
      $("#errormsg6").html(errors);
      return false;
    }
    $("#errormsg6").html();
    validate_password_login();
  }

  /* ----------------- Define Validate Password */
  var validate_password_login = function() {
    var item6 = $("#user_password2").val();

    if (item6.length < 8 || item6.length > 20) {
        $("#errormsg7").html("Password : 8-20 Characters");
        return false;
    }
    $("#errormsg7").html("");
    submitForm();
  }

  var submitForm = function() {
    $.ajax({
      type: 'POST',
      url: 'validatelogin.php',
      dataType: "json",
      data: $("#loginform").serialize(),
      success: function(msg) {

        if(msg.email_check == 'true' && msg.password_check == 'true') {
            //do whatever it is you want to do on correct login here
        } else {
            $("#errormsg6").html("Your login details are incorrect, please check and try again");
        }
      }
    });
  }

  /* ----------------- Stop on Submit */
  $("#login").on('click', function() {
      errors = [];
    if(validate_email_login() == true) {
        alert("hi");
    }
  });
});

You can see the error validation on the jQuery end here: https://jsfiddle.net/calder12/3fhvpenr/


text:
Q: How to install opera-stable_26.0.1656.60_amd64.deb in centos6 I have downloaded opera-stable_26.0.1656.60_amd64.deb and searched how to install the same in my centos6.Got several links but none of them gave actual method.Please provide a suitable solution. I have tried with following command
yum install opera-stable_26.0.1656.60_amd64.deb

A: You could try using this script to convert the deb to an rpm:
http://ruario.ghost.io/2014/12/20/my-christmas-present-to-opera-fans-on-rpm-distros/


text:
Q: Access parent document from dynamic iframe using jquery This question is continuation of this question. I use the following code to append the dynamic  to the document.
var _hf_iFrame = document.createElement("iframe");
_hf_iFrame.setAttribute("id", "_hf_iFrame");
_hf_iFrame.setAttribute("name", "_hf_iFrame");
_hf_iFrame.setAttribute("allow-transparency", true);
_hf_iFrame.setAttribute("style", "height: 354px; width: 445px; border: 0; top: 23%; position: fixed; left:0; overflow: show; background:transparent;");
document.body.appendChild(_hf_iFrame);
_hf_iFrame.setAttribute("src", "javascript:false");

var myContent = '<!DOCTYPE html>'
+ '<title>Helpflip</title>'
+ '';

_hf_iFrame.contentWindow.document.open('text/html', 'replace');
_hf_iFrame.contentWindow.document.write(myContent);
_hf_iFrame.contentWindow.document.close();

When the  has loaded, I am trying to animate it using the following code
$('#_hf_iFrame', top.document).animate({
      'margin-left': '-400px'
   }, 300).animate({
      'margin-left': '-380px'
   }, 150).animate({
      'margin-left': '-393px'
}, 100);

This works fine on Firefox, Chrome and on Safari. IE 9 throws Access Denied on line $('#_hf_iFrame', top.document)
Does the problem of cross domain still apply?
Thanks in advance.


text:
Q: Nested Loops Python Hi I am working with nested loops but can not figure out a way to start a new row for my nested loop below:
for i in range(0,10):
    for j in range(10):
        print(i,end =" ")

Output
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9
The output I want is:
0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
and so on

A: Thank you but I found the answer!
for i in range(0,10):
    for j in range(10):
        print(i, end=" ")
    print()

A: This (and minor variations) also work:
for i in range(10):
    print((('%s '%i)*10)[:-1])


text:
Q: QLabel text not selectble even when i set Qt::TextSelectableByMouse inside QStyledItemDelegate I have a simple item delegate of QStyledItemDelegate type and inside its paint method I have this code. It renders fine, but the main thing here is that I would like the text to be selectable for copy, and this doesn't work.
void ItemDelegate::paintBody( QPainter* painter,
                              const QStyleOptionViewItem& option,
                              const QModelIndex& index ) const
{
    painter->save();

    QLabel *l = new QLabel();
    l->setTextFormat(Qt::RichText);
    l->setTextInteractionFlags(Qt::TextSelectableByMouse);
    l->setGeometry(option.rect);
    l->setText("This is test");
    l->setStyleSheet("QLabel { background-color : transparent; }");
    l->render(painter, option.rect.topLeft());

    painter->restore();
}

A: Because all all you're doing is painting a QLabel.  The QLabel does not 'exist' inside the model view you are calling for, it is only rendered in the state that you created it.
You should use
QStyle::drawControl( ControlElement element,
                     const QStyleOption* option,
                     QPainter* painter,
                     const QWidget* widget = 0 ) const;

to draw the label. Do not create a new QLabel everytime you need to paint it, not only is this inefficient, you have also created the mother of all memory leaks by not deleting it...
More importantly though, selecting text should really be a part of the editor delegate, so you should be overriding
QWidget* QAbstractItemDelegate::createEditor( QWidget* parent,
                                              const QStyleOptionViewItem& option,
                                              const QModelIndex& index ) const;

to return a widget that can display editable rich text.


text:
Q: Exception When Opening Excel File in C# Using Interop I have a program running on a server which downloads an .xls file from a website every day, opens it then converts it to a .csv to be able to parse it correctly and add to a database.
When I run it on my local PC everything works fine and it works most of the time on the server as well, but maybe once or twice a week I get this exception:
Exception occurred: System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
   at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
Here's a code snippet:
 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Open(_dir + _fileNameTrim + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wbWorkbook.SaveAs(_dir + _fileNameTrim + ".csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wbWorkbook.Close(false, "", true);

I've read many things online, a lot of solutions mention security settings but I don't think this is the case with me, otherwise it wouldnt work at all. People have also mentioned the file being corrupt. I'm really not sure. Any help would be much appreciated.
UPDATE:
Excel is installed on the server and the exception occurs when trying to open the file.

A: .Workbooks.Open(strPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlExtractData);

A: I have the same problem.
It is specifically related to new Microsoft.Office.Interop.Excel.Application(); and what I have been doing is to create the file in a temp location where I know I don't have any permission issues.
Once I am done creating the document, I then move it to the final destination, deleting the file created in my temp location.
So far I have not had any issues.
I suggest you create a log file and save it by date where it can log the steps it completes throughout your code. This way you can see where it fails.
If possible too, do a Process.Kill() on excel if this is the only application that requires excel. This helps if Excel.exe does not close properly.
Final, as stated in the comments above, Excel automation on the server is not supported. I would recommend looking in to SSIS for automation of excel.
UPDATE:
Make sure you test if the application runs even when no user is logged on. You might need to set the DCOM identity for Microsoft Excel to run as a specific user account and not the interactive user.
Go to:

Control Panel\All Control Panel Items\Administrative Tools

Click on

Component Services and navigate to Console Root\Component
  Services\Computers\My Computer\DCOM Config\Microsoft Excel Application

Right click Microsoft Excel Application and select Properties
Under the Security tab, set to Customize on all and give access to Everyone (for testing)
Under the Identity tab, set This User and select the appropriate account (same account as the Task Scheduler is using to run your application)
Good Luck!

A: Run> dcomcnfg
This will open Component Services and navigate to Console Root
\Component Services\Computers\My Computer\DCOM Config\Microsoft Excel Application
Right click Microsoft Excel Application and select Properties
Click on Identity Tab and check selection.
It works for me when select option - The interactive user
Please try, best luck!!

A: Did you check if it's a permission issue?  It's possible that you are trying to save the file to a location and .NET doesn't have the permissions to write to that location.


text:
Q: Session Variables for Counting Login attempts I am trying to implement a login scheme where I keep a count on the number of attempts the user tries , this is for security reasons . My code is :
{
    ob_start();
    $_SESSION['attempts'] = 0;
    $_SESSION['sleep'] = 0;
    $_SESSION['ip']=$this->get_ip_address() ;
    $login = new User('login');
    // renders the view file 'protected/views/site/index.php'
    // using the default layout 'protected/views/layouts/main.php'

    if(isset($_POST['yt0']))
    {
            $login->Username = ($_POST['User']['Username']);
            $salt = $login->getSaltByUsername($login->Username) ;
            $login->SecretCode = $this->hasher($login->Username,($_POST['User']['SecretCode']),$salt);
            var_dump($_SESSION)  ;  /*First Dump , gives all session variables correctly*/
            echo $_SESSION['attempts'] ;
            Yii::app()->user->setState('attempts', $_SESSION['attempts']++);

            var_dump($_SESSION)  ;

I am getting the PHP Notice : "Undefined index: attempts "
However in the first dump as well as the echo i am getting the correct number of attempts .
What am I doing wrong here ?

A: I think you should use CHttpSession instead of $_SESSION
$session=new CHttpSession;
$session->open();

$session['attempts'] = 0;
$session['sleep'] = 0;
$session['ip']=$this->get_ip_address();

I've never used $_SESSION in any of my Yii projects.


text:
Q: Can't import JSON with Arrays to Firebase Realtime Database I usually make a copy of a Node, with 'Export JSON', in the 3 dots menu at the top right.

Then I go to another path and Import the same JSON.
A few days ago, I remember that I could do it without problems.
Now, when I try to Import the JSON from one Node to another Node, it says that it contains "[" "]" and it can't import because of that.
I know that Firebase transforms arrays into Objects with number keys like
{0: "value", 1: "value"}.... but when I export the database, it gives me a Json with Arrays... that the same Firebase don't accept when I try to import in another part of the database.
How could I transform this JSON with arrays to be accepted by Firebase again?

A: I would advise you to transform your data like this:
"productos" {
    "productoUid" : {
       "cor" : "preto",
       "modelo" : "SJ53SA" ,
       "tamanho" : "PP",
       "tipo" : "remover",
       //this is same uid as productoUid
       "uid" : SJ54SApretoM"
    },
    "productoUid2": {/* product item*/}, ....
}

This way you'll be able to iterate through all children of productos node and add them to list. This solution is easier to maintain the keeping the data in an array.
Here and here you can read why in Firebase real-time database storing data in an array is bad practice.


text:
Q: Use of PHP generated sites in SEO? I've got a site that is based around a contact form. This form is generated according to the variables passed in the URL, and the information passed is put in headers in the body, and also in the title. Additionally images are customized, so basically the whole content is changed according to these variables.
So I've run a sitemap generator, and it's actually generated lots of these www.site.tld/me.php?a=hi&b=pie, www.site.tld/me.php?a=hi&b=chocolate, www.site.tld/me.php?c=hi&hello.... you get the point.
So, my question is: is it smart to use this to my advantage, include these in the sitemap and customize them for SEO, or should I just ignore it and omit it from the sitemap?

A: In general having dynamic urls is okay, but you don't necessarily want them indexed for SEO purposes. In general its better to have a well organized url structure, as its seen to be more appealing. (i.e. site.com/article/sports/baseball123 is better than site.com?id=123433). So depending on your content (whether its static or dynamic) you may want to move to that type of a url structure, and have your pages indexed. On the other hand if you need to keep dynamic urls (for some reason) and depending on the nature of the content, it may be best to leave them out of the equation from an SEO perspective. It ultimately comes down to what you're serving from these pages.

A: Search engine friendly urls by using apache rewrite module search apache mod_rewrite in google there are many ways to do this and there are some ways that work much better than others. Google will index your site based on the content on the page rather than the url or any meta information. Using the mod rewrite makes it easier for your viewers but as far as search engines are concerned it dont really matter. Hope this helps


text:
Q: Google Cloud SDK 0.9.39 still fails to do setup-managed-vms I just updated my gcloud components on my OS X Mavericks laptop, so now I have:
$ gcloud version
Google Cloud SDK 0.9.39

$ boot2docker version
Boot2Docker-cli version: v1.3.2
Git commit: e41a9ae

I was hoping managed vms setup would work, but alas:
$ gcloud preview app setup-managed-vms
Select the runtime to download the base image for:
 [1] Go
 [2] Java
 [3] Python27
 [4] All
Please enter your numeric choice (4):  2

Pulling base images for runtimes [java] from Google Cloud Storage
Pulling image: google/appengine-java
Traceback (most recent call last):
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/gcloud/gcloud.py", line 175, in <module>
    main()
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/gcloud/gcloud.py", line 171, in main
    _cli.Execute()
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/calliope/cli.py", line 385, in Execute
    post_run_hooks=self.__post_run_hooks, kwargs=kwargs)
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/calliope/frontend.py", line 274, in _Execute
    pre_run_hooks=pre_run_hooks, post_run_hooks=post_run_hooks)
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/calliope/backend.py", line 928, in Run
    result = command_instance.Run(args)
  File "/Users/hussein/google-cloud-sdk/lib/googlecloudsdk/appengine/app_commands/setup_managed_vms.py", line 39, in Run
    args.image_version)
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/appengine/lib/images/pull.py", line 54, in PullBaseDockerImages
    util.PullSpecifiedImages(docker_client, image_names, version, bucket)
  File "/Users/hussein/google-cloud-sdk/./lib/googlecloudsdk/appengine/lib/images/util.py", line 232, in PullSpecifiedImages
    'Error pulling {image}: {e}'.format(image=image_name, e=e))
googlecloudsdk.appengine.lib.images.util.DockerPullError: Error pulling google/appengine-java: 500 Server Error: Internal Server Error ("Invalid registry endpoint "http://localhost:49153/v1/". HTTPS attempt: Get https://localhost:49153/v1/_ping: read tcp 127.0.0.1:49153: connection reset by peer. HTTP attempt: Get http://localhost:49153/v1/_ping: read tcp 127.0.0.1:49153: connection reset by peer")

I'm very new to Docker and managed vas, and I'm wondering if the issue is due to my boot2docker port forwarding setup. My env is setup correctly I think;
$ env | grep DOCKER
DOCKER_HOST=tcp://192.168.59.103:2376
DOCKER_TLS_VERIFY=1
DOCKER_CERT_PATH=/Users/h/.boot2docker/certs/boot2docker-vm

With the docker host IP being:
$ boot2docker ip
docker@localhost's password:

The VM's Host only interface IP address is: 192.168.59.103

Finally, the containers on my system so far are:
$ docker ps -a
CONTAINER ID        IMAGE                             COMMAND             CREATED               STATUS                           PORTS                    NAMES
73c6d317a631        google/docker-registry:latest     "./run.sh"          2 minutes ago           Exited (-1) About a minute ago                            goofy_archimedes
40b709d6fa00        gcloud-credentials-image:latest   "/true"             2 minutes ago       Exited (0) 2 minutes ago                                  gcloud-credentials-1417828737.2
a3073bc56ff2        google/docker-registry:latest     "./run.sh"          47 hours ago        Exited (-1) 47 hours ago                                  distracted_bell
1b6fe130af45        11cd171d89b3                      "/true"             47 hours ago        Exited (0) 47 hours ago                                   gcloud-credentials-1417707423.48
28c181e66b11        google/docker-registry:latest     "./run.sh"          2 days ago          Exited (0) 4 minutes ago         0.0.0.0:5000->5000/tcp   elegant_darwin

Then why is gcloud python script trying to access the registry on localhost? Someone, please show me the light!


text:
Q: PHP session not being unset on new server I recently moved to a new DigitalOcean VPS server, and I'm running Ubuntu 14.04 and Apache. This is the first time I set up my own server. I imported my website into the new server. Everything seems to be working but the logout script where I basically unset and destroy the session. For some reason, this doesn't seem to be working anymore.
Here's the code for my logout script
<?PHP
session_start();
session_unset();
session_write_close();
session_destroy();

session_start();
$_SESSION = array();
$_SESSION['logged_out'] = 1;
header ("Location:index.php");
?>

When the page is redirected, the user is still logged in and the session cookie is still set.

A: I remember having the same problem as you.
Try to delete your SESSION using : unset($_SESSION['session_you_need_to_destroy']);
I guess if you destroy only one session, you member will be log off.
Hope it's work for you :)

A: Just for anyone else's future reference, I solved the problem. The URL for the login script was http://website.com (without the www) and the rest of my site used http://www.website.com (with the www).


text:
Q: Coverting sort function to assembly How exactly do I convert this C program into assembly code? I am having a hard time understanding this process or how to even start it. I am new to this. Any help would be appreciated!
 int cmp(char *str1, char *str2){
     while(*str1 && (*str1 == *str2)){
         str1++;
         str2++;
     }
     return *str1 - *str2;
 }

void sort(char **list, int n){
   int sorted=0, i=1, j;
    char *temp;
    while(i < n && !sorted){
         j=0;
         sorted = 1;
         while(j<n-i){
             if(cmp(list[j], list[j+1]) > 0){
                 temp = list[j];
                 list[j] = list[j+1];
                 list[j+1] = temp;
                 sorted = 0;
             }
             j++;
         }
         i++;
     }
 }


text:
Q: how do i check smtp server is connected or not? I am having two smtp. I want to send newsletter through smtp from two systems. If the one system is already established smtp connection then how do i know the established smtp from the other system?
any idea?

A: Check in your php.ini file following setting and set accordingly
   http://php.net/smtp
   SMTP = localhost;
    http://php.net/smtp-port
    smtp_port = 25


text:
Q: How to display pdf files in react js I am trying to display pdf files in the application. When I am uploading files and before uploading, I am showing preview using  tag and it is displaying properly. But when I am receiving data from the backend, that time I am showing all the media, everything is getting displayed properly, e.g. images and videos. But when I am adding documents into  tag, white space is displayed.
Code for preview :

            {data.documents &&
              data.documents.map((doc, id) => (
                <Card>
                  <CardHeader
                    action={
                      <IconButton
                        style={{ float: "right" }}
                        onClick={(doc) =>
                          dispatch({ type: USER_DOCUMENT_DELETE, payload: id })
                        }
                      >
                        <CloseRounded color="secondary" />
                      </IconButton>
                    }
                  />

                  <iframe
                    width="200"
                    height="150"
                    title={doc.url}
                    src={doc.url}
                  />
                  <CardContent>
                    <Typography>{doc.name}</Typography>
                  </CardContent>
                </Card>
              ))}

code for displaying data:

   {reducedDocuments &&
              reducedDocuments.map((document) => (
                <Card
                className={classes.postMedia}
                onClick={() => {
                  dispatch({
                    type: SHOW_POST_MEDIA_PREVIEW,
                    payload: {
                      id: post.id,
                      showPreview: true,
                    },
                  });
                }}>
                   <iframe

                    src={process.env.REACT_APP_BACKEND_FILE_PREVIEW + document.file_name}
                  />

                </Card>
              ))}

for src I have given the .env variable, I am receiving an array of objects with filename, which contains the path to the backend folder's media folder and specific file name.

A:

<object width="100%" height="400" data="Put your pdf url here" type="application/pdf">   </object>

You can use <object> tag to render a pdf file.
https://www.w3schools.com/tags/tag_object.asp


text:
Q: WCF MessageContract formatting issue I have a problem of WCF definition of MessageContact and client calling function.
Scenario; Client called the service with a string type reference ID and server responds instance of type of AudioObject. AudioObject consists of Stream as MessageBodyMember and FormatObject as a MessageHeader.
Following is WCF code snippet.
[ServiceContract]
public interface IAudioStreamService
{
    [OperationContract]
    AudioObject GetAudioDataStream(StringMessage RefID);
}

//StringMessageContract
[MessageContract]
public class StringMessage
{
    [MessageBodyMember]
    public string Name;
}

[MessageContract]
public class AudioObject
{
    Stream _audioStream;
    AudioFormat _audioFormat;

    [MessageBodyMember (Order=1)]
    public Stream AudioStream
    {
        get { return _audioStream; }
        set { _audioStream = value; }
    }

    [MessageHeader(MustUnderstand=true)]
    public AudioFormat AudioFormat
    {
        get { return _audioFormat; }
        set { _audioFormat = value; }
    }
}

[DataContract]
public class AudioFormat
{
    int _nChannels;
    int _nKilloBitsPerSec;
    int _nSamplesPerSec;

    [DataMember(Name="nChannels", Order=0, IsRequired=true)]
    public int nChannels
    {
        get { return _nChannels; }
        set { _nChannels = value; }
    }
    [DataMember(Name = "nKilloBitsPerSec", Order = 1, IsRequired = true)]
    public int nKilloBitsPerSec
    {
        get { return _nKilloBitsPerSec; }
        set { _nKilloBitsPerSec = value; }
    }
    [DataMember(Name = "nSamplesPerSec", Order = 2, IsRequired = true)]
    public int nSamplesPerSec
    {
        get { return _nSamplesPerSec; }
        set { _nSamplesPerSec = value; }
    }
}

The client side code is as follows,
BasicHttpBinding binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = 176160768;
EndpointAddress endpointAddress = new EndpointAddress("URLToService");
AudioStreamServiceClient client = new AudioStreamServiceClient(binding,
endpointAddress);
    AudioFormat audioFormat = client.GetAudioDataStream("000", out serverStream);

The above code is worked fine. But the issue is,
In order to the format of the OperationContract, I expected the client code as follows,
AudioObject audioObject = client.GetAudioDataStream("0000");

But my ServiceReference generated the client-stub other way round(as shown in code). Can anybody explain me the reason for this matter.

A: Either write a client yourself by deriving a class from ClientBase or write an extension method with the method signature of your choice.


text:
Q: How to use category image in detail page? I need to display relevant category image alongside product detail page. I need to display product's sub category image. Im using custom phtml file to display logo image on top of/before the product name. (image location)
My categories are like this,
Category one
Category two
Category three
each category has a few manufacturers as sub categories. I need to display that manufacturer logo image on product's detail page.
I tried using module_catelog/templates/category/image.phtml but it shows some errors on this line of code.
$_imgUrl = $_category->getImageUrl()

How can I get the category image URL in my phtml file?

A: You'll need to update template files to show the manufacturer(s) logo.
Open template/catalog/product/view.phtml
=> If you want to display manufacturer image:
<?php
     $_product = $this->getProduct();
     $manufacturerName = $_product->getAttributeText('manufacturer');
     $manufacturerId = $_product->getManufacturer();
     echo '' ?>
     <img src="../media/catalog/brands/<?php echo str_replace(' ', '_',$manufacturerName); ?>.png" alt="<?php echo $manufacturerName; ?>" />

Manufacturer images in this example are relative to /media/catalog/brands/
=> If you want to Display Category Image :
<?php $categoryImage = Mage::getModel('catalog/layer')->getCurrentCategory()->getThumbnail(); //Get the file name of the Image stored for the category ?>

<img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$categoryImage  ?>" />

A: If(Mage::registry('current_catgory')){
    $Cat=Mage::getModel('catalog/category')->load(Mage::registry('current_catgory'));
    $name=$Cat->getName();
    $thum=  Mage::getBaseUrl('media').'catalog/category/'.$Cat->getData('thumbnail');
}

This code is work if you coming to product page from category page.


text:
Q: What is "VDCI" in terms of output voltage? I am trying to bring back an old monochrome plasma screen from the dead.  I have little information on the device, its from a Compaq Portable (Luggable) III PC.  The manual for the unit lists power supply output specs as follows:
+5.0 VDC
+12.0 VDC
-12.0VDC
+200VDCI
5.0VDCI

That is exactly whats printed in the manual (minus a few columns about min. current, avg. current, and tolerance), not sure why the one "5VDCI" line doesn't have a "+" in front of it.
But more importantly, I have no idea what "VDCI" means.  Is this some old notation (the manual has 1987 as a first print date)? Is this just a typo? Is it some term I have never heard of before? Or is it absolutely nothing at all and simply means volts DC?
Alternatively, if someone manages to hunt down operating specs of the LCD in there, that would be just as awesome.  I've put many hours in to figuring out what I have thus far.

A: From a bit of Googling, it seems that this is terminology used in voltage source devices to mean VDC from an inverter. I'd guess that the lack of a + in front of the 5.0V is just a typo.
That being said, it may also be that they OCR'ed the data from a PDF, and it mistook a close-bracket as an 'I', i.e. "Something (+200VDC)" became "Something +200VDCI".


text:
Q: How to map atan2() to degrees 0-360 atan2(y, x) has that discontinuity at 180° where it switches to -180°..0° going clockwise.
How do I map the range of values to 0°..360°?
here is my code:
CGSize deltaPoint = CGSizeMake(endPoint.x - startPoint.x, endPoint.y - startPoint.y);
float swipeBearing = atan2f(deltaPoint.height, deltaPoint.width);

I'm calculating the direction of a swiping touch event given the startPoint and endPoint, both XY point structs. The code is for the iPhone but any language that supports atan2f() will do.

A: (x > 0 ? x : (2*PI + x)) * 360 / (2*PI)

A: This is what I normally do:
float rads = atan2(y, x);
if (y < 0) rads = M_PI*2.f + rads;
float degrees = rads*180.f/M_PI;

A: Add 360° if the answer from atan2 is less than 0°.

A: Or if you don't like branching, negate the two parameters and add 180° to the answer.
(Adding 180° to the return value puts it nicely in the 0-360 range, but flips the angle. Negating both input parameters flips it back.)

A: An alternative solution is to use the mod () function defined as:
    function mod(a, b) {return a - Math.floor (a / b) * b;}
Then, with the following function, the angle between ini(x,y) and end(x,y) points is obtained. The angle is expressed in degrees normalized to [0, 360] deg. and North referencing 360 deg.
    function angleInDegrees(ini, end) {
        var radian = Math.atan2((end.y - ini.y), (end.x - ini.x));//radian [-PI,PI]
        return mod(radian * 180 / Math.PI + 90, 360);
    }

A: angle = Math.atan2(x,y)*180/Math.PI;

I have made a Formula for orienting angle into 0 to 360
angle + Math.ceil( -angle / 360 ) * 360;

A: @erikkallen is close but not quite right.
theta_rad = atan2(y,x);
theta_deg = (theta_rad/M_PI*180) + (theta_rad > 0 ? 0 : 360);

This should work in C++: (depending on how fmod is implemented, it may be faster or slower than the conditional expression)
theta_deg = fmod(atan2(y,x)/M_PI*180,360);

Alternatively you could do this:
theta_deg = atan2(-y,-x)/M_PI*180 + 180;

since (x,y) and (-x,-y) differ in angles by 180 degrees.

A: double degree = fmodf((atan2(x, y) * (180.0 / M_PI)) + 360, 360);

This will return degree from 0°-360° counter-clockwise, 0° is at 3 o'clock.

A: A formula to have the range of values from 0 to 360 degrees.
f(x,y)=180-90*(1+sign(x))* (1-sign(y^2))-45*(2+sign(x))*sign(y)
     -(180/pi())*sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))

A: I have 2 solutions that seem to work for all combinations of positive and negative x and y.
1) Abuse atan2()
According to the docs atan2 takes parameters y and x in that order. However if you reverse them you can do the following:
double radians = std::atan2(x, y);
double degrees = radians * 180 / M_PI;
if (radians < 0)
{
    degrees += 360;
}

2) Use atan2() correctly and convert afterwards
double degrees = std::atan2(y, x) * 180 / M_PI;
if (degrees > 90)
{
    degrees = 450 - degrees;
}
else
{
    degrees = 90 - degrees;
}

A: Solution using Modulo
A simple solution that catches all cases.
degrees = (degrees + 360) % 360;  // +360 for implementations where mod returns negative numbers

Explanation
Positive: 1 to 180
If you mod any positive number between 1 and 180 by 360, you will get the exact same number you put in. Mod here just ensures these positive numbers are returned as the same value.
Negative: -180 to -1
Using mod here will return values in the range of 180 and 359 degrees.
Special cases: 0 and 360
Using mod means that 0 is returned, making this a safe 0-359 degrees solution.

A: @Jason S: your "fmod" variant will not work on a standards-compliant implementation.  The C standard is explicit and clear (7.12.10.1, "the fmod functions"):

if y is nonzero, the result has the same sign as x

thus,
fmod(atan2(y,x)/M_PI*180,360)

is actually just a verbose rewriting of:
atan2(y,x)/M_PI*180

Your third suggestion, however, is spot on.

A: Here's some javascript.  Just input x and y values.
var angle = (Math.atan2(x,y) * (180/Math.PI) + 360) % 360;

A: The R packages geosphere will calculate bearingRhumb, which is a constant bearing line given an origin point and easting/northing. The easting and northing must be in a matrix or vector. The origin point for a wind rose is 0,0. The following code seems to readily resolve the issue:
windE<-wind$uasE
windN<-wind$vasN
wind_matrix<-cbind(windE, windN)
wind$wind_dir<-bearingRhumb(c(0,0), wind_matrix)
wind$wind_dir<-round(wind$wind_dir, 0)

A: theta_rad = Math.Atan2(y,x);
if(theta_rad < 0)
  theta_rad = theta_rad + 2 * Math.PI;    //if neg., add 2 PI to it
theta_deg = (theta_rad/M_PI*180) ;        //convert from radian to degree

//or
theta_rad = Math.Atan2(y,x);
theta_rad = (theta_rad < 0) ? theta_rad + 2 * Math.PI : theta_rad;
theta_deg = (theta_rad/M_PI*180) ;

-1 deg becomes (-1 + 360) = 359 deg
-179 deg becomes (-179 + 360) = 181 deg

A: For your application I suspect you don't need exact degrees and would prefer a more approximate compass angle, eg 1 of 16 directions?  If so then this code avoids atan issues and indeed avoids floating point altogether.  It was written for a video game so uses 8 bit and 16 bit integers:
/*

                                           349.75d         11.25d, tan=0.2034523
                                              \             /
                                               \   Sector  /
                                                \    0    /  22.5d tan = ?2 - 1
                                             15      |      1   33.75
                                                     |         /   45d, tan = 1
                                        14           |            2 _56.25
                                                     |             /  67.5d, tan = 1 + ?2
                                     13              |               3
                                                     |                __ 78.75
                                                     |
                                    12---------------+----------------4 90d tan = infty
                                                     |                __ 101.25
                                                     |
                                     11              |               5
                                                     |
                                        10           |            6
                                                     |
                                             9       |      7
                                                     8

*/

// use signs to map sectors:
static const int8_t map[4][5] = {  /* +n means n >= 0, -n means n < 0 */
  /* 0: +x +y */ {0, 1, 2, 3, 4},
  /* 1: +x -y */ {8, 7, 6, 5, 4},
  /* 2: -x +y */ {0, 15, 14, 13, 12},
  /* 3: -x -y */ {8, 9, 10, 11, 12}
};

int8_t sector(int8_t x, int8_t y) { // x,y signed in range -128:127, result 0:15 from north, clockwise.
  int16_t tangent; // 16 bits
  int8_t quadrant = 0;
  if (x > 0) x = -x; else quadrant |= 2; // make both negative avoids issue with negating -128
  if (y > 0) y = -y; else quadrant |= 1;
  if (y != 0) {
    // The primary cost of this algorithm is five 16-bit multiplies.
    tangent = (int16_t)x*32;   // worst case y = 1, tangent = 255*32 so fits in 2 bytes.
    /*
       determine base sector using abs(x)/abs(y).
       in segment:
           0 if         0 <= x/y < tan 11.25   -- centered around 0     N
           1 if tan 11.25 <= x/y < tan 33.75   --                 22.5  NxNE
           2 if tan 33.75 <= x/y < tan 56.25   --                 45    NE
           3 if tan 56.25 <= x/y < tan 78.75   --                 67.5  ExNE
           4 if tan 78.75 <= x/y < tan 90      --                 90    E
    */
    if (tangent > y*6  ) return map[quadrant][0]; // tan(11.25)*32
    if (tangent > y*21 ) return map[quadrant][1]; // tan(33.75)*32
    if (tangent > y*47 ) return map[quadrant][2]; // tan(56.25)*32
    if (tangent > y*160) return map[quadrant][3]; // tan(78.75)*32
    // last case is the potentially infinite tan(90) but we don't need to check that limit.
  }
  return map[quadrant][4];
}


text:
Q: Background Image is not responsive and stretched in reactjs and tailwindcss I have created this one of the challenges from frontend-mentor that is of a farm-fruits, i did everything correct except for the home page background image. The code for Home.js is following:
import { useState } from "react"
import headimgd from '../assets/images/desktop/image-header.jpg'
import headimgm from '../assets/images/mobile/image-header.jpg'
import hamburger from '../assets/images/icon-hamburger.svg'
import arrow from '../assets/images/icon-arrow-down.svg'

const Navbar = () => {

    const [navBarOpen, setNavBarOpen] = useState(false)

    const handleOpen = () => {
        setNavBarOpen(!navBarOpen)
    }

  return (

sunnyside

              <button onClick={handleOpen} className="relative">
                  {navBarOpen ?

About

Services

Projects

 Contact

                      :

                  }

              </button>

About

Services

Projects

Contact

We are creatives

  )
}

export default Navbar

The images below this home page are over the homepage bg-image,i lack css tbh, attaching the screenshot of the build:

the egg and its description are separate section i am not sure where i made the mistake and egg and description need to be in opposite places egg-right descrip-left just like in design but this is my first time working with responsive pages. Attaching the og design

also if you could help me about css i mean where can i learn it better tried w3schools wasnt effective for me
thanks in advance <3

A: I made a mistake while making it responsive just incase if you are a newbie to working with responsive pages using tailwind css do not mix desktop version images with mobile version images. the little changes are as followed:
import React from 'react'
import egg from '../assets/images/mobile/image-transform.jpg'
import eggd from '../assets/images/desktop/image-transform.jpg'
import standm from '../assets/images/mobile/image-stand-out.jpg'
import standd from '../assets/images/desktop/image-stand-out.jpg'
import graphicm from '../assets/images/mobile/image-graphic-design.jpg'
import graphicd from '../assets/images/desktop/image-graphic-design.jpg'
import photographym from '../assets/images/mobile/image-photography.jpg'
import photographyd from '../assets/images/desktop/image-photography.jpg'

const Body = () => {
  return (

    {/* ---------- TRANSFORM YOUR BRAND ------------ */}

        Transform your brand

        We are a full-service creative agency specializing in helping brands
        grow fast. Engage your clients through compelling visuals that do
        most of the marketing for you.

        <button className="uppercase font-fraunces pt-8 border-b-8 border-yellow-200 rounded font-bold tracking-wide text-desBlue">
          Learn More
        </button>

  <img
  src={eggd}
  alt="egg"
  className="hidden md:flex w-full"

do not forget comments as you would look clearly i was adding mobile image with (m) on desktop version


text:
Q: Can I extend viewWillAppear in UIViewController? I am looking for a way to extend the implementation of the function viewWillAppear from UIViewController class to make it print the class name of the view called everytime this function is called.
I know it's not possible to override functions in extensions so I wonder if there is any way to do something like this.

A: Ok, after finding this http://nshipster.com/swift-objc-runtime/ I tried something similar and could achieve the desired result.
The code looks like:
extension UIViewController {
public override class func initialize() {
    struct Static {
        static var token: dispatch_once_t = 0
    }

    // make sure this isn't a subclass
    if self !== UIViewController.self {
        return
    }

    dispatch_once(&Static.token) {
        let originalSelector = #selector(UIViewController.viewWillAppear(_:))
        let swizzledSelector = #selector(UIViewController.nsh_viewWillAppear(_:))

        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)

        let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

        if didAddMethod {
            class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod)
        }
    }
}

// MARK: - Method Swizzling

func nsh_viewWillAppear(animated: Bool) {
    self.nsh_viewWillAppear(animated)
    NSLog("viewWillAppear: \(self)")
}
}

A: Swift 5
@objc func newViewWillAppear(_ animated: Bool) {
    self.newViewWillAppear(animated) //Incase we need to override this method
    let viewControllerName = String(describing: type(of: self)).replacingOccurrences(of: "ViewController", with: "", options: .literal, range: nil)
    print("Swizzled viewWillAppear", viewControllerName)
}

static func swizzleViewWillAppear() {
    //Make sure This isn't a subclass of UIViewController, So that It applies to all UIViewController childs
    if self != UIViewController.self {
        return
    }
    let _: () = {
        let originalSelector = #selector(UIViewController.viewWillAppear(_:))
        let swizzledSelector = #selector(UIViewController.newViewWillAppear(_:))
        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
        method_exchangeImplementations(originalMethod!, swizzledMethod!);
    }()
}

Then on AppDelegate:
UIViewController.swizzleViewWillAppear()


text:
Q: Dell "Rescue Disk" image size questions I used Dell's provided software for creating a "Rescue Disk" image to a 32GB USB stick for a few laptops and have backed these up using imageUSB.
Questions

*

*What is the recommended way that can be done to shrink these down since they take up 32gb each?

*Is there a better way to store these backups?

*I noticed that windows provides a mechanism for creating recovery drives. Would this solution be suitable too and provide better results?


text:
Q: Best way to reference a certain variable throughout the namespace? I have a mainForm variable that is used nearly everywhere in my program. I'd like to be able to reference to this variable without having to type the name of the class that holds this variable (i.e. instead of Global._mainForm, I should be able to just type _mainForm to access this variable anywhere within the same namespace).
What is the best way to accomplish this?

A: Anytime I see a global anything I get worried, so I would reconsider how your program is architected. You can almost always get away without having a globally accessible object. Although there are legitimate reasons to have a globally accessible object, usually I try to stay away from them.
From the little information you've given, you might be able to use events to talk to the main window instead of directly accessing it.
If you do have real need for a globally accessible object then you could do something like this
Note: In the code below everything is static, conversely you could create a special static class that holds a reference to the instance of the class you're really interested in. But there is no way that I'm aware of to hold a global reference that is outside of all namespaces to an instance of an object.
using Bar = ProbablyAReallyBadIdeaToHaveAGlobalAnythingButHeyWhyNot.TestClass;

namespace ProbablyAReallyBadIdeaToHaveAGlobalAnythingButHeyWhyNot
{
  public static class TestClass
  {
    public static int TestFoo { get; set; }
  }
}

namespace Foo.SomeOtherNamespace
{
  class MyClassThatDoesStuff
  {
    public void DoStuff()
    {
      Bar.TestFoo = 123;
    }
  }
}

A: You can't accomplish this in C#.
Namespaces are simply part of the type name of a class.  Lexically, you can think of a namespace as containing only other namespaces and classes.
Classes may contain fields, functions, events, properties, nested classes, etc., but not nested namespaces.
Therefore there is no way to to define a symbol in a namespace outside of class that aliases or refers to a symbol contained in a specific class.
When resolving the reference to the variable name _mainForm, the only place that it does not require additional qualification is from within the scope of the class that it is defined in.
If you are in a namespace scope that is the same as as the class that defines _mainForm (and _mainForm is a static instance), then you only need access it by qualifying it with the class name.  Otherwise you will require additional namespace qualification, or perhaps trickery with a using directive.  But outside of the containing class, you will always require a qualification of some kind to access _mainForm.
See http://en.csharp-online.net/ECMA-334:_10.7_Scopes for excruciating detail.

A: The only way I can see, in C#, for every class in a namespace to be able to directly address the same variable is by defining the variable as static in a base class used by all other classes in the namespace.  Since static variables can be addressed as local variables within the class (or classes inheriting from) they are defined in, the variable will be available without class qualifications.
Can't say it is a good idea, but that's not what you asked ...