text:
Q: And function with SHL FUNCTION ,,,,,01011011b and 11000111b ;;;I am trying to display the results as an ascii string of binary digits.
I am using the shl instruction to isolate each bit and jump on carry. All that I can get to print is garble. Can someone lend a hand?
    .stack 100h
    .model small
    .386

    .data

    str1  db  20 dup(?)
    lstring EQU 9

    .code

main:
    mov ax, @data                ; initialize DS
    mov ds, ax
    mov cx, lstring
L1:
    mov al,01011011b
    and al,11000111b
    shl al, 1
    mov str1, al
    mov ax, 8
    loop L1

    mov ax, 4000h                   ;   dos service to display...
    mov bx, 1                   ;   to screen
    mov cx, lstring             ;   number of bytes
    mov dx, OFFSET str1         ;   where to get data
    int 21h

    MOV AH, 4CH                 ; return control to DOS
    INT 21H

end main

A: You should address your output string str1 dynamically, using a register. DI is the best choice:
  mov di,str1 ; Address of the first byte of output string.
  mov cx,8 ; Number of bits to print.
L1:
  shl al,1 ; Put the most significant bit of AL to CF.
  mov dl,'0' ; Output ASCII character.
  adc dl,0  ; Change it from '0' to '1' when CF was set.
  mov [di],dl ; Store the ASCII character to output string.
  inc di ; Let di point to the next character.
  loop L1 ; Repeat with remaining bits.


text:
Q: Проблема с Pymem. Или какие вообще есть способы подключиться к модулю (dll) процесса в Windows? Для тренировки решил попробовать написать простейший чит. Т.к. по читам для CS:GO очень много гайдов, то выбор пал именно на неё.
Пробую подключиться к DLL для модификации памяти процесса. В гугле нашёл этот код:
pm = pymem.Pymem("csgo.exe")
client = client = pymem.process.module_from_name(pm.process_id, "client_panorama.dll")

Но client присваивается значение None, тогда как у всех остальных всё работает. Возможно причина в том, что процесс 32 бита, а питон - 64?
Какие вообще есть способы найти адрес DLL процесса силами питона?
Версия Python - 3.6, система - Windows 10 x64, версия pymem - самая последняя из pip.

A: Ничего не могу сказать про pymem, никогда им не пользовался, но знаю, что память другого процесса можно модифицировать с помощью ctypes:
memchange.py
import sys
import ctypes
import ctypes.wintypes as wintypes

PROCESS_ALL_ACCESS = 0x1F0FFF

kernel32 = ctypes.windll.kernel32

kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.OpenProcess.argtypes = [
    wintypes.DWORD,
    wintypes.BOOL,
    wintypes.DWORD
]

kernel32.CloseHandle.restype = wintypes.BOOL
kernel32.CloseHandle.argtypes = [ wintypes.HANDLE ]

kernel32.WriteProcessMemory.restype = wintypes.BOOL
kernel32.WriteProcessMemory.argtypes = [
    wintypes.HANDLE,
    wintypes.LPVOID,
    wintypes.LPCVOID,
    ctypes.c_size_t,
    ctypes.POINTER(ctypes.c_size_t)
]

pid = int(sys.argv[1])
addr = int(sys.argv[2], 16)

val = 42
buf = (val).to_bytes(4, byteorder='little')
buf_ptr = ctypes.c_char_p(buf)

ph = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
kernel32.WriteProcessMemory(ph, addr, buf_ptr, len(buf), None)
kernel32.CloseHandle(ph)

Для краткости из кода выброшены все проверки.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vector Field Definition(on open subsets of $\mathbb{R}^n$). I'm reading An Introduction to Differentiable Manifolds and Riemannian Geometry, Revised by Boothby.
I'm reading the second chapter right now, and in this chapter, the tangent space $T_p(\mathbb{R}^n)$ for $p \in \mathbb{R}^n$ is defined by the vector space of line segment starting at $p$.
The canonical basis, $E_{1a}, \ldots, E_{na}$ for $T_a(\mathbb{R}^n)$ is the line segment connecting $a$ to $a + e_i$ where $e_i = (0,0,....,1,0...0)$.

Now, the vector field on $U \subseteq \mathbb{R}^n$ is defined as a function sending $p \in U$ to a vector $X_p \in T_p(U)$.

Now it says to define vector field $E_i$ by sending each $p \in \mathbb{R}^n$ to the naturally defined basis vector.

I assume this means that for each $p$, send it to $E_{ip} \in T_p(\mathbb{R}^n)$. So for example, the vector field $E_1$ would send $(1,1)$ to line segment connecting $(1,1)$ and $(2,1)$.
Now, they set $U = \mathbb{R}^2 - 0$ and define $X_1 = x_1 E_1 - x_2 E_2$ and $X_2 = -x_2 E_1 +x_1 E_2$.
So I assume this is the vector field sending $p = (x_1, x_2)$ to the vector $x_1 E_1 - x_2 E_2 \in T_p(\mathbb{R}^2)$.

Now here is the problem. Let's say $p = (1,1)$. Then $X_1$ sends $p$ to $E_{1p} - E_{2p} \in T_p(\mathbb{R}^2)$, which is a line segment connecting $(1,1)$ to $(2,0)$, which would go against what the figure says.
And $X_2$ would send $p$ to a line segment connecting $(1,1)$ to $(0,2)$, which is against the figure again.
So what am I misunderstanding here?
Thank you!


text:
Q: pass href text to modal I have a table with usernames and the names of the users are links which when clicked show a modal. In this modal, the user's password can be changed. I want to get the text of the href in the modal. My code is below:

    username

I want to see the username that was clicked in the modal.

                <button type="button" class="close" data-dismiss="modal">×</button>

User Edit

                <form class="forma" role="form" method="POST" action="#">

                            Password

                            <input type="text" name="newpass" class="form-control" placeholder="Password must be 8 charachters long!" id="newpass" maxlength="20" />

                            Retype Password

                            <input type="password" name="newpass2" class="form-control" placeholder="Retype Password" id="newpass2" onkeyup="checkPass(); return false;" maxlength="20"/>

                    <button type="submit" class="btn btn-default" id="btn1" >Submit</button>
                </form>

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: You can use .on(shown.bs.modal) of bootstrap as below and get its relatedTarget of event and fetch its text as below:
DEMO
$('#useredit').on('shown.bs.modal',function(e){
    $(this).find('.modal-title').html($(e.relatedTarget).text());
});

A: Two ways to achieve this
1st way
Here is the link to learn how to use href to modal
http://tutsme-webdesign.info/bootstrap-3-1-and-modals-with-remote-content/
2nd way (easiest way) :
Step 1 : Download bootbox.js from link http://bootboxjs.com/
and use it in your project.

Step 2:
Use function bootbox.dialog and pass your href url in message parameter
bootbox.dialog takes many parameters, some of they are:
1) title: title of the modal popup
2) message: you can pass content here using Jquery function
 e.g:  $('').load(url),
