text:
Q: Reading a Printer Device Context in C# I am able to display and save a screen device to DIB bitmap, and I would like to do the same with a printer device context. I can get a non-null bitmap, but it is always solid black.
Here is the code that allows me to handle a screen device context.
        //In size variable we shall keep the size of the window.
        SIZE size;

        //Win32 API functions are imported in classes
        //PlatformInvokeGDI32
        //PlatformInvokeUSER32

        //Get handle of calc.exe window.
        IntPtr hwnd = PlatformInvokeUSER32.FindWindow("SciCalc", "Calculator");

        //Get window dimensions
        PlatformInvokeUSER32.RECT rect;
        PlatformInvokeUSER32.GetWindowRect(hwnd, out rect);
        size.cx = rect._Right - rect._Left;
        size.cy = rect._Bottom - rect._Top;

        //Get the device context of Calculator.
        IntPtr hDC = PlatformInvokeUSER32.GetDC(hwnd);

        //Draw on the Calculator surface.
        Graphics CalculatorGraphics = Graphics.FromHdc(hDC);
        Color colorRed = Color.FromName("Red");
        Pen penRed = new Pen(colorRed);
        CalculatorGraphics.DrawEllipse(penRed, 50, 50, 50, 50);
        CalculatorGraphics.Save();

        //Here we make a compatible device context in memory for screen device context.
        IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(hDC);

        //Create a compatible bitmap of window size and using screen device context.
        m_HBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(hDC, size.cx, size.cy);

        //As m_HBitmap is IntPtr we can not check it against null. For this purspose IntPtr.Zero is used.
        if (m_HBitmap != IntPtr.Zero)
        {
            //Here we select the compatible bitmap in memeory device context and keeps the refrence to Old bitmap.
            IntPtr hOld = (IntPtr)PlatformInvokeGDI32.SelectObject(hMemDC, m_HBitmap);
            //We copy the Bitmap to the memory device context.
            PlatformInvokeGDI32.BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, PlatformInvokeGDI32.SRCCOPY);
            //We select the old bitmap back to the memory device context.
            PlatformInvokeGDI32.SelectObject(hMemDC, hOld);
            //We delete the memory device context.
            PlatformInvokeGDI32.DeleteDC(hMemDC);
            //We release the screen device context.
            PlatformInvokeUSER32.ReleaseDC(hwnd, hDC);
            //Image is created by Image bitmap handle and returned.
            return System.Drawing.Image.FromHbitmap(m_HBitmap);
        }
        //If m_HBitmap is null retunrn null.
        return null;

Here is how I get a printer device context:
        //In size variable we shall keep the size of the window.
        SIZE size;
        size.cx = 1000;
        size.cy = 1000;

        //Get Printer Handle
        IntPtr PrinterHandle;
        PlatformInvokeGDI32.PRINTER_DEFAULTSW defaults = new PlatformInvokeGDI32.PRINTER_DEFAULTSW();
        PlatformInvokeGDI32.OpenPrinterW("Bullzip PDF Printer", out PrinterHandle, defaults);

        //Get Printer Device context
        IntPtr PrinterHDC = PlatformInvokeGDI32.CreateDCW("", "Bullzip PDF Printer", "", IntPtr.Zero);

        //Initialize DocInfo structure.
        PlatformInvokeGDI32.DOCINFOW docInfo = new PlatformInvokeGDI32.DOCINFOW();

        //Start printing.
        PlatformInvokeGDI32.StartDocW(PrinterHDC, ref docInfo);
        PlatformInvokeGDI32.StartPage(PrinterHDC);
        Graphics graphics = Graphics.FromHdc(PrinterHDC, PrinterHandle);

        Color theColor = Color.FromName("Red");
        Pen pen = new Pen(theColor);
        graphics.DrawRectangle(pen, 50, 50, 50, 50);
        graphics.DrawEllipse(pen, 50, 50, 50, 50);
        graphics.Save();

        //Here we make a compatible device context in memory for screen device context.
        IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(PrinterHDC);

        //Create a compatible bitmap of window size and using screen device context.
        m_HBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(PrinterHDC, size.cx, size.cy);

        //As m_HBitmap is IntPtr we can not check it against null. For this purspose IntPtr.Zero is used.
        if (m_HBitmap != IntPtr.Zero)
        {
            //Here we select the compatible bitmap in memeory device context and keeps the refrence to Old bitmap.
            IntPtr hOld = (IntPtr)PlatformInvokeGDI32.SelectObject(hMemDC, m_HBitmap);
            //We copy the Bitmap to the memory device context.
            PlatformInvokeGDI32.BitBlt(hMemDC, 0, 0, size.cx, size.cy, PrinterHDC, 0, 0, PlatformInvokeGDI32.SRCCOPY);
            //We select the old bitmap back to the memory device context.
            PlatformInvokeGDI32.SelectObject(hMemDC, hOld);
            //We delete the memory device context.
            PlatformInvokeGDI32.DeleteDC(hMemDC);
            //We release the screen device context.
            //PlatformInvokeUSER32.ReleaseDC(hwnd, PrinterHDC);
            //Image is created by Image bitmap handle and returned.

            PlatformInvokeGDI32.EndPage(PrinterHDC);
            PlatformInvokeGDI32.EndDoc(PrinterHDC);
            PlatformInvokeGDI32.ClosePrinter(PrinterHandle);
            pen.Dispose();
            graphics.Dispose();

            return System.Drawing.Image.FromHbitmap(m_HBitmap);
        }
        //If m_HBitmap is null retunrn null.
        return null;

How can I draw on the printer device context?
How can I save the printer device context to DIB?
Thank you,
Jacob

A: Printer device contexts are write-only.
For example, suppose you are printing to a PostScript printer.  You create a printer device context and draw some text on it.  The printer device driver does not render a bitmap containing your text.  Rather, it creates a sequence of PostScript commands to draw the text and sends the commands to the printer.  In other words, there is no bitmap to be copied.
What are you trying to achieve?


text:
Q: How to return array of user defined types, and then pass as an argument in VBA I have a User Defined Type, Decision:
Public Type Decision
    choice As String
    cost As Double
End Type

I am trying to use an array of my UDTs to store the results of a dynamic program (choice and cost for a stage/state).
Public Function DPSolve(arg1, arg2, ...) as Decision
        Dim Table() As Decision
        ReDim Table(arg1, arg2+ 1)

        'do stuff that fills each Table().choice and Table().cost

        'return Table()
        DPSolve = Table()
End Function