3) onEscape : by pressing escape key , modal will automatically close
Here is the detail example by using bootbox.js:

 function OpenRemoteUrl()
{
     var url = 'https://www.google.co.in';
         bootbox.dialog(
               {
                   title: "title of the modal box here",
                   message: $('

').load(url),
                   backdrop: true,
                   keyboard: true,
                   onEscape: function () { }
               });
 }

I am using bootbox.js in my project for bootstrap based project, and it is the easiest way to open a modal pop up for remote url
You can learn all the documentation from http://bootboxjs.com


text:
Q: Creating p-interesting graphs
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
?
the graph contains exactly 2n + p edges;
the graph doesn't contain self-loops and multiple edges;
for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.

This a question from codeforces, https://codeforces.com/blog/entry/10972. However, I am finding the explanation impossible to understand. Does anyone understand why we are only considering 0 and 3-interesting subgraphs? To me, a triangle is a loop.


text:
Q: How to know send() or sendmsg() successfully deliver message? I set up a simple client and server program using TCP socket to communicate. The server waits for the client to connect and reply whether it receives the message from the client. Below is how the code is implemented in the server and the client:
Code on the server-side:
 listen(sockfd,5);

 clilen = sizeof(cli_addr);
 newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

 if (newsockfd < 0)
      error("ERROR on accept");
 bzero(buffer,256);

 n = read(newsockfd,buffer,255);

 if (n < 0)
     error("ERROR reading from socket");

 printf("Here is the message: %s\n",buffer);

 n = write(newsockfd,"I got your message",18);

 if (n < 0)
     error("ERROR writing to socket");

Code on the client-side:
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
    error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
     error("ERROR writing to socket");
else
    printf("sucess. n = %d", n);

bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
     error("ERROR reading from socket");

Now, assume that I starts the server and then starts the client, the client successfully connects to the server. Then I shuts down the server and tries to send a message from the client, the write() operation returns no error. What I expect here is an error because the server actually does not receive any packets (it is shut down).
So my question is: is there any way to know whether the write() (or send(), sendto() or sendmsg()) successfully delivers the message to the server?

A: No. Write or send just do the talking, they don't wait for feedback (e.g. ACK in case of TCP). But you can only be sure that the message was delivered successfully, if you got some kind of feedback. It does not even help to try another send because it might be executed while the previous message is not yet at the client. It also does not help to recv and hope for error, because the data you receive might hace been sent by the peer before you even sent your message. The only way to be really sure is to put some kind of explicit handshake in your application protocol and wait for the matching response to your message.

A: It does not work that way. write() returns success as soon as message fits in the send buffer. The only way to know that message was received and processed by the server is receiving e parsing the "I got your message".
write() returns -1 then the connection is already known to be closed or invalid, but don't count on that to detect all possible errors.


text:
Q: How to implement Isotope - Elements Complete on the iphone? Please go to:
http://isotope.metafizzy.co/demos/elements-complete.html
I want to implement on the iPhone the "Toggle variable size" part.
To be more specific, I want to layout my 30+ photos (same size) on a scroll-view and i want it to look like "Toggle variable size" looks like.
The implementation needs to be native, I guess via view-controller or some table-view with custom cells.
Do you have any thoughts on whats the best way to implement this on the iPhone?

A: In this answer I will line out a very high level overview of how I would aproach your problem.
Create a custom scroll view subclass, lets say TiledGridView. For simplicity, let's assume that the interface looks like similar to this:
@interface TiledGridView : UIScrollView {
    NSArray *tileData;
}
@property(retain) NSArray *tileData;
- (void)layoutSubviews;
@end

The tileData array contains information about the tiles (location, size, and the image). You set tileData using the synthesized accessors in the simplest case. You can create a ViewController that actually calculates the positions of the tiles, or you can add a method in the view. For further discussion, lets assume that tileData contains all the data about the tiles we need, and that we already know their positions etc.
Then, the most important part is to override the layoutSubviews message in your subclass. In layoutSubviews you will do the following:

*

*check the bounds of the TiledGridView

*add UIImageViews (or whatever you like) for tiles that are within those bounds

*remove tiles outside the bounds

You do it so that you don't run out of memory when you have many images. This is also what UITableView does, but they even reuse views.
A pseudo-implementation could look similar to this:
- (void)layoutSubviews {
  CGRect bounds = self.bounds;

  for (id tile in tileData) {
    if (/*tile is not yet visible and tile overlaps bounds*/) {
      UIView newTileView = /* create the view for the tile */
      [self insertSubview:newTileView atIndex:0];
   } else if (/*tile is visible and no longer overlaps bounds*/) {
      UIView oldTileView = /* fetch the corresponding view */
      [oldTileView removeFromSuperview];
    }
  }

This will make your view very fast, as subviews are added only as needed.


text:
Q: Windows Server 2012 R2 FTP folders do not refresh data automatically I have set up a new IIS FTP Service in our local subnet and added 40 user accounts. Everything works successfully except one thing: whatever is written by the server inside a user's folder, does not appear on his mapped Windows 7 drive automatically, neither by refreshing it.
Only hack that works is creating a new file with New -> Text Document and then everything appears. It seems that the new file creation somehow "triggers" the folder to fetch data. What could be the fault ?


text:
Q: windows phone 8.1 call rest api c# I am developing one windows phone 8.1 app. In this app I required to call restful apis. Here is my api call method
public static async Task<HttpResponseMessage> callrestApi(string baseurl, string api, string method, string contenttype, object objPost)
{
    try
    {
        HttpResponseMessage response = null;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseurl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contenttype));

            switch (method.ToLower())
            {
                case "get":
                    // HTTP GET
                    response = await client.GetAsync(api);
                    if (response.IsSuccessStatusCode)
                    {
                        object obj = await response.Content.ReadAsStringAsync();
                        //return obj;
                    }
                    break;
                case "post":
                    // HTTP POST
                    response = await client.PostAsync(api, new StringContent(objPost.ToString(), Encoding.UTF8, contenttype));
                    if (response.IsSuccessStatusCode)
                    {
                        object obj = await response.Content.ReadAsStringAsync();
                        //return obj;
                    }
                    break;
                default:
                    break;
            }
        }
        return response;
    }
    catch (Exception)
    {
        return null;
    }
}

I am calling this method from MainPage.xaml for login. I am passing json obj with username and password.
var resp = await Constants.callrestApi(Constants.base_Url, Constants.apiList.loginApi, Constants.httpmethod.post, Constants.contenttype.json, jsonObj);
if (resp != null)
{

}

When I debug this I am getting following error

error CS0012: The type 'HttpResponseMessage' is defined in an assembly that is not referenced.
  You must add a reference to assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I think the problem is in await call. How can I call restful api?

A: In the description of the error it says that you have not added the assembly named System.Net.Http to your references. Just try to right-click on the references [image 1] of your app and select Add reference. Find System.Net.Http in the list of Frameworks and add it to your project [image 2].

[EDITED FROM HERE]
Since that is not the issue, I have put together a small example of a method that calls a REST API (async). Let me know if this works for you, and if not provide some more details about the API.
public async Task<string> callRestAPI(string serviceURL)
{
    var getRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, serviceURL);

    var postRequest = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, serviceURL);
    postRequest.Content = new StringContent("string data");

    using (var httpClient = new System.Net.Http.HttpClient())
    {
        var getResponse = await httpClient.SendAsync(getRequest);
        var postResponse = await httpClient.SendAsync(postRequest);
        var getData = await getResponse.Content.ReadAsStringAsync();
        var postData = await postResponse.Content.ReadAsStringAsync();

        Debug.WriteLine(getData);
        Debug.WriteLine(postData);

        return getData;
    }
}

I am calling the method just for testing in the OnNavigatedTo method as follows:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    // TODO: Prepare page for display here.

    // TODO: If your application contains multiple pages, ensure that you are
    // handling the hardware Back button by registering for the
    // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
    // If you are using the NavigationHelper provided by some templates,
    // this event is handled for you.

    var testResult = await callRestAPI("~your URL here~");
}

A: You have to add the Microsoft.Net.Http NuGet package for Windows Phone (and other platforms as well). You can find the package information here:
https://www.nuget.org/packages/Microsoft.Net.Http/
Either add this via command line or right click on the project, then select Manage NuGet Packages, then search for Microsoft.Net.Http and finally select Install.
Using the package manager console you can use the following command to add this package to your project.
Install-Package Microsoft.Net.Http


text:
Q: Error while deploying an EJB in JBOSS-Failed to load component class I am using Jboss-6.1.0. I am trying to create an EJB to print Hello world. I have three classess.
1.
    package remoteif;

    import java.rmi.*;
    import javax.ejb.*;
    public interface HelloWorld extends EJBObject{
        public String sayHello() throws RemoteException;
    }

2.
    package homeif;

    import remoteif.HelloWorld;

    import javax.ejb.CreateException;
    import javax.ejb.EJBHome;
    import java.rmi.RemoteException;

    public interface HelloWorldHome extends EJBHome {
        public HelloWorld create() throws
                CreateException, RemoteException;

    }

and
3.
        package beanimpl;
    import remoteif.HelloWorld;

    import javax.ejb.*;
    import java.rmi.RemoteException;

    public class HelloWorldBean implements SessionBean {
        // Methods of Remote interface
        public String sayHello() {
            return "Hello, world !";
        }
        // Methods of Home interface
        public void ejbCreate() {}

        protected SessionContext ctx;
        public void setSessionContext(SessionContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void ejbRemove() throws EJBException, RemoteException {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void ejbActivate() throws EJBException, RemoteException {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void ejbPassivate() throws EJBException, RemoteException {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }

I am using two xml files ejb-jat.xml &jonas-ejb-jar.xml inside the META-INF directory. I have created jar file of this application (includes the class files and the xml files) and ear file that includes this jar file and the application.xml file. I have copied it in the JBOSS server. But when I am starting the server ,I am getting the following error.

ERROR [AbstractKernelController] Error installing to Real: name=vfs:///data/EJB/jboss-6.1.0.Final/server/wsdl/deploy/EjbSample.ear state=PreReal mode=Manual requiredState=Real: org.jboss.deployers.spi.DeploymentException: Error during deploy: vfs:///data/EJB/jboss-6.1.0.Final/server/wsdl/deploy/EjbSample.ear/ejbDemo.jar/
    at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:185) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1832) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1550) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1603) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1491) [:2.2.2.GA]
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.change(DeployersImpl.java:1983) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:1076) [:2.2.2.GA]
    at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:679) [:2.2.2.GA]
    at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.process(MainDeployerPlugin.java:106) [:6.1.0.Final]
    at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.process(ProfileControllerContext.java:143) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileDeployAction.deploy(ProfileDeployAction.java:151) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileDeployAction.installActionInternal(ProfileDeployAction.java:94) [:0.2.2]
    at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) [jboss-kernel.jar:2.2.0.SP2]
    at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) [jboss-kernel.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.SP2]
    at org.jboss.profileservice.dependency.ProfileActivationWrapper$BasicProfileActivation.start(ProfileActivationWrapper.java:190) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileActivationWrapper.start(ProfileActivationWrapper.java:87) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileActivationService.activateProfile(ProfileActivationService.java:215) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileActivationService.activate(ProfileActivationService.java:159) [:0.2.2]
    at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.activate(AbstractProfileServiceBootstrap.java:112) [:0.2.2]
    at org.jboss.profileservice.resolver.BasicResolverFactory$ProfileResolverFacade.deploy(BasicResolverFactory.java:87) [:0.2.2]
    at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2]
    at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.1.0.Final]
    at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.1.0.Final]
    at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6]
    at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6]
    at java.lang.Thread.run(Thread.java:662) [:1.6.0_45]
Caused by: java.lang.RuntimeException: Failed to load component class: HelloWorldBean from loader: BaseClassLoader@192c07a{vfs:///data/EJB/jboss-6.1.0.Final/server/wsdl/deploy/EjbSample.ear}
    at org.jboss.webservices.integration.deployers.WSEJBAdapterDeployer$WebServiceDeclarationAdapter.getComponentClass(WSEJBAdapterDeployer.java:232) [:6.1.0.Final]
    at org.jboss.webservices.integration.deployers.WSEJBAdapterDeployer$WebServiceDeclarationAdapter.getAnnotation(WSEJBAdapterDeployer.java:214) [:6.1.0.Final]
    at org.jboss.webservices.integration.util.ASHelper.isWebServiceBean(ASHelper.java:239) [:6.1.0.Final]
    at org.jboss.webservices.integration.util.ASHelper.getJaxwsEjbs(ASHelper.java:222) [:6.1.0.Final]
    at org.jboss.webservices.integration.deployers.WSTypeDeployer.isJaxwsEjbDeployment(WSTypeDeployer.java:140) [:6.1.0.Final]
    at org.jboss.webservices.integration.deployers.WSTypeDeployer.internalDeploy(WSTypeDeployer.java:73) [:6.1.0.Final]
    at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55) [:2.2.2.GA]
    at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179) [:2.2.2.GA]
    ... 44 more