If I want to then pass the result of this function to a new function (to say, print the Table() in Excel, or do more work using the Table() result, how do I do this?
I am trying
Sub Main
    Dim x as variant

    x = DPSolve(arg1, arg2, ...)

    Function2(x)
End Main

but am getting the following error:

I have tried making x an array, but I get a "cannot assign to array" error. I have also tried making x a Decision, but that did not work either. The code is in a module.
Thanks!

A: So DPSolve shall return an array of Decisions. And x()shall also be an array of Decisions.
Public Type Decision
    choice As String
    cost As Double
End Type

Public Function DPSolve(arg1, arg2) As Decision()
        Dim Table() As Decision
        ReDim Table(arg1, arg2 + 1)

        'do stuff that fills each Table().choice and Table().cost

        'return Table()
        DPSolve = Table()
End Function

Sub Main()
    Dim x() As Decision

    x = DPSolve(2, 2)

End Sub

Works for me. Example:
Public Type Decision
    choice As String
    cost As Double
End Type

Public Function DPSolve(arg1, arg2) As Decision()
        Dim Table() As Decision
        ReDim Table(arg1, arg2 + 1)

        'do stuff that fills each Table().choice and Table().cost

        Table(1, 2).choice = "choice1,2"
        Table(1, 2).cost = 123.45

        'return Table()
        DPSolve = Table()
End Function

Sub Main()
    Dim x() As Decision

    x = DPSolve(2, 2)

    MsgBox x(1, 2).choice
    MsgBox x(1, 2).cost

End Sub

To be clear with "Can't assign to an array". You can't assign an type and size dimensioned and filled array to another type and size dimensioned array. But you surely can assign an filled array to an type dimensioned but not size dimensioned array.
Sub test()

 Dim arr1(3) As String
 Dim arr2() As String

 arr1(0) = "Value 0"
 arr1(1) = "Value 1"
 arr1(2) = "Value 2"
 arr1(3) = "Value 3"

 arr2 = arr1

 MsgBox Join(arr2, ", ")

End Sub

A: The error mean that you can't assign a defined type to a variant.
So you either need to have the type defined on the variable
Public Type Decision
    choice As String
    cost As Double
End Type

Public Sub DPSolve(source, arg1, arg2)
  ReDim source(arg1, arg2 + 1)
End Sub

Sub Main()
    Dim x() As Decision
    DPSolve x, 4, 4
End Sub

Or if you really want to use a variant, then you need to use a class:
Public Sub DPSolve(source, arg1, arg2)
  Dim i&, j&
  ReDim source(0 To arg1, 0 To arg2 + 1) As Decision
  For i = 0 To arg1
    For j = 0 To arg2 + 1
      Set source(i, j) = New Decision
    Next
  Next
End Sub

Sub Main()
    Dim x
    DPSolve x, 4, 4
End Sub

Class Decision:
Public choice As String
Public cost As Double

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using android:fitsSystemWindows="true/false" Navigation drawer height changing and Navigation bar becoming white I am working on UnityPlayerActivity in which camera is rendering on complete screen on top of which, having my Toolbar and Navigation drawer. So I am facing following issues as
Case A : Used android:fitsSystemWindows="false"
Shows navigation drawer but not as expected as height of drawer is not showing fullscreen.
But android navigation bar is transparent, camera is taking complete screen as
expected.
Case B : Used android:fitsSystemWindows="true"
Shows navigation drawer as expected and drawer height is showing fullscreen.
But android navigation bar is not transparent, so camera is not taking complete screen as expected.

This is my layout file

A: It is not necessary that you have to be bound with Unityplayer activity or mainActivity.
You can make any activity static and call the function or UI present in those activities from c# unity.
The correct methodology is to create a static Activity in your main Android project and call it currentActivity. After this in your oncreate method you set the currentActivity to this the following code demonstrated that:
public class MainActivity extends UnityPlayerActivity {

 public static MainActivity currentActivity;

 @Override

     public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);

         currentActivity=this;

In addition : From your Unity code you can use C# to call an Android method from the MainActivity by using the following code:
AndroidJavaClass jc = new AndroidJavaClass("yourpackagename.youractivity");

 AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");

 jo.Call("toggleMenu");

OR
You can convert UnityPlayerActivity to Fragment,link mentioned below will help you on same
How can I open an Android Fragment in a new process?


text:
Q: Rich Text fields in New Item Dialog - IE9 I had an issue with a number of things due to upgrading my web application's master page to utilize IE9 for HTML 5 and CSS 3 goodies.  The problem is this breaks a LOT of things in SharePoint 2010.
One thing in particular was the Rich Text field offered by the Calendar list type for describing an appointment.  This field, on the "New" Item form, was completely disabled until a user selected something that reloaded the dialog (like one of the checkboxes).
Below I will provide the solution.
Other issues related to this one I have tackled:
IM Presence icons not working in IE9
Context menus not working in IE9
/**** UPDATE ****/
in response to a comment below I checked the response and noticed there wasn't a block of code for the 3rd function I mentioned.  Maybe the solution works without it, maybe not!
Here's my version of RTE_GetEditorInstanceVariables():
function RTE_GetEditorInstanceVariables(strBaseElementID)
{ULS1Lu:;
    if (parent.g_oExtendedRichTextSupport != null) {
        g_oExtendedRichTextSupport = parent.g_oExtendedRichTextSupport
    }
    if (g_oExtendedRichTextSupport != null) {
        if (g_oExtendedRichTextSupport.editors[strBaseElementID] != null) {
            return g_oExtendedRichTextSupport.editors[strBaseElementID];
        }
    }
    return null;
}

A: Actually, you can set it up so that you can use the Rich Text in IE9 (some people believe you have to disable it completely)!  You just have to override 3 functions in form.js (I created a file called form.ie9fix.js) and make sure it loads AFTER the "normal" form.js (or form.debug.js, whichever).
The functions in question:
RTE_DD_GetMenuFrame()
RTE_GetEditorInstanceVariables()
RTE_GetEditorIFrame()

Each of these needs to be rewritten because it makes a call to document.frames() which is not proper notation in pretty much any browser, let alone IE9 (works in IE8-, though!).  if you're searching you can find doc.frames( and replace the () with [] and you will be fine, because this is an array reference not a function.  You can probably use this to fix the rich text issues in firefox, chrome, etc, as well.
SharePoint has a lot of cases like this and some of them are pretty hard to nail down.  This one I had to work even harder because the normal ScriptLink trick did not work.  After the main ScriptLink tag on the master page, I added the following for each script where <scriptname> is the name of the script in question.
<script type="text/javascript">
  ExecuteOrDelayUntilScriptLoaded(function(){
     document.write('<script type="text/javascript" src="/_layouts/1033/<scriptname>.ie9fix.js"></'+'script>');
     }, '<scriptname>.js');
/* rinse, repeat, for each script to be overridden */
</script>

Good luck!

*

*Matt

A: @DJ Monzyk
this is a follow up javascript file as reference in previous answer
function RTE_DD_GetMenuFrame()
{
    var ifmMenu=null;
    var elemMenu=RTE_DD_GetMenuElement();
    if (null !=elemMenu)
    {
        if (document.frames.length > 0)
        {
            ifmMenu=document.frames[g_strRTETextEditorPullDownMenuID];
        }
        else
        {
            if ((document.parentWindow !=null) && (document.parentWindow.frames !=null))
            {
                ifmMenu=document.parentWindow.parent.document.frames[g_strRTETextEditorPullDownMenuID];
            }
        }
    }
    if (null==ifmMenu)
    {
        if (g_fRTEFirstCallToGetMenu)
        {
            g_fRTEFirstCallToGetMenu=false;
            return null;
        }
    }
    return ifmMenu;
}

function RTE_GetEditorIFrame(strBaseElementID)
{
    var ifmEditor=null;
    var doc=document;
    if ((null !=doc.frames) && (doc.frames.length==0) && (doc.parentWindow.parent !=null))
    {
        doc=doc.parentWindow.parent.document;
    }
    if ((null !=doc.frames) && (doc.frames.length > 0))
    {
        var ifmContainer=doc.getElementById(RTE_GetEditorIFrameID(strBaseElementID));
        if (ifmContainer !=null)
        {
            ifmEditor=doc.frames[RTE_GetEditorIFrameID(strBaseElementID)];
        }
    }
    return ifmEditor;
}

A: Its great that you seem to have a solution for this, as I've encountered this maddening problem and am desperately trying to remedy it.  You allude to the fix, but I'm still not clear on the "HOW" aspect of it.....You identified the functions in question, and how to call the script once its ready, but I dont get the "Each of these needs to be rewritten" part...in what way?  Do you have a script you can share?


text:
Q: Why could Voldemort's memory from the diary horcrux take physical form? Why did the diary Horcrux create a fully fledged Tom Riddle who could walk and talk and stuff when no other Horcrux seemed to do that?
What was special about the diary that allowed it to do this?

A: Why did the memory inside the diary acquire a quasi physical form?
The Diary was no ordinary diary. It had the power to draw life force from a reader/writer who got emotionally attached to it and use it to create its own body. As it happened, Ginny poured her heart out to Voldemort, strengthening him and making herself vulnerable to him.
So Voldemort used Ginny's life force to create a quasi-body for him. He would have succeeded in creating a full body, Had Harry not intervened.
Voldemort did not bestow the power to draw life force to strengthen the Horcrux inside any other of his relics except the diary which is why it stands out.
What impacts the diary's success in chamber of secrets could have had, JRK had following to say, (quoted from DVK's answer):

Q: In 'Chamber of Secrets', what would have happened if Ginny had died
  and Tom Riddle had escaped the diary?
A: I can't answer that fully until all seven books are finished, but it
  would have strengthened the present-day Voldemort considerably.

A: The diary couldn't create a Tom Riddle body straight away. Like most
Horcruxes it started out looking like a normal object. Ginny then began to pour her problems into the diary and it slowly took hold of her. At this point the Horcrux began to drain Ginny's strength and used it to create Tom Riddle.
Eventually the Horcrux would have enough strength to bring Riddle back to life entirely but was stopped before this could happen. When the diary was destroyed Ginny's strength appeared to return to her. Other Horcruxes didn't have someone dependent on them in the same way so couldn't drain their strength.


text:
Q: python cv2 read video from archive I have a .tar file containing a .mp4 video. I need to open them via OpenCV (v2.4.8) in PyQt4 without extracting the archive to the file system.
Here there solution for reading images from tar
Instance:
import cv2
import numpy as np
import tarfile

tar0 = tarfile.open('files.tar')
fileg = tar0.extractfile('1.mp4')#  (may be convert fileg to VideoCapture?)


text:
Q: RxJs7 deprecated throwError I've been following the NestJS course and during the section about Interceptors we need to create a TimeoutInterceptor as so:
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(3000),
      catchError(err => {
        if (err instanceof TimeoutError) {
          return throwError(new RequestTimeoutException());
        }
        return throwError(err);
      }),
    );
  }
}

But my VSCode tells me throwError has been deprecated in RxJs v7, so I've come with the following solution:
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(3000),
      catchError((err) => {
        if (err instanceof TimeoutError) {
          throw new RequestTimeoutException();
        }

        throw new Error(err);
      }),
    );
  }
}

I haven't found anything on the NestJS documentation that seems up to date and the method still seems to work even if it's deprecated, so I was wondering if my solution is viable and safe for production environments or if should I stick to the official NestJS documentation? Or maybe there's another better solution that I just haven't found yet online...
Thanks in advance for taking the time of answering me.

A: You need to change it to.
    export class TimeoutInterceptor implements NestInterceptor {
      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        return next.handle().pipe(
          timeout(3000),
          catchError(err => {
            if (err instanceof TimeoutError) {
              return throwError(() => new RequestTimeoutException());
            }
            return throwError(() => err);
          }),
        );
      }
    }


text:
Q: Alter postgresql column from one enum type to another I have two enum types defined creation_source_enum (A1) and data_source_enum (A1, A2) as a table with this field
CREATE TABLE data (
    ..
    source creation_source_enum NOT NULL
);

I want to change the type to data_source_enum, used this command
ALTER TABLE data
   ALTER COLUMN source TYPE data_source_enum
    USING source::data_source_enum;

But getting this error
ERROR: cannot cast type creation_source_enum to data_source_enum Position: 95; SQLState: 42846

What am I doing wrong?


text:
Q: show two table side by side on top and float second table up in html I have two tables and I want them to appear side by side thus I used prop in CSS (display: inline-block;);
But the problem is the second table is floated at the bottom where the first table is ending. i.e both 1st and 2nd table bottom is coming at same line,
whereas I want the 1st line of both tables to appear on the same line.
(display: inline-block;)

A: Not entirely sure what you're asking, but make sure the tables aren't too big to be floated together. Here is an example:

body {
  padding: 0;
  margin: 0;
}
table {
  width: 50vw;
  background-color: blue;
  height: 50vw;
  outline: 1px solid black;
  float: left;
}

table:nth-of-type(1) tr {
  width: 30vw;
  background-color: red;
  height: 10vw;
  outline: 1px solid black;
}

table:nth-of-type(2) tr {
  width: 30vw;
  background-color: yellow;
  height: 10vw;
  outline: 1px solid black;
}

A: You can create like this to side by side table.
Following an example
jsfiddle example
jsfiddle

.left {
  display: inline-block;
}

.right {
  display: inline-block;
}

      HELLO
      HELLO
      HELLO

      HELLO
      HELLO
      HELLO


text:
Q: rails3 model question i moved from php to rails3, and i still think it was a good decision! Anyway I have some models:
users
questions
answers
question_id
votes
user_id
answer_id

model for users:
has_many :questions
has_many :votes

model for questions:
belongs_to :user
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? }, :allow_destroy => true

model for answers:
belongs_to :question
has_many :users, :through => :votes, :dependent => :destroy
has_many :votes

model for votes:
belongs_to :answer
belongs_to :user

Now my question, once a user has voted on an answer, the voting for that user and for that specific question should be closed...
I use devise and cancan for users and authorization in the rest of my project...
In my view it should look something like:
<% unless current_user.question_answered.include? question %>

and then do the script where i render the vote buttons...
In my votes model i have an
answer_id and a user_id, i know the
current_user.id and the current question.id
so if the vote.user_id has the vote.answer_id that is in the current question.id than it shouldn't render my button making script...  aarghh but how to put this to work...?
Thanks very much in advance!
And best regards,
Thijs

A: I would personally go outside of devise and write my own method. I think it's a little cleaner and easier to understand. You'll also guarantee with this method that you are only performing  a single fast query to your DB. By asking current_user.questions_answered you are querying the database for all questions that a user has answered, which is potentially a much larger result set than checking if the user has voted on the current question:
class User
  def can_vote_on? question
    !question.answers.joins(:votes).where('votes.user_id = ?', id).exists?
  end
end

You can then adjust your view to:
<% if current_user.can_vote_on?(question) %>

A: in ability write something like this
can :vote, Answer, :votes => { :users => user }

in your view do something like
<% if can? :vote, Answer %>

(i cant really test it right now so let me know if it works)


text:
Q: Does anyone know the name of this template? Although I like LaTeX, I am a bit bored of the default template and would like to use something looking more like this:
http://www.ens-lyon.fr/DSM/SDMsite/M2/stages_M2/Debierre2012.pdf
Does anyone the name of this specific template? Or something looking alike?

A: I don't know if there is a specific template that looks like that, but if you do the titlepage yourself, having
\usepackage[margin=2cm]{geometry}
\usepackage{mathptmx}
\usepackage[T1]{fontenc}

\usepackage{fancyhdr}
\pagestyle{fancy}

should give you something close.


text:
Q: Why is my json not appearing in my params? In my Rails app, I have:
routes.rb:
  resources :tasks, :defaults => {:format => 'json'}, :except => [:index, :new, :create, :show, :edit, :update, :destroy] do
    member do
      get :to_chrome
      post :from_chrome
    end
  end

mime_types.rb:
Mime::Type.register "application/xls", :xls
Mime::Type.register "application/json", :json

tasks_controller.rb:
class TasksController < ApplicationController

  skip_before_action :verify_authenticity_token, if: :json_request?

  def to_chrome
    @survey = Survey.find(params["id"])
      @survey = Survey.last
      respond_to do |format|
        format.json {render_for_api :private, :json => @survey}
      end
    end
  end

  def from_chrome
    binding.pry_remote
    render :nothing => true
  end

  protected

  def json_request?
    request.format.json?
  end

end

to_chrome is working fine.
I'm trying to trigger from_chrome from Postman with the following settings:
URL: http://localhost:3000/tasks/2452456/from_chrome
Verb: Post
Body: "John Rambo", time:"2pm"
(have also tried wrapping the entire string in single quotes)
Body format: raw JSON (application/json)
Header 1: Accept: application/json
Header 2: Content-Type: application/json
In Postman, I'm getting back a 200 response.
But in Rails, when I inspect params inside from_chrome, I just see:
{"format"=>"json", "controller"=>"tasks", "action"=>"from_chrome", "id"=>"2452456"}

Where's my Json?
Thanks,
Steven.

A: Never mind. I just found the json in request.body.read.


text:
Q: Django Newbie Question: Activation View Being Called Twice ... 99% of the time - Invalid token error Hi and thank you for looking at my question.
When a user clicks activation link in their email, they get a token invalid error page.  The user is activated and can use the site.
After adding debugging I see that the activation view is being called twice. The first time it works as expected, but the second time the activation key no longer exists so there is an error.
Just to make thing more complicated, it does work once in a very blue moon.
Why would this happen? How can I prevent this from happening?
Thanks!

A: For anyone who comes upon this post:
I added a session variable when the activation is true, and then checked for it in the beginning of the function, if so redirect to the appropriate url.
This solved the problem.


text:
Q: #Deleted for values of a linked Oracle table in MS Access I've created a simple table in Oracle 12c like so:
CREATE TABLE TEST
(
ID NUMBER GENERATED ALWAYS AS IDENTITY,
TEXT VARCHAR2(2000 CHAR),
CONSTRAINT ID_PK PRIMARY KEY (ID)
);

Then I linked it in MS Access using ODBC driver. The problem is that when I input value into TEXT and click away both ID and TEXT show #Deleted. My value gets recorded in the database but I have to requery in MS Access in order to see it.
I also noticed that if I change the datatype of TEXT field to NUMBER, it works fine. After saving the record in MS Access both auto generated ID and value in TEXT field are there. I don't have to requery anything.
This happens only when inserting. Updating works just fine.
Please advise.

A: So, it would appear you already found the solution, but this is more of an explanation as to why it works that way. Simply speaking, if the base-table uses non-integer values as primary keys, Access rounds these integers to the nearest whole number and then (since it was not a numeric value) Access can no longer find the applicable records. So, changing the data type from TEXT to INTEGER in the table structure would give you your desired result.
Alternatively, if you're using a query to run through these, if you cannot change the keys in the Oracle table then altering the Access query type to a snapshot (in the query properties) will also bypass this problem. But from the sounds of it, this is not how you are utilizing the data.

A: In my case, the Oracle ODBC driver (using the rather old version 11.02.00.01 that otherwise works ok and Microsoft Access 2016 32Bit) seems to use the unique indices and not the primary key constraint for determining the primary key.
I had a field with NUMBER(11) as PK with an unique index, then added a VARCHAR2 field with another unique index. The name of the index of the VARCHAR2 field was alphabetically before that of the NUMBER field.
Now, the linked table in Microsoft Access showed the VARCHAR2 field as primary key and I had the problem with '#Deleted' appearing after entering & saving a record as you describe.
After renaming the unique index on the NUMBER field in Oracle to be alphabetically before that of the VARCHAR2 field and re-linking the table in Microsoft Acces, the NUMBER field was the primary key again in Microsoft Access and the '#Deleted' problem was solved.


text:
Q: Styling elements within a jQuery UI dialog I have am attempting to add some input fields to a jquery ui dialog box and am having trouble applying styles to them.
Currently I have something like this:

<fieldset>
    <legend>Add a New Client</legend>

Code<input class="input-md" type="text" id="clientCode" name="Code" disabled="true" />

Client Name<input class="input-md required" type="text" id="ClientName" name="ClientName" />

</fieldset>

The css I have to style this is not getting picked up.  If I move the fields to just display on the page (not in the dialog) then the styles I have applied to left-lbl, right-lbl, etc. get picked up fine.
If I examine the dialog in firebug the styles are there on the elements but do not show as having been applied.  Is there something I need to do specific to jquery ui to make this work?

A: Ok, problem solved. This was just a stupid mistake on my part.  I had the style applied to all class within  a wrapper div on my page but the dialog's div is declared outside of the wrapper and so it wasn't picking them up.
#wrap label.left-lbl

instead of just
label.left-lbl


text:
Q: How do I localize web part title? I'm adding a bunch of web parts to a page using a module like this:
    <AllUsersWebPart WebPartZoneID="TopLeftRow" WebPartOrder="1">
    <![CDATA[
        <webParts>
          <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
            <metaData>
              <type name="SiteDef.MyTasks_wp.MyTasks_wp, SiteDef, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fppbar" />
              <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
            </metaData>
            <data>
              <properties>
                <property name="Title" type="string">$Resources:Resources,MyTasks</property>
              </properties>
            </data>
           </webPart>
        </webParts>
    ]]>
  </AllUsersWebPart>

I've deployed my resource file as a provisioning resource since runtime resources seem to have no effect. The localization works after provisioning but if I switch language the original localization is persisted.
Is there a way to localize a web part's title so that it adapts to the end user's language preferences?


text:
Q: Uncaught SyntaxError with day countdown script So I have this script that I got from a website, which I modified to the best of my limited JS knowledge. Surprisingly it did not work, as it gave an error on the line I'll highlight.
Here's the script that I put inside the  of my HTML:
<script>
  var before = "Event before"
  var current = "Today is the date set in countdown"
  var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

  function countdown(yr, m, d) {
      var today = new Date()
      var todayy = today.getYear()
      if (todayy < 1000)
        todayy += 1900
      var todaym = today.getMonth()
      var todayd = today.getDate()
      var todaystring = montharray[todaym] + " " + todayd + ", " + todayy
      var futurestring = montharray[m - 1] + " " + d + ", " + yr
      var difference = (Math.round((Date.parse(futurestring) - Date.parse(todaystring)) / (24 * 60 * 60 * 1000)) * 1)
      if (difference == 0)
        document.getElementByID("days").innerHTML = "0";
      else if (difference > 0)
        document.getElementByID("days").innerHTML = +difference + ;
    }
    //enter the count down date using the format year/month/day
  countdown(2015, 01, 01)
</script>

It's supposed to replace the contents of a bold tag inside a paragraph, but apparently the issue is with the actual script and not with the ID or the function.
Any help is much appreciated:)

A: else if (difference > 0)
    document.getElementByID("days").innerHTML = difference;


text:
Q: Laravel get/map with key I was hoping I could do this on one line:
$users = [];
$rawUsers = User::select('id','first_name','last_name')->where('company_id',Auth::user()->company_id)->get();
foreach($rawUsers as $u) {
    $users[$u['id']] = $u['first_name'].' '.$u['last_name'];
}

I see the Collection class has a ->map function which would let me do the concatenation, but I don't know how to get the results indexed by id. Is there a way to do what I want?

A: You can do this using lists method on the query:
User::select(DB::raw('concat(first_name," ",last_name) as full_name'), 'id')->lists('full_name', 'id');
// returns array(id => full_name, ...)

Or use accessor on the model and lists on the collection:
// User model
public function getFullNameAttribute()
{
    return $this->attributes['first_name'].' '.$this->attributes['last_name'];
}

// then on the collection call lists:
$usersRaw = User::where(...)->get()->lists('fullName','id');


text:
Q: Getting null value of radio button in request.getParameter() enter code hereCan you please suggest whats going wrong, I dont understand why I am getting a null value for request.getParameter("IDclass") where IDclass is the name attribute of my radio button. Following is the code, please run it and let me know. Appreciate your help.
/**
 * @see HttpServlet#HttpServlet()
 */
public Salary_Servlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //DOA data = new DOA();
    //String id = request.getParameter("IDclass").toString();
    //List<PaycheckBean> paylist = data.getpay();
    PrintWriter out = response.getWriter();
    //Gson gson = new Gson();
    //out.println(gson.toJson(paylist));
    out.print(request.getParameter("IDClass"));
}

}
and my JSP is below

<div id="div1" class="right_side">
    Hello World
</div>