08:47:08,518 INFO  [HornetQServerImpl] trying to deploy queue jms.queue.DLQ
08:47:08,667 INFO  [HornetQServerImpl] trying to deploy queue jms.queue.ExpiryQueue
08:47:08,696 INFO  [service] Removing bootstrap log handlers
08:47:08,791 ERROR [ProfileServiceBootstrap] Failed to load profile:: org.jboss.deployers.client.spi.IncompleteDeploymentException: Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS):

DEPLOYMENTS IN ERROR:
  Deployment "vfs:///data/EJB/jboss-6.1.0.Final/server/wsdl/deploy/EjbSample.ear" is in error due to the following reason(s): java.lang.RuntimeException: Failed to load component class: HelloWorldBean from loader: BaseClassLoader@192c07a{vfs:///data/EJB/jboss-6.1.0.Final/server/wsdl/deploy/EjbSample.ear}

    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:1228) [:2.2.2.GA]
    at org.jboss.deployers.plugins.main.MainDeployerImpl.checkComplete(MainDeployerImpl.java:905) [:2.2.2.GA]
    at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.checkComplete(MainDeployerPlugin.java:87) [:6.1.0.Final]
    at org.jboss.profileservice.deployment.ProfileDeployerPluginRegistry.checkAllComplete(ProfileDeployerPluginRegistry.java:107) [:0.2.2]
    at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:135) [:6.1.0.Final]
    at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.1.0.Final]
    at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6]
    at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6]
    at java.lang.Thread.run(Thread.java:662) [:1.6.0_45]

What should I do to clear this error?


text:
Q: TypeError cv2.rect Am trying to implement an object detection model on an image using ssd_inception_v2_coco_2018_01_28 model. Am trying to get the output with a bounding box on top.
1) ssd_inception_v2_coco_2018_01_28 object detection model. Successfully converted to IR.
2) Taken an input image and preprocessed it according to the input layer information of the model.
3) Successfully extracted the model outputs.
4) Added bounding boxes to the output image.
But am getting the following error, please help!
Source Code
#Preprocessing image

img = r'D:\SriSailam.jpg'
img = cv2.imread(img)
img = cv2.resize(img,(300,300))
img = img.transpose((2,0,1))
img = img.reshape(1,3,300,300)

exec_net = engine.load_network(net,'cpu')

#Asynchronous request

infer_request_handle = exec_net.start_async(request_id=0, inputs={'image_tensor': img})
infer_status = infer_request_handle.wait()
output = next(iter(net.outputs))

n,c,h,w = img.shape

result = infer_request_handle.outputs[output]  #output layer shape

'''
Draw bounding boxes onto the image.
'''
for box in result[0][0]: # Output shape is 1x1x100x7
        conf = box[2]  #box[2] = result[0][0][2] is a probability value
        print("probability value : ",conf)
        print("box[0] : ",box[0])
        print("box[1] : ",box[1])
        print("xmin : ", box[3])
        print("ymin : ", box[4])
        print("xmax : ", box[5])
        print("ymax : ", box[6])

        if conf >= 0:
            xmin = int(box[3] * w)  #box[3] - xmin
            ymin = int(box[4] * h) #box[4] - ymin
            xmax = int(box[5] * w)  #box[5] - xmax
            ymax = int(box[6] * h) #box[6] - ymax
            rect = cv2.rectangle(img, ((xmin), (ymin)), ((xmax), (ymax)), (0, 0, 255), 1)
cv2.imshow(rect,'face_detection')
cv2.waitKey(0)

Output
C:\Users\adity\Desktop\openvino>py check_infer.py
probability value :  0.6344592
box[0] :  0.0
box[1] :  1.0
xmin :  0.1831626
ymin :  0.10697469
xmax :  0.86960804
ymax :  1.0
Traceback (most recent call last):
  File "check_infer.py", line 68, in <module>
    rect = cv2.rectangle(img, ((xmin), (ymin)), ((xmax), (ymax)), (0, 0, 255), 1)
TypeError: an integer is required (got type tuple)

A: Reproduced your error.
The error message is pretty confusing in this version of OpenCV (4.2.0).
If you do the same in OpenCV 4.3.0 you will get a more intelligible error like
  File "<stdin>", line 1, in <module>
TypeError: Expected Ptr<cv::UMat> for argument 'img'

Which basically says that img argument you passed into cv2.rectangle has a wrong type.
The problem is that after you call
img = img.transpose((2,0,1))
img = img.reshape(1,3,300,300)

img cannot be interpreted as an image by OpenCV.
The issue can be solved, for example, this way:
1. Copy img before the transformation to another variable imgForDisplaying
2. Use imgForDisplaying to draw rectangle.
img = r'D:\SriSailam.jpg'
img = cv2.imread(img)
img = cv2.resize(img,(300,300))
imgToDisplay = img
img = img.transpose((2,0,1))
img = img.reshape(1,3,300,300)
...
rect = cv2.rectangle(imgToDisplay, (xmin, ymin), (xmax, ymax), (0, 0, 255), 1)