<script>
$(document).ready(function(){
    $('#getdata').click(function(){
        var username = $('uname').val();
        var password = $('pword').val();
        console.log("Wekcome");
        $.ajax({
            url : 'http://localhost:8080/Practice_App/Login_Servlet',
            async : 'true',
            data : {username : name, password : password},
            type : 'POST',
            dataType : 'JSON',
            success : function(data) {
                var table = document.createElement("table");

                for(var j=0;j<data.length;j++){
                    var tableRow = document.createElement("tr");
                    var EmployeeID = document.createElement("td");
                    var radiospace = document.createElement("input");
                    radiospace.setAttribute("type", "radio");
                    radiospace.setAttribute("name", "IDclass")
                    radiospace.setAttribute("value", j);
                    var Name = document.createElement("td");
                    var Phonenumber = document.createElement("td");

                    EmployeeID.innerHTML = data[j].EmployeeID;
                    Name.innerHTML = data[j].Name;
                    Phonenumber.innerHTML = data[j].Phonenumber;
                    radiospace.innerHTML = "Hello";

                    tableRow.appendChild(EmployeeID);
                    tableRow.appendChild(Name);
                    tableRow.appendChild(Phonenumber);
                    tableRow.appendChild(radiospace);

                    table.appendChild(tableRow);

                }
                document.getElementById("tableDiv").appendChild(table);

                $('input:radio[name="IDclass"]').change(function(){
                    //var id = $('IDclass').val();
                    for(var i=0;i<data.length;i++){
                        if ($(this).is(':checked') && $(this).val() == i) {
                            // append goes here
                            console.log("You choose "+(i+1));
                            $.ajax({
                                url: "http://localhost:8080/Practice_App/Salary_Servlet",
                                async : 'true',
                                type : 'POST',
                                dataType : 'JSON',
                                success : function(data) {
                                    var table = document.createElement("table");
                                    for(var k=0;k<data.length;k++){
                                        var tableRow = document.createElement("tr");
                                        var ID = document.createElement("td");
                                        var Month = document.createElement("td");
                                        var Salary = document.createElement("td");

                                        ID.innerHTML = data[k].ID;
                                        Month.innerHTML = data[k].Month;
                                        Salary.innerHTML = data[k].Paycheck;

                                        tableRow.appendChild(ID);
                                        tableRow.appendChild(Month);
                                        tableRow.appendChild(Salary);

                                        table.appendChild(tableRow);
                                    }
                                    document.getElementById("div1").appendChild(table);
                                }
                            });
                        };
                    };
                })
            },
            error : function(e) {
                console.log(e);
            }
        });
    });
});

$("#IDsearch").keyup(function(){
     var term = $(this).val();
     if(term != ""){
         $("#tableDiv tr").hide();
         $("#tableDiv td").filter(function(){
             return $(this).text().toLowerCase().indexOf(term)>-1;
             }).parent("tr").show();
     }
     else
         {
         $("#tableDiv table>tr").show();
         }

  });
</script>

enter code here


text:
Q: Passing multiple URL parameters as props using react-router? When I pass just one parameter as follows, everything works as intended.
<Switch>
    <Route exact path="/" component={SessionViewer} />
    <Route path="/:sessionID" render={
        (props) => <SessionViewer { ...props }/>
    } />
</Switch>

However, when I try to pass multiple (not just one) dynamic URL parameters as props with react-router:
<Switch>
    <Route exact path="/" component={SessionViewer} />
    <Route path="/:sessionID/:tsFrom/:tsTo" render={
        (props) => <SessionViewer { ...props }/>
    } />
</Switch>

The page doesn't load and the following error is thrown:
Uncaught SyntaxError: Unexpected token <
Is there a proper way to do this?

A: I get what you are trying to do but this is not how you do it, react-router actually does this for you in a sense, let me explain:
React-router actually has its own props, and you can connect to the router to get those props
Little exemple:
First, Change your routing to this:
<Switch>
    <Route exact path="/" component={SessionViewer} />
    <Route path="/:sessionID/:tsFrom/:tsTo" component={SessionViewer} />
</Switch>

this will make sure both routes will render SessionViewer, Then:

*

*create a componentDidMount() method in SessionViewer

*React-Router-Dom will provide you with different props by default if you use withRouter method on your component -> Add export default withRouter(SessionViewer) to your SessionViewer class

*Since you have now a connected Class (to the routing) you can access match inside your props, this props is created by react-router and contains informations about what matched in this route : For exemple match.params.sessionId would contains the :sessionId from the route, meaning if I have /10/from/to
match.params = {
    sessionId: 10,
    tsFrom: from,
    tsTo: to
}

*Now inside you componentDidMount method you can setState all the match.params you need to make conditionnal rendering for exemple.

Hope it helps, i can go deeper if you need but i rather keep it simple

A: After searching around Stackoverflow for my Uncaught SyntaxError: Unexpected token < error, I found this answer that helped resolve the issue. I'll paste it here as well:
The "unexpected token" error can show up for a number of different reasons. I ran into a similar problem, and in my case the problem was that the script tag to load the generated bundle in the html was like so:
<script src="scripts/app.js"></script>

When navigating to a route with a parameter (same thing will happen to a nested route or a route with more than one segment), browser would try to load the script using the wrong url. In my case the route path was 'user/:id', and the browser made a request to http://127.0.0.1:3000/user/scripts/app.js instead of http://127.0.0.1:3000/scripts/app.js. The solution was easy, change the script tag to this:
<script src="/scripts/app.js"></script>


text:
Q: Loop in Oracle SQL, comparing one month to another I have to draft a SQL query which does the following:
Compare current week (e.g. week 10) amount to the average amount over previous 4 weeks (Week# 9,8,7,6).
Now I need to run the query on a monthly basis so say for weeks (10,11,12,13).
As of now I am running it four times giving the week parameter on each run.
For example my current query is something like this :
select account_id, curr.amount,hist.AVG_Amt
from
(
    select
        to_char(run_date,'IW') Week_ID,
        sum(amount) Amount,
        account_id
    from Transaction t
    where to_char(run_date,'IW') = '10'
    group by account_id,to_char(run_date,'IW')
) curr,
(
    select account_id,
        sum(amount) / count(to_char(run_date,'IW')) as AVG_Amt
    from Transactions
    where to_char(run_date,'IW') in ('6','7','8','9')
    group by account_id
) hist
where
    hist.account_id = curr.account_id
    and curr.amount > 2*hist.AVG_Amt;

As you can see, if I have to run the above query for week 11,12,13 I have to run it three separate times. Is there a way to consolidate or structure the query such that I only run once and I get the comparison data all together?
Just an additional info, I need to export the data to Excel (which I do after running query on the PL/SQL developer) and export to Excel.
Thanks!
-Abhi

A: You can use a correlated sub-query to get the sum of amounts for the last 4 weeks for a given week.
select
    to_char(run_date,'IW') Week_ID,
    sum(amount) curAmount,
    (select sum(amount)/4.0 from transaction
     where account_id = t.account_id
     and to_char(run_date,'IW') between to_char(t.run_date,'IW')-4
                                        and to_char(t.run_date,'IW')-1
    ) hist_amount,
    account_id
from Transaction t
where to_char(run_date,'IW') in ('10','11','12','13')
group by account_id,to_char(run_date,'IW')

Edit: Based on OP's comment on the performance of the query above, this can also be accomplished using lag to get the previous row's value. Count of number of records present in the last 4 weeks can be achieved using a case expression.
with sum_amounts as
(select to_char(run_date,'IW') wk, sum(amount) amount, account_id
 from Transaction
 group by account_id, to_char(run_date,'IW')
)
select wk, account_id, amount,
1.0 * (lag(amount,1,0) over (order by wk) + lag(amount,2,0) over (order by wk) +
       lag(amount,3,0) over (order by wk) + lag(amount,4,0) over (order by wk))
/ case when lag(amount,1,0) over (order by wk) <> 0 then 1 else 0 end +
  case when lag(amount,2,0) over (order by wk) <> 0 then 1 else 0 end +
  case when lag(amount,3,0) over (order by wk) <> 0 then 1 else 0 end +
  case when lag(amount,4,0) over (order by wk) <> 0 then 1 else 0 end
as hist_avg_amount
from sum_amounts

A: I think that is what you are looking for:
with lagt as (select to_char(run_date,'IW') Week_ID, sum(amount) Amount, account_id
  from Transaction t
  group by account_id, to_char(run_date,'IW'))
select Week_ID, account_id, amount,
  (lag(amount,1,0) over (order by week) + lag(amount,2,0) over (order by week) +
   lag(amount,3,0) over (order by week) + lag(amount,4,0) over (order by week)) / 4 as average
  from lagt;


text:
Q: Source code of HTML page without Framework Question pretty much sums it up. I don't have access to a framework and I need to get the FULL HTML Source of the current page. Is there some command that is supported by JS natively?
For the record, I've tried:
document.getElementsByTagName('html')[0].innerHTML

A: This can be done in a one-liner using XMLSerializer.
var generatedSource = new XMLSerializer().serializeToString(document);

Which gives String
<!DOCTYPE html><html><head>

<title>javascript - Source code of HTML page without Framework - Stack Overflow</title>
...

A: I don't think it's possible to get the complete, actual, live page source from the current page. (edit: as it seems, it is possible! See @Paul S. his answer)
But what you could do to load the initial, unaltered HTML, just load the page through AJAX, and then check the page source as it is returned by the server.
$.get(document.location.href, function(response) {
    window.console.log(response);
});

This is with jQuery, but you would alternatively use

var xmlhttp;
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        window.console.log(xmlhttp.responseText);
    }
}
xmlhttp.open("GET",document.location.href,true);
xmlhttp.send();


text:
Q: Using Group by to sum the int value and string I want to select the Column of Uptime for 8 hour shift and when there is no production I wanted to show "NoProduction" on that select column.
For Example Raw Table look like this

Uptime(hr)
Production_Day(0 or 1)
t_stamp(date and time)
Shift

1
1
Feb 15 05:00:00 EST 2021
Mor

1
1
Feb 15 06:00:00 EST 2021
Mor

---(so on up 13:00 and value of uptime for each hour is 1 and Production_day is 1)

1
1
Feb 15 13:00:00 EST 2021
Mor

0
0
Feb 15 14:00:00 EST 2021
Aft

---(so on up to 21:00 and value of uptime for each hour is 0 and Production_day is 0)

0
0
Feb 15 21:00:00 EST 2021
Aft

And I want to have result like this

Uptime
Shift

8
Mor

"NoProduction"
Aft

Here is my sql query which I tried,
select SUM(case when Production_Day = 1 then Pastry1_1hrUpTime_Minutes else "NoProduction" end) as Uptime,  Max(Shift) as Shift
FROM Table
WHERE t_stamp >= FORMAT(getDate()-0,'yyyy-MM-dd 05:00:00') and t_stamp <= FORMAT(getDate()-0,'yyyy-MM-dd 21:00:00')
GROUP BY DATEADD(hh, ((DATEDIFF(hh, 0, t_stamp)+3)/8*8)-4, 0)

So anybody can help me, how to use sum int and string in same select statement.
Thanks

A: Provided Pastry1_1hrUpTime_Minutes is int, zero sum value will be casted to '0'.  Try
select case when Uptime ='0' then 'NoProduction' else Uptime end Uptime
    , -- more columns
from (
      select cast(SUM(case when Production_Day = 1 then Pastry1_1hrUpTime_Minutes else 0 end) as varchar(254)) as Uptime
      , -- more columns
      from ..
) t;


text:
Q: Is it a bad idea to start a thread in init method? I have a class which acts like a Queue in which I am creating a worker thread. This worker thread would be responsible for processing each item from the queue.
Since an instance of this class should always have a worker thread, I am creating and starting the worker thread in the init method itself.
I would like to know if it is a bad practice to do so.
e.g
class CustomQueue:

    def __init__(self):
        # some initialization
        self.worker = threading.Thread(target=sometarget)
        self.worker.start()

A: It is OK, but you will need to add a __del__ method that stops the thread so that the thread doesn't hang around after the CustomQueue object dissapears. This __del__ method will be called when the CustomQueue instance is garbage collected.

A: I don't know if I would go so far as to call it bad practice, but my
first instinct is to avoid all side-effects in constructors:
don't talk to DBs, don't interact with the file system, don't make
web requests, and, no, don't spin up processes or threads. Whenever possible,
object instantiation should be a cheap, lightweight operation.
This general rule is particularly useful when it comes to testing
and debugging. For example, imagine this scenario:
class CustomQueue:

    def __init__(self):
        # Side effects here...

    def fubb(self, x, y):
        ...

If you want to unit test fubb(), or perhaps interact with it in the Python
REPL, it's fairly annoying to have to think about all those side-effects.
There are exceptions to most rules, and if it really makes sense for
this class to take immediate action, one workaround is to add an
optional parameter to support your testing/debugging use cases. For example:
class CustomQueue:

    def __init__(self, lightweight = False):
        if not lightweight:
            # Side effects here...


text:
Q: Strings command on exe revealing too much I've created an application in VC++ 2010 Express and i wanted to see what would a search for strings reveal about my executable. I saw a lot of strings as expected but what caught my attention is that i saw the exact location of the .pdb file that VS produces for every project.
C:\Users\...\myapp\Debug\myapp.pdb

That one really bothers me because i dont think that this much information(my username for example) should be revealed.
Apart from that i also saw a lot of error messages like
Stack memory around _alloca was corrupted
A local variable was used before it was initialized
Stack memory was corrupted
A cast to a smaller data type has caused a loss of data.  If this was intentional, you     should mask the source of the cast with the appropriate bitmask.  For example:
char c = (i & 0xFF);
Changing the code in this way will not affect the quality of the resulting optimized code.
The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
Stack around the variable ' ' was corrupted.
The variable ' ' is being used without being initialized.

I don't really understand why they show up(my programm works fine,none of them applies) but i guess i could live with that.
My question is how can i avoid that kind of data(especially as i said the pdb location) showing up?I tried finding something in the project properties but without success.

A: The first option you want is /PDBALTPATH:%_PDB% - this keeps the PDB name but drops its path.
The error messages are caused by the default options /GS and /RTC. The latter isn't default for release builds, though. /GS- would turn the first one off, but that's a security risk.


text:
Q: What effect does taking the transpose of a linear transformation matrix have on the transformed plane I have recently been using 3Blue1Brown's fantastic YouTube series on linear algebra to supplement my third year matrix analysis course. I have found it super useful to be able to visualise matrices as transformations of the plane (or 3D space).
As far as I am aware however, he never touches on the effect of taking the transpose of a linear transformation matrix or provide any intuition of what the transpose does to the plane.  Could anyone shed light on an intuitive way to think about the transpose of a matrix as a linear transformation.


text:
Q: How to find non zero elements of a list containing zeros and symbols I have a list, obtained after differentiating a list of expressions, which contains zeros and symbols, say:
A = {x1^2, x2^2, x3^2, x4^2}
D[A,x3]

results in the list:
{0, 0, 2 x3, 0}

How do I get the position of the non-zero entry, mathematica cannot compare symbols to zero directly. I could convert the elements of the list to strings but is there a faster way?

A: I've failed to find good topic to mark it a duplicate so this is the answer.
Let's assume your list is:
list = {0, 2 x3, 0.}

so we 0 is not 0. and missing this may cause troubles while pattern matching. Take a look here and there.
SparseArray[list]["NonzeroPositions"]

{{2}}

or alternatively:
Position[list, x_ /; ! TrueQ[x == 0], {1}, Heads -> False]


text:
Q: Why does the default shell in OS X 10 look differently than that in Linux (Mint, Lubuntu...)? To clarify, when entering the default shell in OS X it appears as:
pcname:~ username$
and changing directories appears as:
pcname:myFolder~ username$

however, in my experience with linux distros, the shell appears as:
username@pcname:~$
what is the purpose for the differences in syntax?

A: What I do is the following: On the system that has the promt the way I want it, I type:
echo $PS1

I copy the result, say, \u@\h \w\a \$ and then edit the ~/.bashrc on the system that I want to use with the line:
export PS1="\u@\h \w\a \$ "

And then I get the same prompt on that system as well.
If you want to get creative, have a look here


text:
Q: Simple action to change the record type of the record I am looking for a simple way for the user to change the record type of a record. I would like to know if it is possible to have a button on the page layout for the record that the user is working and for them to be able to press this button and to then change the record type of the record, e.g., case. As a result the page layout would change but more importantly the Process flow would then kick in to manage the record.
I need a button/action because this is what users prefer as a way of changing the record

A: In Salesforce classic you can update the Record Type through a OnClick JavaScript button.
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

// identify the record
var o = new sforce.SObject("Opportunity");
o.id = "{!Opportunity.Id}";

// make the field change
o.StageName = "Closed Won";

// Update the Record Type
o.RecordTypeId = "XXXXXXXXXXXXX"; //You can also Query the RecordTypeId

// save the change
sforce.connection.update([o]);

//refresh the page
window.location.reload();

Refer this link for more details on OnClick JavaScript button. http://hometeamconsulting.com/update-records-javascript-buttons/


text:
Q: Get all url GET values and some random values after insert in db I have a custom form wich have ~6 custom intuts and 1-20 can be random how can i get random inputs with $_GET and put them in col atributes:
    <form method="GET" action="products.php" enctype="multipart/form-data">

                            Name
                            <input required  class="scurtI" type="text" name="prod_name" value="<?= $_GET['prod_name'] ?>" placeholder="">

                            Description
                            <input required  class="scurtI" type="text" name="prod_descr" value="<?= $_GET['prod_descr'] ?>" placeholder="">

                            Meta - Title
                            <input required  class="scurtI" type="text" name="prod_meta_title" value="<?= $_GET['prod_meta_title'] ?>" placeholder="">

                            Meta - Description
                            <input required  class="scurtI" type="text" name="prod_meta_desc" value="<?= $_GET['prod_meta_desc'] ?>" placeholder="">

                            Meta - Keywords
                            <input required  class="scurtI" type="text" name="prod_meta_keys" value="<?= $_GET['prod_meta_keys'] ?>" placeholder="">

                            Price
                            <input required  class="scurtI" type="text" name="prod_price" value="<?= $_GET['prod_price'] ?>" placeholder="">

                            Currency
                            <select name="prod_curency" class="focusSelect">
                            <option value="RON">RON</option>
                            <option value="USD">USD</option>
                            <option value="EUR">EUR</option>
                          </select>

                            Units
                            <input required  class="scurtI" type="text" name="prod_units" value="<?= $_GET['prod_units'] ?>" placeholder="">

                            Category
                            <select name="prod_ctgy" class="focusSelect">

                            <?php

                            $sql = "SELECT * FROM `categorii` WHERE `cat_id`";
                            $connect = mysqli_query($db_connect, $sql);
                            while (($item = mysqli_fetch_array($connect)))
                                {
                                    ?>
                                     <option
                                    value="<?= $item['cat_id'] ?>"><?= str_repeat(' ', 6 * $item['section_level']) ?><?= $item['section_name'] ?></option>
                                <?php

                            }

                            ?>

                          </select>

                            Manufacturer
                            <select name="prod_manu" class="focusSelect">

                            <?php

                            $sql = "SELECT * FROM `manufactures` WHERE `id`";
                            $connect = mysqli_query($db_connect, $sql);
                            while (($item = mysqli_fetch_array($connect)))
                                {
                                    ?>
                                     <option
                                    value="<?= $item['manu_code'] ?>"><?= $item['manu_name'] ?></option>
                                <?php

                            }

                            ?>

                          </select>

                         Atributes
                         <select name="prod_atr_id" class="focusSelect">

                            <?php
                            if (isset($_GET['prod_atr_id'])){
                                echo "<option selected value=".$_GET['prod_atr_id'].">Selected</option>";
                            }

                            $sql = "SELECT * FROM `products_atributes` WHERE `prod_atr_id`";
                            $connect = mysqli_query($db_connect, $sql);
                            while (($item = mysqli_fetch_array($connect)))
                                {
                                    ?>
                                     <option
                                    value="<?= $item['prod_atr_id'] ?>"><?= $item['prod_atr_name'] ?></option>
                                <?php

                            }

                            ?>
                          </select>
                           <button class="btn btn-sm btn-primary" type="submit" name="next_add_product">Next</button>

                                <?php
            if(isset($_GET['prod_atr_id']))

    {
        list_atributes($_GET['prod_atr_id']);

    ?>

                                Main Image
                                <input type="file" name="prod_image" style="">

                                <input class="btn btn-sm btn-primary" type="submit" name="prod_add_new" value="Add Product">

                        </form>

    <?php
    }
        if(isset($_GET['prod_add_new']))

    {
    //$prod_name = $_GET['prod_name']

    foreach($_GET as $key => $value){
      echo $key . " : " . $value . "
\r\n";

    }

    //print_r($all_gets);

    }
    ?>

    function list_atributes($id)
{
    global $db_connect;
    $atribute_detect = $id;
            if ($atribute_detect > 0){

                $sql = "SELECT * FROM `products_atributes` WHERE `prod_atr_parent` = '".$atribute_detect."'";
                $connect = mysqli_query($db_connect, $sql);
                $count = mysqli_num_rows($connect);
                if ($count == 0)
                    {
                        $sql = "SELECT * FROM `products_atributes` WHERE `prod_atr_id` = '".$atribute_detect."'";
                    }
                if ($count > 0)
                    {
                        $sql = "SELECT * FROM `products_atributes` WHERE `prod_atr_parent` = '".$atribute_detect."'";
                    }

                $connect = mysqli_query($db_connect, $sql);
                while (($item = mysqli_fetch_array($connect)))
                {
                    echo "

                            ".$item['prod_atr_name']."
                            <input required  class='scurtI' type='text' name='".$item['prod_atr_code']."' value='".$_GET[$item['prod_atr_code']]."' >

                    ";

                }

            }

}

And now i get this restults

*

*prod_name : sadfasd