text:
Q: J. Feinstein Sliding Menu check if open I used J. Feinstein library to make awesome sliding menu(thanks for J. Feinstein), but I need to know whether sliding menu is opened or closed. I need to know because I have implemented ABC action bar while in some condition, sliding menu opened and user can open navigation drawer and make my app dimmed(overlay from navigation drawer).
I know from documentation, slidingMenu.toggle() can automatically check condition of sliding menu, whether is closed or opened(If it is open, it will be closed, and vice versa). but please see my code bellow:
            @Override
            public void onDrawerOpened(View drawerView) {
                // here i wanna check if sliding menu opened or closed
                if(isOpened)
                  // if is opened then close the sliding menu first
                  menu.toggle();

                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

I want to check if sliding menu opened, then close sliding menu first and then draw navigation after that. How to do that?
Many thanks.

A: if you need to check sliding menu is opened or closed, you can use this code bellow :
// Check whether sliding menu is opened or closed
if(menu.isMenuShowing()){
  //Do action here
}

in my case, i need to close sliding menu first and then open navigation drawer, so here the code :
@Override
public boolean onCreateOptionsMenu(Menu menuActionBar) {
  if (!mNavigationDrawerFragment.isDrawerOpen()) {
    getMenuInflater().inflate(R.menu.main, menuActionBar);
    restoreActionBar();
    return true;
  }else{
    if(menu.isMenuShowing()){
      menu.toggle();
    }
  }
  return super.onCreateOptionsMenu(menuActionBar);
}

I hope this solution will help others. Thanks for Stackoverflow and J. Feinstein.


text:
Q: g++ rejects my simple functor with "expected a type, got 'xyz'" I've been playing about with functors in C++. In particular, I've got a vector of pairs I'd like to sort by the first element of the pair. I started off writing a completely specialised functor (i.e. something like "bool MyLessThan(MyPair &lhs, MyPair &rhs)"). Then, just because this sort of stuff is interesting, I wanted to try writing a generic "Apply F to the first elements of this pair" functor. I wrote the below, but g++ doesn't like it. I get:
error: type/value mismatch at argument 2 in template parameter list for 'template struct Pair1stFunc2'
error:   expected a type, got 'less'
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>

template <class P, class F>
struct Pair1stFunc2
{
    typename F::result_type operator()(P &lhs, P &rhs) const
    { return F(lhs.first, rhs.first); }

    typename F::result_type operator()(const P &lhs, const P &rhs) const
    { return F(lhs.first, rhs.first); }
};

typedef std::pair<int,int> MyPair;
typedef std::vector<MyPair> MyPairList;

MyPairList pairs;

void foo(void)
{
    std::sort(pairs.begin(),
              pairs.end(),
              Pair1stFunc2<MyPair, std::less>());
}

Can anyone shed any light on what I'm doing wrong here? I know this is as slightly artificial example, but I'd like to know what's going on, if only to improve my STL-fu.

A: To expand on dirkgently's answer, here's an example of what might work as you intend:
template <typename T, template <typename> class F>
struct Pair1stFunc2
{
    template <typename P>
    typename F<T>::result_type operator()(P &lhs, P &rhs) const
    { F<T> f; return f(lhs.first, rhs.first); }

    template <typename P>
    typename F<T>::result_type operator()(const P &lhs, const P &rhs) const
    { F<T> f; return f(lhs.first, rhs.first); }
};

void foo(void)
{
    std::sort(pairs.begin(),
              pairs.end(),
              Pair1stFunc2<int, std::less>());
}

Note that it works, but it might not be exactly what you had in mind.

A: Note that std::less is itself a template and you do not specify the template template parameter when you call it from with foo() function's sort! Here less is an incomplete type and hence the problem.

A: You need to specialize std::less with the comparison type you're using.
Pair1stFunc2<MyPair, std::less<int> >()

will do the trick.  Within your own operator() you'll also need to instantiate an object of the comparison type, since you can't just call the class directly.  E.g. change
return F(lhs.first, rhs.first);

to
F func;
return func(lhs.first, rhs.first);

You could also move the specialization into the functor, as another answer suggests.

A: Similar to unwesen. But you don't need to use template templates.
#include <algorithm>
#include <functional>
#include <memory>
#include <vector>

typedef std::pair<int,int> MyPair;
typedef std::vector<MyPair> MyPairList;
MyPairList pairs;

// Same as original.
template <typename T,typename F>
struct Pair1stFunc2
{
    template <typename P>
    typename F::result_type operator()(P &lhs, P &rhs) const
    { F f;  // Just need to create an anstance of the functor to use.
      return f(lhs.first, rhs.first); }

    template <typename P>
    typename F::result_type operator()(const P &lhs, const P &rhs) const
    { F f;  // Just need to create an anstance of the functor to use.
      return f(lhs.first, rhs.first); }
};

void foo(void)
{
    std::sort(pairs.begin(),
              pairs.end(),
              Pair1stFunc2<int, std::less<int> >()); // initialize the version of less
}

A: The simplest solution would be to state what you want as an argument, a function with a suitable signature:
template<typename P, bool (*F)(P,P)> struct Pair1stFunc2 { ... }

In this case, passing a function template as the second argument will cause overload resolution to be done on it with P,P as argument types. This works because you move the overload resolution out of struct Pair1stFunc2::operator()
You also want the possibility of passing in a functor, but those do need to be passed as a template type argument and then created inside operator() :
typename F::result_type operator()(const P &lhs, const P &rhs) const
{ return F()(lhs.first, rhs.first); }

Here, F is the functor type and F() an instance of that functor.
The third case is already covered earlier, the functor template. std::less is such a template. In that case, you need a template template argument.


text:
Q: How do I pass varaibles to another python file I have two files and needed to move a variable from one to the other. There is also some shell scripting involved.
For example, I have script1.py and a variable called var1.
script1.py

var1 = sys.argv[1]

When I try to import this into another Python file. For e.g.
script2.py

from script1.py import var1
print(var1)

It is actually running the sys.argv[1] again in script2.py. This is how my shell script looks.
shellcode.sh
python3 script1.py "1st parameter"
python3 script2.py "2nd"

How to get only the "1st parameter" not "2nd".
I'm a complete beginner at python and shell scripting. Is it related to pass by value? Any help would be highly appreciated.

A: pass directly arguments from script2.py it should work.
script1.py
import sys
var1 = sys.argv[1]

in script2.py
from script1 import var1
print(var1)

on shell run like this
python3 script2.py --test

Will print #
test

A: One way around this would be to use the parameter as a variable in your shell script and just pass both to the second python argument.
shellcode.sh:
#!/bin/bash
PAR1="1st paramter"
PAR2="2nd parmaeter"
python3 script1.py $PAR1
python3 script2.py $PAR1 $PAR2

Otherwise you could write and read the argument something like
script1.py:
import sys
var1 = sys.argv[1]
with open('script1_var.txt', 'w') as f:
    f.write(var1)

script2.py:
import sys
with open('script1_var.txt', 'r') as f:
    var1 = f.readlines()[0].strip()
var2 = sys.argv[1]
print('var1', var1)
print('var2', var2)


text:
Q: Writing/Reading stream of output from external command in realtime I was asked to run a python script in a Jenkins job, which calls external commands via subprocess package. In the Jenkins console, the output of the external commands should be printed in realtime or/and be writen to a log file.
I found a SO post about printing in realtime somehow like this:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
while True:
    line = p.stdout.readline()
    print (line)
    if not line and p.poll() is not None:
        break

So I created a function for executing external commands:
def execute_cmd(command, splitlines=True, timeout=None, output_stream=None):

    pipe = Popen(command, stdout=PIPE, stderr=PIPE)

    utf8_output = []
    while True:
        line = pipe.stdout.readline()
        utf8_output.append(line)
        # Add to stream here
        if output_stream:
            output_stream.write(line)
        if not line and pipe.poll() is not None:
            break

    return ''.join(utf8_output)

As you see I didn't use print. That's because a requirement tells me to use a stream object which could be either streaming to a file or to output everything to the jenkins console in realtime.
So if I want to print the external output to the jenkins console, I wanted to do something like this in my job:
from io import TextIOBase
my_output_stream = TextIOBase()
func1(output_stream=my_output_stream)

Where func1 is a function, that calls an external command via the execute_cmd method.
In my understanding this should write the output of the external command to my_output_stream
Now my question is, how can I output the data writen to that stream in realtime? Don't I need any kind of asynchronous execution? Because I can't just add a loop that reads lines of the stream after the call of func1 as this would be executed after the execution of the function has finished, but not in realtime.
Sorry for the kind of weird description of my problem, if something is still unclear, please comment and I will update my question with further explanation.


text:
Q: How to test rollback scenario in spring I need to test rollback scenario for this service:
@Service
public class MyService2 {

    private final Entity2Repo entity2Repo;

    public MyService2(Entity2Repo entity2Repo) {
        this.entity2Repo = entity2Repo;
    }

    public void create(Long entity1Id) {
        Entity2 entity2 = new Entity2();
        entity2.assignToEntity1(entity1Id);
        entity2Repo.save(entity2);
    }
}

I've created this Integration test case:
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JpaApplication.class)
public class MyServiceIntTest {

    @Autowired
    private Entity1Repo entity1Repo;

    @Autowired
    private EntityManager entityManager;

    @Test
    public void create() throws Exception {

        MyService2 mock = mock(MyService2.class);
        doThrow(new RuntimeException("bla bla")).when(mock).create(anyLong());

        MyService myService = new MyService(entity1Repo, mock);

        try {
            myService.create("some name");
            fail("should never fails");
        } catch (RuntimeException e) {
            assertThat(e.getMessage()).isEqualTo("bla bla");        // success
        }

        Entity1 dbEntity1 = (Entity1) entityManager.createQuery("from Entity1 where name = 'some name'").getSingleResult();

        assertThat(dbEntity1).isNull();                             // fail, however it should be null as it is rolled-back
    }
}

The question is, why the organization object is still saved in the Database after the rollback happens?
EDIT: Complete source code at github: https://github.com/mhewedy-playground/test-transaction-rollback

A: The problem was, I was creating the MyService object out of spring context and then expecting the transaction manager to start.
I've changed the test code to the following and now it works successfully:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JpaApplication.class)
public class MyServiceIntTest {
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private MyService myService;

    @MockBean
    private MyService2 myService2;

    @Transactional
    @Test(expected = RuntimeException.class)
    public void createWillRollback() throws Exception {

        doThrow(new RuntimeException("bla bla")).when(myService2).create(anyLong());

        myService.create("some name");

        assertThat(count()).isEqualTo(0);
    }

    @Transactional
    @Test
    public void create() throws Exception {

        doNothing().when(myService2).create(anyLong());

        myService.create("some name");

        assertThat(count()).isEqualTo(1);
    }

    private long count() {
        return ((Long) entityManager.createQuery("select count(*) from Entity1").getSingleResult());
    }
}


text:
Q: Flutter Web: How to run without a device/browser? I want to run the flutter web development server without specifying a device/browser.

A: I guess you mean without specifying browser? If so you try running it with this command :
flutter run -d web-server

A: You must to define chrome.
flutter run -d chrome

Check this documentation:
https://flutter.dev/docs/get-started/web


text:
Q: Extract specific text from webpage May I ask how to extract

*

*County name

*and answer for confirmed cases, death?

For example: {'Alabama':{'Augauta County':{'confirmed cases':'1522','death':'24'}, 'Baldwin County':{'confirmed cases':'4787','death':'7'}}}, etc
Webpage link https://usafacts.org/visualizations/coronavirus-covid-19-spread-map/state/alabama
I was able to scrape and save this webpage as a file.
Thank you so much!
Text 1
{"@type":"ImageObject","url":"https://static1.squarespace.com/static/5a1340ef914e6bf3c0764c0c/t/5dbb4885de62ca18968da164/1582662729455/?format=1500w"},"founder":"Steve Ballmer","legalName":"Ballmer Giving LLC"}},"mainEntityOfPage":"/visualizations/coronavirus-covid-19-spread-map"}</script><script data-react-helmet="true" type="application/ld+json">{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"How many COVID-19 cases in Autauga County, Alabama?","acceptedAnswer":{"@type":"Answer","text":1522}},{"@type":"Question","name":"How many COVID-19 cases in Baldwin County, Alabama?","acceptedAnswer":{"@type":"Answer","text":4787}},

Text 2
{"@type":"Question","name":"How many COVID-19 deaths in Autauga County, Alabama?","acceptedAnswer":{"@type":"Answer","text":24}},{"@type":"Question","name":"How many COVID-19 deaths in Baldwin County, Alabama?","acceptedAnswer":{"@type":"Answer","text":46}},{"@type":"Question","name":"How many COVID-19 deaths in Barbour County, Alabama?","acceptedAnswer":{"@type":"Answer","text":7}}

A: It seems that the text that you extracted is an array of json object, so just simply enclose it with a bracket and load into dict using the json library
something like this?
import json

text2 = '''{"@type":"Question","name":"How many COVID-19 deaths in Autauga County, Alabama?","acceptedAnswer":{"@type":"Answer","text":24}},{"@type":"Question","name":"How many COVID-19 deaths in Baldwin County, Alabama?","acceptedAnswer":{"@type":"Answer","text":46}},{"@type":"Question","name":"How many COVID-19 deaths in Barbour County, Alabama?","acceptedAnswer":{"@type":"Answer","text":7}} '''
data = json.loads('[' + text2 + ']')
for item in data:
    print(item['name'])
    print(item['acceptedAnswer']['text'])


text:
Q: how to export the dashboard to excel report at power BI I'm new at the Power BI.
I created dashboard on Power BI and I have published to the web
when opening the dashboard  on custom URL I need to export the dashboard to excel report
can I do this in Power BI or not
I new I can to do this in Power BI web APP but I need do that in my dashboard URL
thank you

A: This "custom URL" that you mention makes me think that you used Publish to web. One of the limitations of this feature is that you can't export the data:

*

*Reports using row level security.