*prod_descr : asdfasd

*prod_meta_title : ghdf

*prod_meta_desc : gs

*prod_meta_keys : asdf

*prod_price : 235243

*prod_curency : RON

*prod_units : 1243123

*prod_ctgy : 16

*prod_manu : 70123825

*prod_atr_id : 1

*26126933 : 1243ghz

*40320861 : 2000mb

*47789694 : 64bit

*prod_image : log_masacru.png

*prod_add_new : Add Product

How can i get this values, for all with prefix prod_ i have special cols, and for that with numbers i must put them all in a single col and after i must use them to extract as id=40320861 value=2000mb, etc. How can i build the code to add in db random number of $_GET values in a single column

A: My understanding of the question is that you need to save the following GET variables :
26126933 : 1243ghz
40320861 : 2000mb
47789694 : 64bit
in a single db column where the keys are randomly generated ( unknown).
ANSWER:
Save the attributes in a multidimensional array, for this set their name values in the html to something like prod_attr_value[][$RANDOM_NUMBER], this will make the attributes values in the array $_GET['prod_attr_value'] .
Then to save in these values in a single db column, you can simply json_encode($arr).
hth
UPDATE:
<input required  class='scurtI' type='text' name='".$item['prod_atr_code']."' value='".$_GET[$item['prod_atr_code']]."' >

The above creates a $_GET var with a key having the name (not value) of the value of $item['prod_atr_code'].
Changing the name to something like prod_attr_values_arr[][$item['prod_atr_code']], will on sending the request create a array $GET['prod_attr_values_arr']


text:
Q: Background color for existing floats (e.g. w/o defining a new environment)? I'm trying to make all my figures (including caption) backgrounded with a decent color.
I already found these questions with some nice answers:

*

*How to set a background color of figure environment?

*Rounded corner colored box around figure

*Background color boxes around complete figure in LaTeX
But all these answers have in common that they define some new environments or commands that need to be put inside the figures or replace the figures completly.
Is there a way to put a background color behind existing floats without having to change the content of these existing floats?

A:
\documentclass{article}

\makeatletter

\def\foo#1\normalcolor\vbox\bgroup#2!!{%
\def\@xfloat ##1[##2]{#1%
 \normalcolor
      \hbox\bgroup{\color{yellow}\leaders\vrule\hskip\columnwidth\hskip-\columnwidth}%
      \vbox \bgroup\aftergroup\egroup
#2}}
\expandafter\foo\@xfloat{#1}[#2]!!

\makeatother

\usepackage{color}
\begin{document}

\begin{figure}
a\\b\\c
\caption{yes no}
\end{figure}

one two three

\end{document}

A: Here is an elementary implementation using mdframed that redefines the figure environment (therefore not adapting the usage of figure in your document):

\documentclass{article}
\usepackage{lipsum,mdframed,xcolor}% http://ctan.org/pkg/{lipsum,mdframed,xcolor}
\let\oldfigure\figure% Store old figure environment start
\let\endoldfigure\endfigure% Store old figure environment end
\renewenvironment{figure}[1][htbp]% Redefine figure
  {\oldfigure[#1]\mdframed[backgroundcolor=blue!15]}
  {\endmdframed\endoldfigure}
\begin{document}
\lipsum[1]
\begin{figure}[ht]
  \centering\includegraphics{example-image-a}
  \caption{This is a figure}
\end{figure}
\lipsum[2]
\end{document}

From here it would be straight forward to apply a different style to a different float (like table, for example).


text:
Q: How to set setMaxPerRoute in PoolingHttpClientConnectionManager? I have PoolingHttpClientConnectionManager where I want to set max connections per route. I'm doing it in next way:
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(5);
poolingHttpClientConnectionManager.setMaxPerRoute(new HttpRoute(HttpHost.create(url)), 3);

where for example my url is https://repo.maven.apache.org/maven2.
So I have default max per route 5 and 3 per specific url. Then if I call
poolingHttpClientConnectionManager.getStats(new HttpRoute(HttpHost.create(url)));

I receive as a result PoolStats with max = 3 so everything ok for now.
But when I create a client with pooling connection manager and call same url I can see in logs:
PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {s}->https://repo.maven.apache.org:443][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 200]

As I can see it still uses 5 connections as max for that example url.
So my question is how to set max connections per some route to make it work?

A: Ok I've managed to fix it with next code:
// code to create HttpRoute the same as in apache library
private HttpRoute getHttpRouteForUrl(String url) throws URISyntaxException
{
    URI uri = new URI(url);
    boolean secure = uri.getScheme().equalsIgnoreCase("https");
    int port = uri.getPort();
    if (uri.getPort() > 0)
    {
        port = uri.getPort();
    }
    else if (uri.getScheme().equalsIgnoreCase("https"))
    {
        port = 443;
    }
    else if (uri.getScheme().equalsIgnoreCase("http"))
    {
        port = 80;
    }
    else
    {
        LOGGER.warn("Unknown port of uri %s", repository);
    }
    HttpHost httpHost = new HttpHost(uri.getHost(), port, uri.getScheme());
    // TODO check whether we need this InetAddress as second param
    return new HttpRoute(httpHost, null, secure);
}

And if we use this HttpRoute for setMaxPerRoute everything works as expected.


text:
Q: handle input from multiple processes example in nextflow dsl2 How do I go about defining a workflow that executes two initial processes in parallel and then handles both outputs of those processes in a third process? The simple examples I was able to find in tutorials always define sequential flows and often use stdin/stdout to transport information.
In order to illustrate what I want to achieve, here is a diagram of the DAG that I imagine:

I imagine the .nf file to look something like the following but cannot fill in the blanks
#!/usr/bin/env nextflow
nextflow.enable.dsl=2

process produceRandomX {

    output:
        x // what do I put in these places?

    """
    print $RANDOM
    """
}

process produceRandomY {

    output:
        y

    """
    print -$RANDOM
    """
}

process calculateSum {
    input:
        x
        y
    output:
        sum

    """
    print $x+$y
    """
}

process printResult {
    input:
        sum
    output:
        stdout

    """
    print $sum
    """
}

workflow {
    // syntax here is broken and just meant to illustrate what I want to achieve
    produceRandomX \
                     | calculateSum | printResult
    produceRandomY /
}

A: Nextflow processes can define one or more input and output channels. The interaction between these, and ultimately the pipeline execution itself, is implicitly defined by these input and output declarations1. In the following example, produceRandomX and produceRandomY could be run in parallel (assuming there are sufficient system resources available) but even if they're not, calculateSum will wait until it receives a complete input configuration (i.e. until it receives a value from each input channel).
process produceRandomX {

    output:
    stdout

    """
    echo "\$RANDOM"
    """
}

process produceRandomY {

    output:
    stdout

    """
    echo "-\$RANDOM"
    """
}

process calculateSum {

    input:
    val x
    val y

    output:
    stdout

    """
    echo \$(( $x + $y ))
    """
}

workflow {

    x = produceRandomX()
    y = produceRandomY()

    sum = calculateSum( x, y )

    sum.view()
}

Results:
$ nextflow run -ansi-log false main.nf
N E X T F L O W  ~  version 22.10.0
Launching `main.nf` [lonely_torvalds] DSL2 - revision: 3b752ca2cc
[07/8e1473] Submitted process > produceRandomX
[fd/d9a629] Submitted process > produceRandomY
[15/c88aac] Submitted process > calculateSum
-1331


text:
Q: Can I get iOS analytics without including mysterious closed-source libraries into my app? I want to collect very simple analytics about my app (session count, monthly active users, maybe a list of events corresponding to each screen open), but the systems I've found all require integrating an opaque binary library into my project.
Does anyone know of any iOS analytics systems that don't have this shortcoming?

A: You can use Google Analytics with an os library: https://github.com/ksmandersen/GoogleReporter

Easily integrate Google Analytics into your iOS, macOS, and tvOS app without downloading any of the Google SDKs.

Mixpanel is also open-source and doesn't include any static libraries.
https://github.com/mixpanel/mixpanel-iphone


text:
Q: How can I dereference an array of arrays in Perl? How do I dereference an array of arrays when passed to a function?
I am doing it like this:
my @a = {\@array1, \@array2, \@array3};

func(\@a);

func{
    @b = @_;

    @c = @{@b};
}

Actually I want the array @c should contain the addresses of @array1, @array2, and @array3.

A: my @a = {\@array1, \@array2, \@array3};

The above is an array with a single member -> a hash containing:
{ ''.\@array1 => \@array2, ''.\@array3 => undef }

Because as a key in the hash, Perl coerces the reference to @array1 into a string. And Perl allows a scalar hash reference to be assigned to an array, because it is "understood" that you want an array with the first element being the scalar you assigned to it.
You create an array of arrays, like so:
my @a = (\@array1, \@array2, \@array3);

And then in your function you would unpack them, like so:
sub func {
    my $ref = shift;
    foreach my $arr ( @$ref ) {
        my @list_of_values = @$arr;
    }
}

Or some variation thereof, like say a map would be the easiest expression:
my @list_of_entries = map { @$_ } @$ref;

In your example, @c as a list of addresses is simply the same thing as a properly constructed @a.

A: You may want to read perldoc perlreftut, perldoc perlref, and perldoc perldsc  You can say:
sub func {
    my $arrayref = shift;

    for my $aref (@$arrayref) {
        print join(", ", @$aref), "\n";
    }
}

my @array1 = (1, 2, 3);
my @array2 = (4, 5, 6);
my @array3 = (7, 8, 9);

my @a = \(@array1, @array2, @array3);

func \@a;

or more compactly:
sub func {
    my $arrayref = shift;

    for my $aref (@$arrayref) {
        print join(", ", @$aref), "\n";
    }
}

func [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];

A: Read the perlreftut documentation.
Edit: Others point out a good point I missed at first.  In the initialization of @a, you probably meant either @a = (...) (create array containing references) or $arrayref = [...] (create reference to array), not {...} (create reference to hash).  The rest of this post pretends you had the @a = (...) version.
Since you pass one argument (a reference to @a) to func, @_ is a list containing that one reference.  You can get that reference and then dereference it by doing:
sub func {
  my $arrayref = shift;
  my @c = @{$arrayref};
}

Or in one line, it would look like:
sub func {
  my @c = @{shift()};
}

(If you hadn't used the backslash in func(\@a), @_ would be equal to @a, the array of three references.)

A: The following function is designed to take either an array or an array reference and give back a sorted array of unique values. Undefined values are removed and HASH and GLOB are left as is.
#!/usr/bin/perl
use strict; use warnings;

my @one = qw / dog rat / ;
my @two = qw / dog mice / ;
my @tre = ( "And then they said it!", "No!??  ", );
open my $H, '<', $0 or die "unable to open $0 to read";
my $dog; # to show behavior with undefined value
my %hash; $hash{pig}{mouse}=55; # to show that it leaves HASH alone
my $rgx = '(?is)dog'; $rgx = qr/$rgx/; # included for kicks

my @whoo =  (
    'hey!',
    $dog, # undefined
    $rgx,
    1, 2, 99, 999, 55.5, 3.1415926535,
    %hash,
    $H,
    [ 1, 2,
              [ 99, 55, \@tre, ],
    3, ],
        \@one, \@two,
        [ 'fee', 'fie,' ,
            [ 'dog', 'dog', 'mice', 'gopher', 'piranha', ],
            [ 'dog', 'dog', 'mice', 'gopher', 'piranha', ],
        ],
        [ 1, [ 1, 2222, ['no!', 'no...', 55, ], ], ],
        [ [ [ 'Rat!', [ 'Non,', 'Tu es un rat!' , ], ], ], ],
        'Hey!!',
        0.0_1_0_1,
        -33,
);

print join ( "\n",
    recursively_dereference_sort_unique_array( [ 55, 9.000005555, ], @whoo, \@one, \@whoo, [ $H ], ),
    "\n", );
close $H;
exit;

sub recursively_dereference_sort_unique_array
{
    # recursively dereference array of arrays; return unique values sorted. Leave HASH and GLOB (filehandles) as they are.
    # 2020v10v04vSunv12h20m15s
    my $sb_name = (caller(0))[3];
    @_ = grep defined, @_; #https://stackoverflow.com/questions/11122977/how-do-i-remove-all-undefs-from-array
    my @redy = grep { !/^ARRAY\x28\w+\x29$/ } @_; # redy==the subset that is "ready"
    my @noty = grep {  /^ARRAY\x28\w+\x29$/ } @_; # noty==the subset that is "not yet"
    my $countiter = 0;
    while (1)
    {
        $countiter++;
        die "$sb_name: are you in an infinite loop?" if ($countiter > 99);
        my @next;
        foreach my $refarray ( @noty )
        {
            my @tmparray = @$refarray;
            push    @next, @tmparray;
        }
        @next = grep defined, @next;
        my @okay= grep { !/^ARRAY\x28\w+\x29$/ } @next;
        @noty   = grep {  /^ARRAY\x28\w+\x29$/ } @next;
        push @redy, @okay;
        my %hash = map { $_ => 1 } @redy; # trick to get unique values
        @redy    = sort keys %hash;
        return @redy unless (scalar @noty);
    }
}

A: Should be
func {
    $b = shift;
}

if you're passing in a reference. Hope that helps some.


text:
Q: Using a round rect button as a badge with a counter I'm using a view based NSOutlineView with two different views (both views are custom subclasses of NSTableCellView). In the top level view I display a badge with a counter. The counter indicates the number of entries on the lower level. The counter is implemented as a rounded rect NSButton, following Apple's SidebarDemo project.
As you can see from the images the behaviour of the button upon selection of the cell is not the behaviour you would expect. My button turns black, while in Apple's sample it turns white. I've tracked down the method that sets this particular behaviour for a button to the  setHighlightsBy method:
[[self.button cell] setHighlightsBy: 0];

I use the above in the awakeFromNib method of the custom cell class. In the same awakeFromNib I also set the button's bezel:
[[self.button cell] setBezelStyle: NSInlineBezelStyle];

The bezel style works just fine, but the highlighting seems to be ignored.
Further information I can give: The outline view uses bindings to gets its contents, its highlight mode is set to "Source List".
Why is my highlighting being ignored?

A: Is your button set up in IB (like in the demo project)?  If so, do you have the "enable" box checked in the control section  of the attributes inspector?  I got the behavior you're seeing if I unchecked that box.

A: I found the cause of the described behaviour, thanks to the suggestion made by @rdelmar in his answer. The button is bound to the Cell View using the "Argument" binding inspector.

One of the settings there is "Conditionally sets enabled", which was enabled and apparently causes auto-disabling of my button. Once you disable this setting, the problem disappears.


text:
Q: UIViewPropertyAnimator in UINavigationController I have a UIViewPropertyAnimator setted on a UIVisualEffectView in order to animate its blurriness with a slider. This UIViewPropertyAnimator seems to have no more effect when :

*

*Play with the slider and adjust blurriness

*The view controller that presents this blurry view is embedded in a navigation controller

*I push a new controller on this navigation controller

*Back to blurry view controller

*The slider is not working anymore

I've tried to play with stopAnimation & finishAnimation function from the animator with no luck. Is it the expected behaviour ? I guess I could solve this issue by completly removing and resetting the blur and its animator with correct value when needed (like on viewWillAppear, didDisappear) but that seems so wrong... !
github source code


text:
Q: How to use addHeaderView to add a simple ImageView to a ListView My target is simple. I want to add a "Red Rectangle" as a headerview to a ListView.
so I create a simple activity
public class MainActivity extends Activity {
    private String[] adapterData = new String[] { "Afghanistan", "Albania", "Algeria",
            "American Samoa", "Andorra", "Angola"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView lv;
        lv = (ListView)findViewById(R.id.list);

        LayoutInflater lf;
        View headerView;
        lf = this.getLayoutInflater();
        headerView = (View)lf.inflate(R.layout.header, null, false);

        lv.addHeaderView(headerView, null, false);

        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, adapterData));
    }
}

activity_main.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FF0"
        android:cacheColorHint="#0000"
        android:paddingLeft="20dip"
        android:paddingRight="20dip"
        android:divider="#0000"
        android:scrollbarStyle="outsideOverlay" />

list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:minHeight="40dip"
    android:singleLine="true"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
/>

most important, header.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dip"
    android:background="#F00"/>

But it doesn't seem to work. Nothing is displayed.
Can any give some suggestions on this? Your help is highly appreciated.

A: Check this, I have get it working right now:
    ListView lv = (ListView)findViewById(R.id.list);

    LayoutInflater layoutInflater = this.getLayoutInflater();
    View headerView = (View) layoutInflater.inflate(R.layout.header, lv, false);

Just send listview to the second param of the inflate method :)

A: Old question, but I just copied it and run it and indeed the red doesn't show up.
You're missing one simple thing: Regardless of how you call inflate you always1 have to pass a parent view (second param) so that it can figure out which LayoutParams subclass to instantiate.
1: there are always1 exceptions

.inflate(R.layout.header, lv, false)

For more on the subject I highly suggest: http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ (worth reading even a few times)
Your full code modified (xml files can stay as is):
public class MainActivity extends Activity {
    private static final String[] ADAPTER_DATA = {
            "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView list = (ListView) findViewById(R.id.list);
        View header = getLayoutInflater().inflate(R.layout.header, list, false);

        list.addHeaderView(header, null, false);
        list.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, ADAPTER_DATA));
    }
}

A: This is how I add a header:
    View view = View.inflate(context, R.layout.header, null);
    lv = (ListView) findViewById(R.id.list);

    lv.addHeaderView(view);

A: You should declare the header view in a separated xml file. Then, inflate it in to a View instance and set it to ListView.
View view = ... (inflate the view from xml file)
listview.addHeaderView(view)

You must call addHeaderView before setAdapter to the listview.


text:
Q: Dual booting windows 8.1 and ubuntu I have a lenovo laptop with windows 8.1. I wanted to use ubuntu alongside windows. Hence, i downloaded the ubuntu 14.04 iso and created a live pendrive using Universal USB installer.
I disabled secure boot and booted from the pendrive. All i get is the GNU GRUB command line version 2.X.
I don't get a GUI for the GRUB and i don't know how to boot into ubuntu from the command line.
I searched quite a few online forums but in vain. Can someone tell me how to proceed?
Thanks in advance.

A: Did you download the Live .iso file and then burn that to disk? If so, you may want to check the official Ubuntu MD5 hash from here against your download. If not exactly the same, it may explain you issues. In that case re-download and try again...
All the best,
dkp

A: I had the same problem and I just loaded the Boot Menu(F12 on Lenovos) then booted windows from there.
After that, you can create a windows recovery (http://windows.microsoft.com/en-us/windows-8/create-usb-recovery-drive).

A: i was finally able to do it. I used a DVD and burned the iso onto it. It worked perfectly. Though i still don't know why the flashdrive gave me that "invalid magic number" error.


text:
Q: Reducing the encrypted data field length size in salesforce I am working on simple encryption using the crypto class to encrypt some data fields in salesforce. The encryption class works fine for text data with max size 255. however i need to reduce the encrypted data size once encrypted.
This is sample encryption login i am using to encrypt the data.
for(Account a : scope)
 {
Blob stringencry =Blob.valueOf(a.phone);
Blob encrypted = Crypto.encryptWithManagedIV('AES256', seckey, stringencry);
String b64=EncodingUtil.base64Encode(encrypted);
a.phone=b64;
}

The above logic works fine for text data type variable however the same could not be implemented for other data types like phone,url or any others .While saving the records i am receiving the  "STRING_TOO_LONG" error from salesforce.
So post encryption  there has to be a way in restricting the encrypted size of the data.Any light on this is great help to me.

A: Some of the standard Salesforce fields like phone, URL, email etc. have enforced character limit which is set by the platform. Phone I believe is 40 characters. Your output (encrypted and encoded) is most likely to be greater than 40 characters hence it won't fit in that field.


text:
Q: Erro ao Ler XML com namespace no PHP Preciso acessar o valor das tags numeroCNS, dataAtribuicao, etc do seguinte arquivo XML:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <cad:responseConsultar xmlns:cad="http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice">
        <usu:UsuarioSUS xmlns:usu="http://servicos.saude.gov.br/schema/cadsus/v5r0/usuariosus" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
            <usu:Cartoes>
                <usu:CNS>
                    <cns:numeroCNS xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">foo</cns:numeroCNS>
                    <cns:dataAtribuicao xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">bar</cns:dataAtribuicao>
                    <cns:tipoCartao xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">fubá</cns:tipoCartao>
                    <cns:manual xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">canjica</cns:manual>
                    <cns:justificativaManual xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns" />
                </usu:CNS>
            </usu:Cartoes>
        </usu:UsuarioSUS>
    </cad:responseConsultar>
</soap:Body>
</soap:Envelope>

Meu código:
<?php
$x = simplexml_load_file('xml/teste.xml');
echo $x -> Body -> responseConsultar -> UsuarioSUS -> Cartoes -> CNS ->
numeroCNS;
?>

PHP Notice:  Trying to get property of non-object

Se remover manualmente os namespaces, o código funciona. Mas seria inviável fazer isso em todos os arquivos XML. O que estou fazendo errado?

A: Há uma resposta no stackoverflow em inglês que fornece uma base para solucionar seu problema. O problema é que a extensão simple load xml, não consegue fazer o parse dos namespaces presentes no seu xml. Isso pode ser contornado com a função children. Colocando tudo junto fica:
<?php
$x = simplexml_load_file('xml/teste.xml');
$campos = $x->children('soap', true)->children('cad', true)->children('usu', true)->UsuarioSUS->Cartoes->CNS->children('cns', true);

foreach($campos as $chave => $valor){
    echo $chave . ' : ' . $valor . '<br>';
}

?>

Há um pequeno erro no xml postado na pergunta. Falta colocar no final do arquivo o fechamento </soap:Envelope>.


text:
Q: Can i add an animation from crazy talk 7 into a whole keynote presentation? I want to do a presentation with keynote and with Crazy talk 7, but i would like to know how to lay the animation over the entire keynote presentation, how can i do that?

A: With CrazyTalk7 you can output your creations as videos or images in different sizes, resolutions and file formats. You can convert your work to an AVI file in DVD, HD, iPad and iPhone quality. You may also convert it into sequenced image (BMP/JPG/TGA/PNG) files to broadcast on a web server.
If you wish to import a photo or movie into Keynote the most convenient way to do it is by dragging the file directly into Keynote. Just drop it onto you slide.
You can also import media by choosing Insert > Choose from the top menu.
Hope this helps answer your question.
If you have any further questions please contact Reallusion Customer Support directly using the link below. The support team will gladly help you.
http://www.reallusion.com/CustomerSupport/User/QForm.aspx


text:
Q: Finding the maximal `t` at which `u[x,t] == 1`? Given the smooth function u[x,t] on a domain, how do I find the maximal t at which u[x,t] == 1 (leaving x unconstrained)?
I can plot the level curve with
ContourPlot[ u[x,t] == 1, {x, -50, -58}, {t, 50, 58} ]

but I'm not sure how to numerically locate the point I want.
Edit: My u is the solution to a PDE:
sol = NDSolve[
      { D[u[x, t], t] == D[u[x, t], x, x]
          + D[u[x, t], x] - u[x, t]^3
          + 3 u[x, t]^2 -2 u[x, t],
        u[x, 0] == 3 Exp[-x^2 /6],
        u[-100, t] == 0,
        u[30, t] == 0 },
        u, {x, -100, 30}, {t, 0, 100}]

The point of interest lies in the domain $-58<x<-50$ and $50<t<58$.

A: Before any real answer appears:
ContourPlot[Evaluate[u[x, t] /. sol] == 1, {x, -50, -58}, {t, 50, 58}
 ] //  Normal // Cases[#, Line[x__] :> x, Infinity][[ 1, ;; , 2]] & // Max

56.0628

...and the real answer:
U = u /. sol[[ 1]]

FindRoot[{U[x, t] == 1, D[U[x, t], x] == 0}, {{x, -56}, {t, 54}}]

{x -> -56.0326, t -> 56.0635}

So graphical method was not so bad. :)