*Reports using any Live Connection data source, including Analysis Services Tabular hosted on-premises, Analysis Services Multidimensional, and Azure Analysis Services.

*Reports shared to you directly or through an organizational content pack.

*Reports in a group in which you are not an edit member.

*"R" Visuals are not currently supported in Publish to web reports.

*Exporting Data from visuals in a report, which has been published to the web.

*ArcGIS Maps for Power BI visuals.

*Reports containing report-level DAX measures.

*Single sign-on data query models.

*Secure confidential or proprietary information.

*The automatic authentication capability provided with the Embed option doesn't work with the Power BI JavaScript API. For the Power BI JavaScript API, use the user owns data approach to embedding.

You can vote for this feature though.


text:
Q: Data matching in Excel I have two separate Excel files containing an old and a new electrical plant register, both containing electrical plant records identified by the same asset number.
The first file is our old asset register containing an old asset number and a full description of what the plant is. The second file is the new asset register. In some cases the people who made our new asset register put a meaningful description for what the piece of plant is, but when they saw our old asset number on some pieces of plant they just used that as the description.
What I need to do is pull from the old file the description of any records in the new file where the description = the asset number of that piece of plant in the old file.
I.e.
if (current_cell_value exists in old register)
  {pull description of that item from old register and store in corresponding cell in new register;}

Old file looks like this:

5538 PC
2398 Monitor

New file looks like this:

1449449 Office  IEC LEAD
1449450 Office  MONITOR
1449451 Office  5538
1449452 Office  2398
1449453 Office  IEC LEAD

Ultimately I want new file to look like this:

1449449 Office  IEC LEAD
1449450 Office  MONITOR
1449451 Office  PC
1449452 Office  MONITOR
1449453 Office  IEC LEAD

How would I do this?

A: Assuming you can copy the old asset table columns A and B into an empty sheet in your new workbook, let's put them on a sheet named "OLD", again in columns A and B.
Now assume your new dataset is columns A, B and C and it is column C where you need to change "some" of the values.
In an empty column, let's say D2, put this formula and copy down:
=IF(ISNUMBER(MATCH(C2, Old!$A:$A, 0)), VLOOKUP(C2, Old!$A:$B, 2, 0), C2)

Now you have a new set of values and hopefully all the numerics matched and now display the old register description.
Highlight the new column of values and COPY them.
Click on the original set of values in column C and do an Edit > Paste Special > Values
Now, clear the column D and you're done.
NOTE: If you're using Excel 2007+ then you can use a simpler formula than above, you can use this:
=IFERROR(VLOOKUP(C2, Old!$A:$B, 2, 0), C2)


text:
Q: How to create two-column HTML form Does anyone have any tips on how to fix the below problem of the labels and text-areas being so unsymmetric? What's the best way to structure a form like this?
I was thinking of having one div floating left (with the labels) and another div with the text areas floating right, but I didn't quite manage to structure it correctly.

A: It was your idea, I just wrote it...
Fiddle
HTML Layout

        Comment
        Tags
        Category List

        <input type="text" />
        <input type="text" />
        <select></select>

CSS
body { background: #222; color: white; }

.left, .right { width: 50%; float: left; }

.left  { text-align: right; }
.right { text-align: left;  }

span, input, select { display: block; padding: 5px; margin: 5px; }

span   { font-family: sans-serif; line-height: 20px; font-weight: bold;     }
input  { width: 200px;            height: 30px;      box-sizing:border-box; }
select { width: 200px;            height: 30px;      box-sizing:border-box; }

A: The best way is to use BootStrap framework styling issue. you can enter the website and learn more.. alternative way is to put the labels and the input fields (select fields also) in table and they will be organized.
The better to submit BootStrap otherwise use the simple way. and there is no floating issues and that's better!

A: If you want to use divs, then make them both float:left and immediately after put

. Then they will be displayed correctly.
Personally I use tables for this though, like in Islam Attrash's answer.


text:
Q: A perpetually lagging watch and its time accuracy A 24-hour, date-less, digital wrist-watch loses accuracy everyday, falling behind atomic time by an additional 15 minutes (every day). On the date of its manufacture, 1.1.2000 00h:00m:00s, it was perfectly synchronized to atomic time, and the malfunctioning applied every 24 hours thereafter.
A customer buys the watch on 1.1.2017 00h:00m:00s and assumes, rather stupidly, that the time displayed is accurate. After purchase, when mentioning the time to any one who asked, what is the probability that the time our buyer mentions is within +/- 1 minute of atomic time?
(Assume everlasting battery, consider leap years if needed, post purchase the watch still malfunctions everyday as usual, watch displays ONLY hh:mm, and not seconds).

Notes:

*

*Beginning probability student here, solving some harder problems (from the competitive math space)

*Not looking for a number answer or an outright solution, but hints, possible approaches.

A: A beginning:
A lot of the given information is irrelevant: You can forget about dates and leap years.
Since the watch looses $15$ minutes, or ${1\over4}$ hour,  on every $24$ true hours it has lost $24$ hours after exactly $96\cdot24$ true hours. It follows that everything repeats after $96$ days, so that you can take this as your basic interval for probability considerations. You now have to compute the length of the time interval centered at an exact hit during which the watch is off less than $1$ minute from true time.

A: You could calculate the time difference at the time of purchase, and then calculate how long it takes for the watch to be back in sync with the atomic clock for the first time. You could then calculate the duration of a complete cycle, the sum of the time it takes for the clock to run out of sync with the atomic clock, and the time it takes for the clock to run back in sync. You could take into account daylight saving time, leap years and seconds, but... The above steps are in fact not necessary.
Since the difference between the watch and the atomic clock is uniformly distributed, the probability of the watch being no more than one minute ahead or behind, is simply:
$$\frac{2}{24 \cdot 60} = \frac{1}{720}$$


text:
Q: How to force Firefox to load Google in non-HTTPS When I type http://www.google.co.uk in the URL bar Firefox rewrites it as https://www.google.co.uk. This is a problem for me as HTTPS is blocked on my network for content filtering purposes.
Until a few days ago this was not the case, but during some experimentation I seem to have visited the HTTPS version of the site once or twice and also had the HTTPS Everywhere addon installed for a time. Now, no matter what I do Firefox redirects there. Sometimes it doesn't; sometimes I load the browser and the HTTP version loads fine, but then the next time it's oddly trying HTTPS again and nothing can shift it until a few session restarts later. I don't understand why it seems to sporadically use HTTP and HTTPS.
I'm using Firefox 23.0 and Ubuntu 12.04.
I've tried a number of things so far:

*

*Setting browser.urlbar.autoFill false, browser.urlbar.autoFill.typed false, browser.formfill.saveHttpsForms false

*Clearing everything from history

*Resetting Firefox and using safe mode

*Deleting all the profile data in .mozilla folder and creating a
new profile

*Completely purging Firefox and deleting .mozilla, /etc/firefox
and reinstalling

How can I fix this so that Firefox just loads Google in non-HTTPS?
Maybe it's Google doing the redirect, but I just don't understand why it was fine until a few days ago, and also why it only does it sporadically.
Even when I try typing in nosslsearch.google.com I get redirected to the HTTPS version!
Lastly, when I log into another user account on the computer, and try Firefox with Google I see no problems with redirects, just as it had always been until recently on the above account.
EDIT: I should also mention I am not logged into any Google account.

A: I noticed using Fiddler that sending HTTP requests to Google would always return the 302s you mention, redirecting me to the HTTPS url as long as a Firefox user agent string was included in the request header. This is my current user agent string using Firefox 24 on Windows 7 x64:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
So for me, a simple fix was to start using the User Agent Quick Switch add-on for Firefox. I changed my user agent string like this - just removed the Firefox/24.0 at the end:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101
I'd guess a similar change to your Ubuntu user agent string would also do the trick, although there is an outside chance that it be problematic on another site.

A: If you are logged in to Google with a Google user account, Google will serve everything in https, so be sure you are logged out of all Google accounts.

A: This behavior is determined from the server. If you look the over the request you will find that we are requesting for http://wwww.google.co.in but the response returns https://www.google.co.in with the status code 302. So that means server redirects the http request to https
Here is what I observed in developer console of firefox.


text:
Q: Dart: Extend HTMLElement with abstract class I was trying to write something with the following design pattern:
void main()
{
    document.registerElement('abs-test', Test);
    TestExtend test = new TestExtend();
    document.body.append(test);
}

abstract class Test extends HtmlElement
{
    Test.created() : super.created();
    factory Test() => new Element.tag('abs-test')..text = "test";
}

class RedTest extends Test
{
    TestExtend() : super() => style.color = 'red';
}

My aim with this is to create a custom HtmlElement registered to the abstract class "Test". This abstract class "Test" would have some properties that all elements of type Test need to have. In this example, all elements of type Test need to have the word "test" as their text.
However, I wanted then to only allow the user to create subclasses of "Test" with more specific properties. In this example we have RedTest which then sets the color of Test to red. The resulting HTML would be:
<abs-test style="color:red;">test</abs-test>

I have 2 problems with this:
1) Is it possible to call the factory constructor of a parent class? (If not, is it possible to extend HtmlElement in a different way that doesn't require a factory constructor)
2) Is it possible to extends HtmlElement with an abstract class?
I have been testing for a while with different constructors but am unable to make it work. Can anyone advice?

A: You register a tag with a class so that the browser can instantiate it for you. If this isn't an 1:1 relation, there is no way for the browser to know what class to instantiate.
Therefore
You need

*

*a different tag for each class

*register each tag with a concrete (non-abstract) class

You normally can call the constructor of a subclass in a factory constructor of an abstract class
factory Test() => new RedTest()..text = "test";

is valid in Dart, but because extending an element requires to return
new Element.tag('abs-test')