A: Following the trend of posting alternative methods and skipping the obvious
NMaximize[{t, sol[x, t] == 1, -58 <= x <= 50, 50 <= t <= 58}, {x, t}]
max = SortBy[PixelValuePositions[
        i = Binarize@Image[ContourPlot[s[x, t] == 1, {x, -50, -58}, {t, 50, 58},
               Frame -> False, PlotRangePadding -> None], ImageSize->2500], Min], -#[[2]] &][[1, 2]]

N@Rescale[max, {1, ImageDimensions[i][[2]]}, {50, 58}]
(*
 56.0632
*)

Some precision is scarified to get errr ... whatever


text:
Q: Why does my bot.get_user(user_id) return me none in discord.py? I'm coding a discord bot with python and I have a problem.
Here is my code :
import discord
from discord.utils import get
from discord.ext import commands

#Créer une instance du bot
bot = commands.Bot(command_prefix='!')

#Donner le jeton pour l'identifier
jeton = "Here is the token"

#Detecter quand le bot est allumé
@bot.event
async def on_ready():
    print("Bot Prêt")
    await bot.change_presence(status=discord.Status.idle, activity=discord.Game('Hello World !'))
    print("Bonjour")

@bot.event
async def on_raw_reaction_add(payload):

    user_id = payload.user_id
    emoji = payload.emoji.name
    canal = payload.channel_id
    message = payload.message_id
    membre = bot.get_user(user_id)

    if canal == 826772563715555358 and message == 826773226675896340 and emoji == "python":
        print("Grade ajouté !")
        print(membre)

@bot.event
async def on_raw_reaction_remove(payload):

    emoji = payload.emoji.name
    canal = payload.channel_id
    message = payload.message_id

    if canal == 826772563715555358 and message == 826773226675896340 and emoji == "python":
        print("Grade enlevé !")

#Créer la commande !regles
@bot.command()
async def regles(ctx):
    await ctx.send("Les règles : \n1. Pas d'insulte \n2. Pas de double compte \n3. Pas de spam")

#Créer la commande !bienvenue
@bot.command()
async def bienvenue(ctx, member: discord.Member):
    pseudo = member.mention
    await ctx.send(f"Bienvenue {pseudo} ! ")

#tester l'erreur de la commande
@bienvenue.error
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Veuillez préciser une personne")

#Connecter le bot
bot.run(jeton)

But in the on_raw_reaction_add, when I print the member, it returns me none. Why ? To get it, I used bot.get_user(user_id).
Thank you very much.
PS : Sorry for the variables and comments in french because I am french

A: Usually and the most common reason for events to return none instead of a valid member is caused by unabled member intents.
Events that require access to a member must require the member intents to be enabled.
Intents can be enabled from Discord developer portal, from there you only need to make sure you have enabled Member in intents within the "Bot" category. You'd then need to define and use the intents in your bot code in the section you define your bot or client:
Use the following code in your code to define and access Discord's member intents
intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix='!', intents=intents)

Make sure to replace bot = commands.Bot(command_prefix='!') with the code above


text:
Q: Magento 1.9.3.4 Mails not sending I`ve my store on 1.9.3.4 and now my customers are not receiving order confirmation email, Contact us mail, new registration mail, forget password mail.
I tried sending through the admin panel but nothing happens, also no update email is being received. Any one can help me with this problem for magento 1.9.3.4?
My site is on Go Daddy server.
I have checked using script "mail.php" using this Mails are going.
Even I have checked var folder therew is no "log" folder.

A: Either your php mail is not serving requests or You are missing some network protocols to allow port25 open to world.

A: You have to properly configure your settings to work with GoDaddy's email service.  Assuming that you have not at all changed any of the DNS settings for the mail service, and are using GoDaddy's default mail settings, then you are likely not able to send mail for a couple reasons, of which I would certainly consider any of the following:

*

*GoDaddy has some security measures in place with respect to insecure, non-patched Zend Framework Mail functionality.

*GoDaddy has purposefully not allowed default mailing functionality due to some sort of compliance with anti-spam policies

*You've already been black-listed mailing from the IP, which could be on a shared server.

Try getting GoDaddy's mail settings for configuring an external mail program (such as outlook) using smtp, then apply those settings to Magento's configuration for sending email using SMTP.  If needed, download an extension that will help with SMTP email.
Use tools such as mxtoolbox (search google for mxtoolbox) to help determine issues such as blacklisted, or improper DNS settings.
Consider that PHP 5.4 has been at EOL for a couple years and perhaps GoDaddy has responded with removal of known issues affecting security.

Final Answer
You have to use godaddy's servers, even if sending from gmail SMTP.
For example, sending from GMail smtp, you'll need to configure the SMTP host to relay-hosting.secureserver.net:

*

*"Send all emails via SMTP"

*"Set the return-path to match the From E-mail"

*"SMTP Host: relay-hosting.secureserver.net"

*"SMTP Port: 25"

*"No Encryption"

*"No SMTP Authentication"

PHP Mailing example using above:
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = "relay-hosting.secureserver.net";
$mail->Username = "your-account@gmail.com";
$mail->Password = "yourpassword";


text:
Q: ocamlfind complains no implementation provided for modules installed through opam I was messing around with the OCaml FFI to try to figure out how it goes about inferring the width of a C enum (which I think is implementation-defined for C) and am trying to insert a type of the wrong width to see what blows up at runtime. That's the motivation, but the actual issue I ran into is much more mundane.
I have a simple OCaml file that uses the C FFI to call a trivial function in example.c that converts an enum to an int.
open Printf;;

let (@->) = Ctypes.(@->);;
let returning = Ctypes.returning;;

let foreign = Foreign.foreign;;

(* deliberately use the wrong scalar type for argument *)
let wrong_int64_of_color =
  foreign "int_of_color" (Ctypes.int64_t @-> returning Ctypes.int64_t);;

let main () =
  printf "%Ld\n" (wrong_int64_of_color (Int64.of_int 100));;

let () = main ();;

I configured opam and installed Ctypes and Ctypes.Foreign
    % opam config env | sed -e 's/=.*/=/'
CAML_LD_LIBRARY_PATH=
OPAMUTF8MSGS=
MANPATH=
PERL5LIB=
OCAML_TOPLEVEL_PATH=
PATH=

% opam list | grep ctypes
ctypes                      0.6.2  Combinators for binding to C libraries withou
ctypes-foreign              0.4.0  Virtual package for enabling the ctypes.forei

The two usual incantations I use for compiling a simple .ml script have both failed me and I'm out of ideas. ocamlfind and corebuild (which I think is a wrapper on top of ocamlbuild)
ocamlfind can't seem to find ctypes and foreign. However, it doesn't complain that about not being able to locate the packages so I'm guessing ctypes and ctypes.foreign are the correct names for these packages in the weird findlib namespace.
% ocamlfind ocamlopt -package findlib,ctypes,ctypes.foreign -thread call_example.ml
File "_none_", line 1:
Warning 58: no cmx file was found in path for module Foreign, and its interface was not compiled with -opaque
File "call_example.ml", line 1:
Error: No implementations provided for the following modules:
         Ctypes referenced from call_example.cmx
         Foreign referenced from call_example.cmx

Why can't ocamlfind locate these modules? I have no problem loading them into the toplevel.
─( 22:30:42 )─< command 0
utop # #require "ctypes";;
─( 22:30:42 )─< command 1
utop # open Ctypes;;
─( 22:30:55 )─< command 2
utop # #require "ctypes.foreign";;
─( 22:31:00 )─< command 3
utop # open Ctypes;;

A: It seems to me that you forget to add -linkpkg ocamlfind option to instruct the compiler actually link the libraries from the packages to build the executable.