this won't work, because you can't return both at the same time.
You need to register each concrete subclass with a different tag like
document.registerElement('abs-test-red', TestRed);
document.registerElement('abs-test-blue', TestBlue);


text:
Q: error: GLSL 3.30 is not supported. Supported versions are: 1.10, 1.20, 1.30, 1.00 ES, 3.00 ES, 3.10 ES, and 3.20 ES I have a Qt code for an 3D application developed with OpenGL. I'm trying to build/run the Qt application with QtCreator but I'm getting the following error:
Error in compiling shader.

0:1(10): error: GLSL 3.30 is not supported. Supported versions are: 1.10, 1.20, 1.30, 1.00 ES, 3.00 ES, 3.10 ES, and 3.20 ES

I tried adding the following to my code as suggested by this answer:
QSurfaceFormat glFormat;
glFormat.setVersion(3, 3);
glFormat.setProfile(QSurfaceFormat::CoreProfile);
QSurfaceFormat::setDefaultFormat(glFormat);

Actually the above code worked, I mean the error got resolved. However, when application is running, it doesn't show/render any 3D content. For example when importing a STL file into the Qt application, the STL content is not shown. Did anybody run into a similar issue?

A: Just to help the next guy who might run into such an issue:

I built/ran the application on a computer belonging to a friend which has two graphic cards: one Intel and one Nvidia.
In the case of Intel graphics card the same previous issue occurred regarding OpenGL versions.
In the case of Nvidia graphics card, no OpenGL error happened. The application runs without any issue and the imported STL file could be rendered/viewed. Therefore my OpenGL error was hardware-related.

What I'm curious to know is how much effort would it take to modify the code so that the 3D application can run on Intel graphics card too. Who knows?


text:
Q: Is there a more elegant way to write this lazy loading pattern in Swift? I've considered null coalescing and if let, nothing seems that great so far, any ideas?
var habitResults: [[String:String]]? = resultsFilteredByHabit[habitId]

if habitResults != nil {
    // No action required
}
else {
    habitResults = results.filter({ $0["habitId"] == habitId })
    resultsFilteredByHabit[habitId] = habitResults
}

A: The usual lazy loading pattern syntax in Swift is
lazy var habitResults : [[String:String]] = {
    return results.filter{ $0["habitId"] == habitId }
}()

The closure is executed once when the variable is accessed the first time

A: I think this looks a little more elegant:
resultsFilteredByHabit[habitId] = resultsFilteredByHabit[habitId] ?? results.filter({ $0["habitId"] == habitId })


text:
Q: Find the probability that the largest number appearing in a coupon is 9 out of coupons numbered 1 to 15 $15$ coupons are numbered $1,2,3...,15$ respectively. $7$ coupons are selected at random one at a time with replacement. The probability that the largest number appearing in a selected coupon is $9$ ???
Try
The largest number will be $9$ if out of $7$ selected coupon one is numbered $9$ and the other $6$ are in between $1$ to $8$.The number $9$ can be choosen in any one place out the $7$ selected coupons. So there are $7$ ways I can choose $9$ and in each case other $6$ numbers can be choosen in $8^6$ ways. Hence the required probability is $\frac {7\times 8^6}{{15}^7}$
I know exactly the same problem is there in Stack. But my approach is completely different. And I want to know where is the mistake in this method.


text:
Q: How do I test while using httprouter without using controllers? I'm trying to write tests for a microservice I wrote using httprouter. I've previously tried to use the answers given here: How to write test with httprouter but that doesn't seem too relevant since I don't use controllers in my microservice. Any help would be greatly appreciated.
Here's what I have so far:
package main

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/julienschmidt/httprouter"
)

func TestCreateURL(t *testing.T) {
  expected := `{"original_url":"https://www.google.com", "short_url":"https://morning-retreat-24523.herokuapp.com/get/3578"}`
  handler := createURL
  router := httprouter.New()
  router.GET("/new/*url", handler)

  req, err := http.NewRequest("GET", "/new/https://www.google.com", nil)
  if err != nil {
      fmt.Println(err)
  }
  rr := httptest.NewRecorder()

  router.ServeHTTP(rr, req)
  if rr.Body.String() != expected {
      t.Errorf("Handler returned unexpected body: Got %v but want %v",
        rr.Body.String(), expected)
  }

}
createURL is a function like this (but with a lot more in it obviously):
func createURL(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {

}


text:
Q: Display a consistent Google Plus icon on ALL pages of my site My website is http://tablified.com and I have managed to setup the Google Plus script. The issue is that every page of the site displays a different Google Plus count. For example, if you go on my site you will see that I have about 180 Google Pluses. Now, if you click on something like "Tablified Apps" you will see that the Google Plus number on the top left corner of the screen is changed to 21. How do I display the Google Plus account for the main page across the entire website regardless of the page being displayed? Where should I place the script exactly? I am running this site on Wordpress. Perhaps a plugin could fix this and save me the hassle? The issue is that I need to have it at that EXACT location and I feel like a plugin would not accomplish this. Thanks for your help!

A: You have to explicitly set the target url or it will use the rel canonical (if present) or grab URL of the current page via js.
Use the button generator and click advanced options to set the target URL, or:
<g:plusone href="http://tablified.com/"></g:plusone>

A: If you change the target URL, you need to be aware of that your visitors will only be able to Google +1 one time and that's for the home page. If a user likes another section or page of your site like the Tablified Games they won't be able to Google +1 that page because they have already done that because it's always the same Google +1.
And you have more than the 180 Google +1. The 180 are just for the homepage and the others you see are for the specific pages.

A: Use this snippet
<!-- Place this tag in your head or just before your close body tag -->
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Place this tag where you want the +1 button to render -->
<g:plusone></g:plusone>


text:
Q: Allow my users to point their subdomains to my server with CNAME, without having to use add-on domain in cpanel So I have a service that allows my user to map their own subdomains to my server. For example
http://sub.userdomain.com will map to http://sub.mydomain.com
Now I know that the user must add a CNAME record that points to my subdomain, but using Apache & Cpanel, now I have to add an add-on domain for this connection to work.
Is there a workaround so that I don't have to set up this add-on domain for the connection to automatically connect? (Basically so that my user can point their CNAME to my subdomain and it then automagically works without me having to do manual input).
Hope that makes sense!

A: No, You need to add addon domain on your server so that cPanel will create entry in apache configuration to work that domain.


text:
Q: Forcing a carriage return in textarea I would like to start a textarea with inside a text that starts some line under the first line. Doing something like:
var myText = '\r \r \r HELLO';

doesn't work: HELLO is written on the first line, while
var myText = 'HELLO \r \r \r HELLO2';

puts correctly HELLO2 after HELLO. This means that \r is correct, but it doesn't work at the beginning of the textarea.
Any suggestions?

A: Have you tried to put space or   before the "\r"?

A: Don't use \r, use \n
Example:
var myText = '\n \n \n HELLO';

A: In PHP I had to make sure to use double quotes instead of single.
$var1 = 'Test1 above /n/n Test below'; //will not work
$var2 = "Test2 above /n/n Test below"; //will work
echo = "<textarea>$var1</textarea><br /><textarea>$var2</textarea>";

A: Try inserting
 into the text area.

A: "\r" is to return to the begining of the line the, i forgot its name, i think is the cursor. But what you need is "\n" for a new line

A: If you are using .net.
Then do
Var myText = "Hello" + Enviroment.NewLine + "Hello2";
However if your using something else, i.e. Java, web languages then I advise you try /n followed by /r. I have had to use "/n/r" to get the result I wanted, after the /r was being ignored.

A: What browser and/or OS are you using?  In my quick test, both \r and \n yield the same (correct) result on Windows in IE 8, Firefox 3.6, and Chrome 9.

<textarea rows="5" id="r"></textarea>
<textarea rows="5" id="n"></textarea>

$(function() {
    $('#r').val('\r\r\rHello');
    $('#n').val('\n\n\nHello');
});


text:
Q: What's the difference between an array and a hash whose keys are integers? What is the difference between an array, an ordered collection of integer-indexed values, and a hash, a collection of key-value pairs, where every key is an index that starts from zero?
arr = [1,2,3,4]
hash = { 0 => 1, 1 => 2, 2 => 3, 3 => 4}

I know that it would be stupid to implement a hash like that, but what is the difference behind the hood? Are they stored in different ways in memory? What data structure makes your program faster when retrieving data from it?

A: Speed
Arrays are a better for iterating over a collection.
Hashes have almost constant lookup time O(log n), while Arrays have linear time O(n).
This means that you should prefer Hashes when you need to use #include?.
Hashes work great as dictionaries.
There is a third underutilised data structure in Ruby which behaves like a unique Array but uses a Hash underneath. This is Set. It works great when you don't care about the order of elements, need to check if something belongs to a group or need a unique collection of elements.
Implemetation
Yes, they are two completely different data structures.
In this particular example you could access these elements in a similar manner by calling arr[0] and hash[0].
The line arr[0] is in fact sugar syntax for arr.[](0). Same goes for arr[0] = 5 which is the same as arr.[]=(0, 5). Both Array and Hash have methods called [] and []=, but under the hood completely different things would happen, because these are two separate methods with the same name.
Arrays are always indexed with integers starting with 0 and the order of items is important.
Array is a simple list of elements backed by a dynamic C array, while a Hash is an implementation of a dictionary/hashmap, a much more sophisticated data structure.
Hashes store both keys and values, and possess the ability to retrieve a value based on the received key. Every single Ruby object that implements #eql? and #hash can become a Hash key.
The order of elements in a Hash can change and is not stable.
Every Hash is in fact an array of slots called buckets. These buckets hold individual key-value pairs. To determine which key should correspond to a certain bucket, Ruby uses a hashing function, provided by the method called #hash on the object passed as the key. If two objects return the same value from their #hash method, they are considered the same key.
This goes both ways, Ruby uses #hash to save the key-value pair in the right bucket, and to find the right value for the passed key.
For example "string".hash will always return the same value, even though these are different objects.
This value is calculated based on the content of the String. This is why Strings with the same content (even though they are different objects) are considered the same key in a Hash.
Sometimes two different objects (of separate classes) end up having the same #hash. Ruby handles these collisions by implementing individual buckets as linked lists of key-value pairs. So a few key-value pairs may be stored in the same bucket.
To decide which value should be returned for a given key, when there are a few key-value pairs in the same bucket, Ruby utilises the eql? method.
It compares each key stored in the bucket with the passed key like so passed_key.eql?(key_in_bucket). When they are equal Ruby considers them a match.
Here's a great article on Hashes.

A: Almost every object in Ruby has a hash method. This method calculates some number which is unique-ish. That number is used to retrieve a key in a Hash object. If you want to get the value for 2 then the hash value for 2 is calculated (for an integer this is really fast) and looked up in the Hash object. So it looks like a hash is a way to over-complicate things - but if you want to be sure, benchmark your use-case is the way to go.


text:
Q: FAST Computation of Integer Basis for Kernel of a Matrix Using GPU Input: a n times m matrix A with integer entries. For example consider the matrix
A = [[2,1,0],[0,1,2]]

Output: an integer basis for the kernel/null space of A. For example for the above matrix, an integer basis is
[[1,-2,1]]

I am using ideas from this stackoverflow post, to first compute a rational basis and then compute an integer basis by multiplying with the lcm of denominators, with the following (Python 2.7) code:
import numpy as np
from sympy import Matrix,lcm
from fractions import Fraction

def ker_int_basis(B):
    BKer = 1.0*np.array(Matrix(B).nullspace())
    Bk =[]
    for basis in BKer:
        l = lcm(map(lambda x: Fraction(x).limit_denominator().denominator,map(str,basis)))
        basis = map(int,l*basis)
        Bk.append(basis)
    Bk = np.array(Bk)
    return Bk

It works on small examples. But the above code is tediously slow and the matrices I have are 10000 times 500 or bigger. The above code doesn't output even after hours of running.
How can I make the code faster? I would prefer a GPU implementation, considering the matrices are very very large. A multi-core CPU will also be an improvement. Even suggestions to use loops and data structures more efficiently in the above code are also welcome.

A: Sympy is using Gaussian Elimination to compute the null space of B. This is $O(n^3)$, and I assume that this computation is the bottle neck in your code (but it would be worth checking).
Gaussian elimination can be parallelized by doing all eliminations simultaneously. The algorithm for GE is relatively straightforward, and there are many implementations for floating point numbers out there. However, I didn't see other symbolic packages which would do this using rational numbers or integers in my brief search (although you could probably implement this relatively easily).
Another thing you could try in order to parallize the task without rewriting an algorithm to find the null space is to split the matrix into two sets of rows, compute the null space of each, and then compute a basis for the intersection of the computed null spaces. This would work well if each of the sets of rows have relatively small null spaces, but not so well if they both return very large null spaces.


text:
Q: Integration test ordering vs. before/after style setup/cleanup when one test is a subset of another I'm aware that it's generally considered bad style to write tests that have to run in a particular order. Let's say I'm testing an account-management API, and have the following two integration tests: test_create_account, and test_log_in. What I understand to be the correct style for this would be something to the effect of:
test_create_account:
  // check whether account creation works

before_test_log_in:
  // create a throwaway account
test_log_in:
  // try logging into the throwaway account from the 'before_' fixture

However, if I can't control the order in which they run (or set up some sort of inter-test dependencies to enforce at least partial ordering), I'll get failures in both tests and have to paw through to figure out which test case is most relevant to the fact that I have failing tests. If I could order/dependency-ify them, it would make the output from the test runner much less noisy.
Why (if at all) is it more important for the tests to be fully independent than to have more eloquent output?

A: Why should tests be independent from each other?
Because otherwise you cannot run them individually. This becomes a challenge when one of a few hundred test fails in a full run of your test suit - but when you are trying to find the cause, running the formerly failing test alone does not fail any more. More general, assume you pick a certain subset of the tests and always get different results depending on what you picked - good luck in managing this.
To prevent such side effects, each of the tests should start with a fixed, defined state of the system under test (this holds regardless if you are doing unit or integration tests). For example, when you have an integration test which includes a database, before the test is run, it requires a fresh copy of the database, maybe with a certain preset of accounts or test data tailored for the specific test. There should be a "setup" state at the beginning of each test which provides this database and its content, regardless of the operations which took place beforehand.
test_create_account may, for example, require a clean test database with no account so far.  test_log_in may require, for example, a clean test database with a predefined account. If you want to make it possible to reuse the same test database for both tests, to save some space, there is nothing wrong when test_log_in uses the same create_account method on the db like test_create_account to create the required throwaway account.
Of course, it depends heavily of the system (for example, the DMBS), how costly it is to setup a fresh new copy of the DB for each test. For a lightweight database like SQLite this maybe pretty simple - just copy a prepared DB file from a fixed origin. For a DBMS like Oracle, you may find it simpler and quicker to have only one DB instance for testing and run some general cleanup scripts beforehand. Other systems may require completely different lines of action, but I guess you get the idea.
What about making the output from the test runner much less noisy?
It is fully up to you what "noise" your tests produce. Ideally, when a test does not fail, it should produce almost no output, maybe just a message "test XYZ succeeded" (or maybe not even this, when you have a statistics, telling you something like "2 of 2 tests succeeded"). So there should be no compelling reason why two independent, succeeding tests produce more than two lines of output, regardless of the order in which you run them.
If both tests reuse some methods (like create_account), don't implement any directly visible output in create_account. Make that method throw an exception in case it fails, and let the tests catch the exception and produce failure messages from it. create_account may write something into some separate background log file, but I would not show the content of the log in each test run, only bring it to the front when a test fails.

A: before_test_log_in requires an account as a precondition, but that doesn't mean it needs to create an account in the same "realistic" way as is tested in test_create_account.

*

*test_create_account should take input data (username, email, password, etc.) from a factory or fixture, and spit out an account object that can be asserted against (make sure that it has the correct username, email, password, etc.)

*before_test_log_in should take an account, and assert that it can log in (whatever that entails). This doesn't have to duplicate the logic of account creation as tested in test_create_account. You can just directly make an account object (using a factory or fixture).


text:
Q: Node.js AES-256-CBC encryption issue I'm trying to create an encrypted string according to one sample code which is given in PHP, my main problem is Node.js crypto module doesn't accept keys with more than 32 bytes length but PHP openssl_encrypt does, it seems that's why I'm getting Invalid key size error.
here is my js code:
    let iv = sha1(await HelpersService.makeRandomNumber(null, null, 16));
    iv = iv.substr(0, 16);
    const text = bundledData;
    const password = sha1(this.credentials.appSecret);
    let salt = sha1(await HelpersService.makeRandomNumber(null, null, 4));
    salt = salt.substr(0, 4);
    const key = crypto.createHash('sha256').update(password + salt).digest('hex');
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encoded = cipher.update(text, 'utf8', 'hex');
    encoded += cipher.final('hex');

and this is the PHP sample:
   function generateCashOutAPIHashKey($app_secret ){
      //remove plus(+) sign from gsm number.
      $data = 'text';
      $iv = substr(sha1(mt_rand()), 0, 16);
      $password = sha1($app_secret);
      $salt = substr(sha1(mt_rand()), 0, 4);
      $saltWithPassword = hash('sha256', $password . $salt);
      $encrypted = openssl_encrypt("$data", 'aes-256-cbc', "$saltWithPassword", null, $iv    );
      return $encrypted;
    }

A: The key generated in the PHP and NodeJS code has a length of 64 bytes. The used encryption AES-256 needs a 32 bytes key. In the PHP code, openssl_encrypt() implicitly shortens the 64 bytes key to 32 bytes. In the NodeJS code this has to be done explicitly:
const key = crypto.createHash('sha256').update(password + salt).digest('hex').substr(0, 32);

Also, openssl_encrypt() returns the ciphertext Base64 encoded by default. In the NodeJS code the result is returned hex encoded. Here you have to change the output encoding from 'hex' to 'base64' in the update() and final() call:
let encoded = cipher.update(text, 'utf8', 'base64');
encoded += cipher.final('base64');

Please note that the PHP reference code has a number of vulnerabilities:

*

*mt_rand() is not a cryptographically secure pseudorandom number generator (CSPRNG). PHP provides cryptographically secure methods for deriving a random IV / salt, e.g. random_bytes() or random_int().

*The key is inferred using SHA-256. It is more secure to use a reliable key derivation function such as PBKDF2. A 4 bytes salt is generally too small.

*SHA1 is considered insecure in most contexts and must no longer be used.

A: Anyone have a problem with the following ?

crypto.createHash('sha256').update(password +
salt).digest('hex').substr(0, 32);

I understand the intent of needing a 32 byte value produced by sha256 but if you hex encode and then take the first 32 characters of the string you have SIGNIFICANTLY reduced the value of this.  You now have a string 32 characters long that has only 16 possible values (0-9a-f) for each character.  You really want a 32 byte value that has 256 possible values for each byte.  You have changed your key security of your encryption key from the intended 256^32 (1.1E77) to 16^32 (3.4E38).

crypto.createHash('sha256').update('').digest('hex');
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
crypto.createHash('sha256').update('').digest('hex').substr(0,32);
'e3b0c44298fc1c149afbf4c8996fb924'

Find a way to use the byte values produced by SHA256.


text:
Q: How to rearrange the string in C# \In my csv file have two row data :
\a;b;c;d;e;
\1;2;3;4;5;
\How do I make it as below in c#:
\a=1;enter code here
\b=2;enter code here
\c=3;enter code here
\d=4;enter code here
\e=5;enter code here

A: tldr; you split the text.

*

*got string from csv  //e.g. string originalTxt  =  @"\a;b;c;d;e; \1;2;3;4;5";

*split row

*rearrange/edit for each word in each row

*combine

string resultTxt = "";
string mycodehere ="enter code here ";
string originalTxt = ...; //TODO :: your code for get text from csv
string[2] rows = originalTxt.Split('\');   // split the \ got 2 rows
string[] row1 = rows[0].Split(';');    //split each word
string[] row2 = rows[1].Split(';');    //split each word
for(int i= 0 ; i< row1.Count ; i++){
     resultTxt  +=  @"\" + row1[i] + "=" + row2[i] + ";" + mycodehere + " " ;
}
 //TODO :: use resultTxt


text:
Q: In ionic app using router-outlet, but hardware back is not working in mobile app I am using ionic app with  for routing, In mobile application while doing hardware back the page is getting struck instead of moving to last page viewed. what can be the issue? I am not getting any console errors

A: It's a bit complicated to answer this question without any code..
But you can add a simple button to your HTML and set your routerLink. Something like:
<ion-buttons slot="end">
  <ion-button routerLink="/backToPage">
    <ion-icon name="chevron-back-outline"></ion-icon>
  </ion-button>
</ion-buttons>

or like this:
<ion-buttons slot="start">
  <ion-back-button defaultHref="home"></ion-back-button>
</ion-buttons>

... if you have dynamic pages


text:
Q: unzip all files and save all contents in a single folder - unix I have a single directory containing multiple zip files that contain .jpg files.
I need to unzip all files and save all contents (.jpgs files) into a single folder.
Any suggestions on a unix command that does that?
Please note that some of the contents (jpgs) might exist with same name in multiple zipped files, I need to keep all jpgs.
thanks

A: unzip '*.zip' -o -B

as by default these utilities are not installed
see http://www.cyberciti.biz/tips/how-can-i-zipping-and-unzipping-files-under-linux.html regarding installation
read about -B flag to realize its limitations.


text:
Q: jquery select input whose name starts with x or y I have a page that is filled with radiobuttonlists whose IDs start with either "inc" or "exc" for inclusion/exclusion questions. I am able to select all the inclusion buttons with $('input[name^="inc"]') and all the exclusions with $('input[name^="exc"]'). Since I am binding both types of buttons with the same function I wanted to combine my select statement to grab both sets of elements.
I tried $('input[name^="inc|exc"]') but this doesn't select anything. I tested that it found nothing by looking at the length and it is zero. I tried a couple other ways but they all result in no matches.
To sum up the problem, using jquery, I need to find all inputs whose name start with "inc" or "exc"

A: $('input[name^=inc], input[name^=exc]');


text:
Q: Adding multiple LIKE parameters yield no results I'm trying to add multiple 'LIKE' to my SQL list here but after the first 'LIKE', it stops returning results.
Code:
SELECT
T1.item_no,
T1.inv_id,
T2.on_hand_qty

FROM inventory_items T1
INNER JOIN inventory_quantities T2 ON T1.inv_id = T2.inv_id

WHERE item_no LIKE 'DP105%'

So say my list is this:
DP105A
DP105B
DP105C
DP108A
DP108B
As my code stands, it generates everything that starts with DP105 (good!)
But once i add AND item_no LIKE 'DP108%' it generates an empty list. I don't know why.

A: You want "OR":
SELECT
T1.item_no,
T1.inv_id,
T2.on_hand_qty

FROM inventory_items T1
INNER JOIN inventory_quantities T2 ON T1.inv_id = T2.inv_id

WHERE item_no LIKE 'DP105%'
OR item_no LIKE 'DP108%'

AND would mean item_no begins with DP108 and DP105...but this is impossible. It can only begin with one of those strings.


text:
Q: Making a list of divisors in Haskell I am doing problem 21 in eulerproject.
One part requires finding the list of proper divisors of a number. i.e. where there is remainder of n and some number of less than n. So I made this Haskell, but GHCI gets angry at me.
divisors n =[ n | n <- [1..(n-1)], n `rem` [1..(n-1)] ==0 ]

The problem is that I don't know how to make:
n `rem` [1..(n-1)]

so that it only returns the number less than n that divide evenly into n.

A: If the order of the list of divisors is not important, you can make this significantly more efficient by only checking divisors in the range [2..sqrt n].
Something like this (you could probably make some local optimisations if you thought about it more):
divisors' n = (1:) $ nub $ concat [ [x, div n x] | x <- [2..limit], rem n x == 0 ]
     where limit = (floor.sqrt.fromIntegral) n

Where divisors is the previous implementation, and divisors' is the new one:
*Main> (sum.divisors) 10000000
14902280
(4.24 secs, 521136312 bytes)

*Main> (sum.divisors') 10000000
14902280
(0.02 secs, 1625620 bytes)

NOTE:
We I used nub to remove any repetitions, when in fact the only possible repetition would be limit, if n is a square number. You could make it slightly more efficient by handling this case better, but I find this way is more readable (if running time isn't critical).

A: You just need a separate variable.
Prelude> let divisors n = [x | x <- [1..(n-1)], n `rem` x == 0]
Prelude> divisors 20
[1,2,4,5,10]
Prelude> divisors 30
[1,2,3,5,6,10,15]

Now, if you wanted to make it a bit more efficient, we already know that a divisor won't be more than half of n, and we know 1 is a divisor of everything.  And, let's go ahead and make it a bit more Haskell-y to boot, avoiding a list comprehension:
Prelude> let divisors n = 1 : filter ((==0) . rem n) [2 .. n `div` 2]
Prelude> divisors 20
[1,2,4,5,10]
Prelude> divisors 30
[1,2,3,5,6,10,15]
Prelude> divisors 31
[1]


text:
Q: GitHub Context Variables Not Evaluating for Reusable Workflow Reference I'm currently trying to build a reusable workflow where the reusable workflow is correctly setup with an on: workflow_call trigger and so forth.
When I'm calling the workflow though, I need to be able to dynamically populate the shared workflow file reference with the current branch or commit. I'd also like to populate the organisation and repo dynamically as well if possible with the current org/repo, but that's less essential. My call to the other workflow therefore looks like this:
jobs:
  call-build-and-test:
    uses: ${{github.repository}}/.github/workflows/cicd-build-and-test.yml@${{github.sha}}

Unfortunately however the two context variables, github.repository, and github.sha don't get evaluated and the workflow fails at runtime stating that a valid organisation and repo are required at the start of the string, or, if the organisation and repo are hardcoded so that they're valid, then it states the commit couldn't be found because that's not evaluated correctly either.
Can anyone explain why the context variables aren't getting evaluated? If this is not possible how can I dynamically populate these values? It's not sufficient to hardcode them as they need to execute against the version on the current branch, as the main branch has not had workflow merged in yet, so can't simply be hardcoded to that as in the examples in the Github docs here:
https://docs.github.com/en/actions/learn-github-actions/reusing-workflows#calling-a-reusable-workflow
I believing using context variables such as github.* is the right approach, as environment variables are only available within the scope of a shell executing a job, however I have also tried environment syntax as well, i.e. GITHUB_REPOSITORY, and GITHUB_SHA with the same problem.

A: It can't be done at the moment as Github Actions doesn't support expressions with uses attributes.
There is no workaround (yet?) because the workflow interpreter (that also checks the workflow syntax when you push the workflow to the repository) can't get the value from the expression at that moment.
It could maybe work if the workflow was recognized by the interpreter, but it doesn't event appear on the Actions tab as it's considered invalid.
For the moment, you can only use tag, branch ref or commit hash after the @ symbol, the same way you use any action. Therefore, this has to be hardcoded at the moment.

A: As GuiFalourd says:

It can't be done at the moment as Github Actions doesn't support expressions with uses attributes.

If you just want to use the ${{ github.sha }}, and you only need the workflow from your local repo, don't specify the ref. As shown here:

If you use the second syntax option (without {owner}/{repo} and @{ref}) the called workflow is from the same commit as the caller workflow.

call-workflow-2-in-local-repo:
    uses: ./.github/workflows/workflow-2.yml

You can find more info here.
Unfortunately I can't find any information on whether they are planning to support this one day.
I am also facing this issue when calling a build workflow from a deployment workflow. I think the solution for me is to pass the branch as a param to the reusable build workflow and checkout that branch if it's specified. I am just going to have to accept that I'm not using the workflow file from the branch specified.
I appreciate I'm late with this and it's a very specific scenario, but hope it may help you in some way!


text:
Q: join two un-sorted txt files in unix I have two files, say:
FILE1
size  freq
  1   .4
  2   .8
  8   .3
  40   .2
  90   .1

And FILE2
size  freq
  1  .2
  3  .5
  4  .1
  60  .3
  70  .2

I like to join then in a way so, the results would be like:
    size  freq1  freq2
      1  .4  .2
      2  .8   0
      3   0  .5
      8   0   0
      40  .2  0
      60  0  .3
      70  0  .2
      90  .1  0

I used
join -a 1 -a 2 -e "0" -o '0,1.2,2.2' FILE1 FILE2

But it sorts the lines one-by-one from either files. Is there any way to join and sort the results simultaneously?
Thanks in advance

A: Note join doesn't support the same key selection and comparison functions as sort(1) (yet).
Therefore the data must be sorted using sort in a specific way so as to be acceptable for join(1). Specifically in this case, join(1) does not currently support numeric comparison.
One can avoid this issue while keeping "numeric" order by using a fixed width numeric field (with leading zeros), or if strict numeric order isn't an issue you can get sort to operate like join operates by default by previously sorting with: sort -k 1b,1 (that's documented in the join man page).