text:
Q: Trying to use StopWatch outside a method I'm trying to create a stop watch form. I want to be able to have a button I press to get a Lap time just like a normal stop watch. For reasons I don't understand I can't define a Stopwatch variable and call it's constructor in another method. How would I go about making a StopWatch variable so that I can use it in other methods? If I'm not supposed to use a StopWatch what should I be doing?
namespace _Hard0002_StopWatch {
    public partial class StopWatch : Form {
        StateEnum state;
        StopWatch stopWatch;

        public StopWatch() {
            InitializeComponent();
            state = StateEnum.Stoped;
        }

        private void StartButton_Click(object sender, EventArgs e) {
            if (state == StateEnum.Stoped) {
                stopWatch = Stopwatch.StartNew();
                state = StateEnum.Started;
                ChangeFormTittle("Started");
                TimeKeeperText.Text = "0.0";
            }
        }

    private void LapButton_Click(object sender, EventArgs e) {
        //save time elapsed to a string array
        stopWatch.getElapsedTime()//I know this isn't how you call it I just worded it to be readable.
    }

This is the error I'm getting when I try to declare stopWatch in my StartButton_Click()
Cannot implicitly convert type 'System.Diagnostics.Stopwatch' to '_Hard0002_StopWatch.StopWatch'

A: C#'s stopwatch is Stopwatch.  Your class is StopWatch.  You declare your variable:
StopWatch stopWatch;

then initialize it:
stopWatch = Stopwatch.StartNew();

using two different objects.  Best to rename your form to something like StopwatchForm to prevent from confusing yourself more.


text:
Q: Bug displaying a div element when a user clicks on a button I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />

    <script type="text/javascript">

    function traverse(){
        output.innerHTML+='Test'; // Nothing happens !
    }

          function check() {
            var keywords = document.getElementById('text').value.split(" ");

            for (var i=0; i < keywords.length; ++i) {
                traverse_tree()
            }
          }

    </script>

  </head>
  <body onload ="init()">
        <input id="text" type="text" size="60" value="Type your keywords here" />
        <input type="button" value="Display the text 'Test'" onclick="check();" />

        <div id="output">
        </div>

  </body>
  </html>

thanks,
Bruno

A: Perhaps because the function is called traverse() and you're calling traverse_tree()?

A: Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
  document.getElementById('output').innerHTML+='Test';
}

You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {

  // Cache the node to be updated here
  var node = document.getElementById(nodeId);

  // This is the function that "traverse()" will call. Return this function,
  // which will assign it to the variable traverse.
  return function () {
    node.innerHTML += 'test';
  };

// Execute the function with the id of the node to cache, i.e. output
}('output'));

redpajama_set_name: RedPajamaStackExchange


text: Q: Custom HTTP Error Page with Specific Code Page and One Template Error View Laravel I want to make template for all error HTTP view and just put code and massage on it in error.blade.php (using template for all code) but for 404, it must using 404.blade.php (using default error template). I'm really confused to implement it and not found the solution. Any ideas?


text:
Q: Wildfly: How to call my code before deployment of war files I have 5 wars in my wildfly deployment directory. But before deployment of these war files i want to call some code which will have logic of jndi and database registration  for these war files.
I have one approach in which i can create one war file having jndi and database register logic and then setting its deployment priority to 1, but due to some reasons i can not go with this approach.
Please suggest me the way to do it.

A: If you just want to create a jndi and database registration, you can directly create a jndi in wildfly itself and use that jndi in your application. So that you don't need to create a new WAR file.
To create a JNDI in wildfly, need to edit the standalone.xml file located in wildfly directory C:\wildfly\standalone\configuration\
Example:
<subsystem xmlns="urn:jboss:domain:datasources:2.0">
    <datasources>
        <datasource jndi-name="java:/jdbc/jndi-name" pool-name="jndi-name-Pool" enabled="true">
            <connection-url>jdbc:oracle:thin:@localhost:1521:orcl</connection-url>
            <driver>oracle</driver>
            <pool>
                <min-pool-size>10</min-pool-size>
                <max-pool-size>20</max-pool-size>
                <prefill>true</prefill>
            </pool>
            <security>
                <user-name>username</user-name>
                <password>password</password>
            </security>
        </datasource>
        <drivers>
            <driver name="oracle" module="com.oracle.ojdbc6"/>
        </drivers>
    </datasources>
</subsystem>

A: There are several possibilities/levels depending on what you want to do:
1) Implement Servlet API ServletContextListener interface in your application.
@WebListener
public class AppInitContextListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent event) {
    // Your code here
  }

  @Override
  public void contextDestroyed(ServletContextEvent event) {
  }
}

2) Implement Servlet API ServletContainerInitializer interface in your application. This alternative allows programmatically adding another servlets, filters, etc. Then add the fully qualified name of your class to the special text file in your war archive:META-INF/services/javax.servlet.ServletContainerInitializer, in order to register your class to be called by container.
public class AppContainerInitializer implements ServletContainerInitializer {

  @Override
  void onStartup(Set<Class<?>> c, ServletContext ctx) {
    // Your code here
  }
}

3) Implement Wildfly (Undertow servlet engine) specific ServletExtension interface in your application. This alternative allows you to do 'down to the metal changes' in servlet engine. Then add the fully qualified name of your class to the special text file in your war archive:META-INF/services/io.undertow.servlet.ServletExtension, in order to register your class to be called by Undertow servlet container.
public class AppInitExtension implements ServletExtension {

  @Override
  public void handleDeployment(final DeploymentInfo deploymentInfo, final ServletContextImpl servletContext) {
    // Your code here
  }
}

4) For the sake of completeness, if you are using JPA, you could hook before deployment of JPA Entity manager this way (e.g. for performing database upgrade before deployment). Implement Hibernate specific Integrator interface in your application. Then add the fully qualified name of your class to the special text file in your war archive:META-INF/services/org.hibernate.integrator.spi.Integrator, in order to register your class to be called by Hibernate framework.
public class SchemaUpgradeIntegrator implements org.hibernate.integrator.spi.Integrator {

    @Override
    public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
        // Starting DB migration
        final DataSource dataSource = (DataSource) sessionFactory.getProperties().get("hibernate.connection.datasource");
        // Your code here
    }

    @Override
    public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {
    }
}


text:
Q: check if condition is met then do a lookup I'm trying to do a parallel job wherein I check the value of a column where in if it matches a certain condition it returns a certain value and if does not it will check on another condition and if it matches that condition it will do a lookup.
I'm not sure where to put the condition if it will be on the reference link or the output link.
Here is a pseudocode of some sort to hopefully makes is clearer:
if (table1.colname = NULL OR table1.colname = '')
  then '999'
else
  if table1.column = 0
     then do a lookup on table2.colname for '1' return table2.colname2
  else
     do a lookup on table2.colname for '2' return table2.colname2
  if value is not found then '999'

I'm kinda new to datastage, so any comments or idea are greatly appreciated.
And please do let me know if you need other clarifications.
Thank you.

A: Use Transformer or Filter to split the records into three links based on the condition
First Link : Records containing Null or Empty
Second Link : Records containing Value Zero
third Link : Otherwise ( Remaining records)
Then do the look up on second and third link seperately as per the requirement
Then Funnel the output from First  link and the outputs from Look up
Use transformer to apply the fourth condition for non matching records
     Or

In transformer create a new field in which write condition like
If NullToEmpty(table1.column)='' then "DefaultValue"(Make sure that the value u are assigning should not have the matching records in reference table)
Else If table1.column = 0
then "1"
Else If table1.column = 1
then "2"
Else "Defaultvalue"
Then do the lookup on this new field with the table2.colname2 and assign "999" in the transformer for the lookup not found records


text:
Q: How can i send images available in asset folder using intent i'm trying to send some images available in asset folder using Intent but it providing error says shared failed try again later please provide me some suggestion.
Here is what i'm doing
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///android_asset/1.jpg"));
startActivity(Intent.createChooser(share, "Share Image!"));

i also trying by using like this
 Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://com.example.whatsappshare/asset/1.jpg"));
startActivity(Intent.createChooser(share, "Share Image!"));

Both the ways providing same result.

A: Once you created bitmap as I said earlier, use following snippet to send it as attachment.
String path = Images.Media.insertImage(getContentResolver(), your_bitmap, "title", null);
Uri screenshotUri = Uri.parse(path);

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
emailIntent.setType("image/png");

startActivity(Intent.createChooser(emailIntent, "Send email using"));

A: Assets directory is private to your app and is not available to other apps. So sharing directly from assets is not possible. You need to copy the file from assets to a public directory in the filesystem and then send the share intent pointing to the public file. Have a look here.

A: You can't share the file directly, but should be using a content provider to share it.
To avoid writing your own content provider, see cwac-provider

CWAC-Provider: Helping to Make Content Providers Sane
This project offers a StreamProvider, based on Google's FileProvider. Like FileProvider, StreamProvider is designed to serve up files, for reading and writing, through the ContentProvider interface (content:// Uri values). StreamProvider offers:

*

*Serving files from assets and raw resources

*Serving files from getExternalFilesDir() and getExternalCacheDir()


text:
Q: ssh-keygen: command not found in Docker I am trying to run this below command inside a docker container
(centos 7 as the base image)
ssh-keygen -t rsa -N ""

and I get this error:

ssh-keygen: command not found

And this is the Dockerfile I used to build the container
FROM centos:7

ENV VER "0.12.9"

RUN yum update -y && yum install wget -y && yum install unzip -y
RUN yum install epel-release -y && yum install ansible -y

RUN wget https://releases.hashicorp.com/terraform/${VER}/terraform_${VER}_linux_amd64.zip
RUN unzip terraform_${VER}_linux_amd64.zip
RUN mv terraform /usr/local/bin/
RUN rm -rf terraform_${VER}_linux_amd64.zip

Can someone help me, Please?

A: ssh-keygen is command provided by OpenSSH, you need to install it.
Add yum install openssh-clients -y to your Dockerfile.
FROM centos:7

ENV VER "0.12.9"

RUN yum update -y && yum install wget -y && yum install unzip -y
RUN yum install epel-release -y && yum install ansible -y && yum install openssh-clients -y

RUN wget https://releases.hashicorp.com/terraform/${VER}/terraform_${VER}_linux_amd64.zip
RUN unzip terraform_${VER}_linux_amd64.zip
RUN mv terraform /usr/local/bin/
RUN rm -rf terraform_${VER}_linux_amd64.zip


text:
Q: ImportError: No module named pyaudio with sudo I am trying to run a python3 script using sudo on raspberry pi, but it is always giving me an import error the first line, in my case "module pyaudio is not found".
I have tried changing the sudoers file and putting in an env_keep += "my_python_path" like this post : PYTHONPATH not working for sudo on GNU/Linux (works for root)
 but it doesn't seem to work.
However, when I run sudo with python2 or when I run python3 without sudo the import errors don't happen. Any suggestions on how to get it work with python3?

A: I just used sudo su to gain root access and everything worked fine.


text:
Q: PBS_MARQUEE Progressbar WinApi I'm trying to get a progress bar of the type PBS_MARQUEE working.
I can create the progress bar, but i just can't manage it to make it moving.
If found this, but i don't understand clearly what i have to do:
"Turns out since i had the progress bar as a resource instead of using the CreateWindowEx(..) i had to use SetWindowLongPtr(..) to set the PBS_MARQUEE style for this control..."
I create the progressbar that way:
   hwndPB = CreateWindowEx(0, PROGRESS_CLASS,
                            (LPSTR)NULL, WS_CHILD | WS_VISIBLE | PBS_MARQUEE ,
                            rcClient.left,
                            rcClient.bottom - cyVScroll,
                            rcClient.right, cyVScroll,
                            hwnd, (HMENU) 0, NULL, NULL);

Then i try to make it working:
    SetWindowLongPtr(hwndPB,GWL_STYLE,PBS_MARQUEE);
    SendMessage(hwndPB,(UINT) PBM_SETMARQUEE,(WPARAM) 1,(LPARAM)NULL );

Thx & regards

A: The problem is that you are obliterating the window style.  The error is the line:
SetWindowLongPtr(hwndPB,GWL_STYLE,PBS_MARQUEE);

This sets the PBS_MARQUEE style flag, but removes all other flags, most definitely not what you intend.
Instead you should use bitwise OR like so:
LONG_PTR style = GetWindowLongPtr(wndPB, GWL_STYLE);
SetWindowLongPtr(hwndPB, GWL_STYLE, style | PBS_MARQUEE);

I'm know next to nothing about C++ type rules so there will probably be wrinkles with this code, but I'm sure that this is your problem!
In fact, since you set the window style in the call to CreateWindowEx() I don't see why you need to modify it at all.

One final hunch at why your marquee progress bar is not working. Did you include a manifest for common controls v6? The marquee style is only supported in common controls v6 and up.
You can do this most simply by including the following in, for example, stdafx.h:
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

I tested this with the following code added to the blank Win32 project in Visual Studio:
HWND hwndPB = CreateWindowEx(
    0, PROGRESS_CLASS, (LPCWSTR)NULL,
    WS_CHILD | WS_VISIBLE | PBS_MARQUEE,
    0, 0, 400, 100,
    hWnd, (HMENU) 0, hInst, NULL
);
SendMessage(hwndPB,(UINT) PBM_SETMARQUEE,(WPARAM) 1,(LPARAM)NULL);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);

I needed to add the manifest pragma to get v6 comctl32 and without the pragma there was no marquee.


text:
Q: Loop animation with javascript I got stuck on a looping animation till the end of page, so it should continue where it left off. Here is link to code pen

var width = window.innerWidth ||
  document.documentElement.clientWidth ||
  document.body.clientWidth;
var granica = width * 10 / 100;
console.log(width);
var animacija = anime({
  targets: ".glavniDiv img",
  easing: 'linear',
  delay: 200,
  translateX: [{
      value: [0, 50],
      duration: 500,
    },
    {
      value: '+=50',
      duration: 500,
    }
  ],
  translateY: [{
      value: [-25, 25],
      duration: 500,
    },
    {
      value: '-=25',
      duration: 500
    }
  ],
});
.glavniDiv img {
  height: 70px;
  width: auto;
  position: fixed;
  top: 50%;
  margin-top: -50px;
  left: 10%;
}

.glavniDiv {}
  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

I tried with for loop and didn't work so i don't know if i tried it wrong way or what


text:
Q: Istio Ingress and Egress gateway pods went in to CrashLoopBackOff I am upgrading my Istio from v1.14.6 to v1.15.6 using canary deployment.
New istio control plane deployment was successful but ingress and egress gateway pods are going into CrashLoopBackOff.
The pod logs are:
kc -n istio-system logs istio-egressgateway-xxx-xxx
exec /usr/local/bin/pilot-agent: exec format error

Istioctl install output is:
istio-1.15.6 % ./bin/istioctl install --revision 1-15-6 -y -f ../istio-operator.yaml -f ../local-settings/eks/values.yaml
WARNING: Istio is being upgraded from 1.14.6 -> 1.15.6.
WARNING: Before upgrading, you may wish to use 'istioctl analyze' to check for IST0002 and IST0135 deprecation warnings.
✔ Istio core installed
✔ Istiod installed
✘ Ingress gateways encountered an error: failed to wait for resource: resources not ready after 5m0s: timed out waiting for the conditionystem/istio-ingressgateway
Deployment/istio-system/istio-ingressgateway (container failed to start: CrashLoopBackOff: back-off 2m40s restarting failed container=istio-proxy pod=istio-ingressgateway-55bb5dd9dd-42g42_istio-system(3db0d5af-5b10-4bd2-96fa-99ff1802a03c))
✘ Egress gateways encountered an error: failed to wait for resource: resources not ready after 5m0s: timed out waiting for the condition
Deployment/istio-system/istio-egressgateway (container failed to start: CrashLoopBackOff: back-off 2m40s restarting failed container=istio-proxy pod=istio-egressgateway-bcd94f69-9m6f4_istio-system(278a3ec3-4ddf-4914-89ab-ae4aff747176))
- Pruning removed resources
Error: failed to install manifests: errors occurred during operation

I'm not sure if I am missing any additional argument to my IstioOperator spec like os arch as from v1.15.6 they have started supporting arm as well.


text:
Q: Pastie is broken for Ubuntu 11.04 I had pastie working for the longest time on Ubuntu 11.04, working great, I love the little bugger :) I still have it working on my laptop (same system).
Recently I ran upgrade on all packages in my Ubuntu 11 system. Now pastie doesn't work, this is the error I get:
Traceback (most recent call last):
  File "/usr/bin/pastie", line 96, in <module>
    clipboard_protector = protector.ClipboardProtector()
  File "/usr/lib/pymodules/python2.7/pastielib/protector.py", line 72, in __init__
    self.history.set_payload(self.recover_history())
  File "/usr/lib/pymodules/python2.7/pastielib/protector.py", line 138, in recover_history
    history_tree = tree.parse(input_file)
  File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1177, in parse
    tree.parse(source, parser)
  File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 653, in parse
    parser.feed(data)
  File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1624, in feed
    self._raiseerror(v)
  File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1488, in _raiseerror
    raise err
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 2, column 380

Anyone know what to do to get this thing to work again or what the heck all those error's mean? I'm not a python guy.  I tried apt-get purge pastie and re-install but no go.

A: For those looking in the future for this same problem as Pastie doesn't help any at all! :)
The answer was hinted on by SirCharlo. By looking through the code I found that Pastie uses a clipboard history file in XML, the code for this is in the main Pastie file and protector.py.
Running a find in my home directory I found that Pastie stores this history file in ~/.local/share/pastie, it's called clipboard_history.
Basically something that was copied in the past had a character that Python didn't like or wasn't escaped right by the software code. So it was choking on that line of XML in the history file.
So just go to that directory and erase the file completely and restart pastie, works like a charm.  If your using an older version of Pastie the file is located at ~/.clipboard_history


text:
Q: Java - Objective C Socket UTF8 Problem I'm programming a little Client - Server program.
The Server is in Java and the Client IOS.
On the Server i use java.net.ServerSocket and on the Client the LXSocket. Sending Data (Integer, Double, Float, UTF8 String) from Client to Server works perfect, but when i'm trying to send a UTF8 String back to the Client it kinda fails. I can receive the message, but not convert it to a NSString.
Java sending Code:
public void sendMessage(java.net.Socket socket) throws IOException {
    DataOutputStream stream = new DataOutputStream(socket.getOutputStream());
    int i = swabInt(64);
    stream.writeInt(i);
    String message = "Message to send as UTF8.";
    int len = swabInt(message.length());
    stream.writeInt(len);
    stream.write(nachricht.getBytes("UTF8"));
}

IOS receiving Code:
-(IBAction)createSocket {
LXSocket *socket = [[[LXSocket alloc] init] autorelease];
[socket connect:@"localhost" port:11111];

int i = [socket readInt];
int len = [socket readInt];
NSData *data = [socket readBytesWithLength:len];
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

Receiving the Stream works, but when i'm trying to init the NSString it crashes.
Any ideas?
EDIT
Transmission works fine, but i found out something strange. I tried out this code:
NSString *test = @"The Message";
    const char *c = [test UTF8String];`
NSString *string = [[NSString alloc] initWithUTF8String:c];
NSLog(@"Decoding: %s", string);

But my Console says:
2011-03-17 22:51:27.555 Sockets[8641:207] Decoding: ¿Ø'

So is there any way to get a NSString from this char array encoded with UTF8??

A: Okay i figured it out...
Plain stupidity...
NSLog(@"%s", theString);

instead of
NSLog(@"%@", theString);

Epic fail.


text:
Q: Integer to binary without multiplication or division I am having trouble with writing a python program that reads an integer number and displays its binary representation, WITHOUT MULTIPLICATION OR DIVISION?
So it's supposed to convert like the integer 5 into 101.. Anyone can help out? Thank you very much!

A: print(bin(5))   # yes, it's this easy

A: You can calculate bin like this:
def bin2(x):
    binary_digits = []

    while x:
        binary_digits.append(x & 1)
        x >>= 1

    return "".join(str(digit) for digit in reversed(binary_digits))


text:
Q: Repeat instruction in assembly 8086 I've created 3 squares that appear nice to the eye. I only want to repeat this animation over and over, I know it ain't hard but I can't find how to do so. The explanations are in Romanian, sorry for them.
Basically I just want to clear the screen and make them appear over and over. Thanks for all the support.
.stack 100
.data
y1 dw 70
x  dw 70
y2 dw 120

x2 dw 130
y3 dw 70
y4 dw 120

x3 dw 190
y5 dw 70
y6 dw 120

l db 50; lungime
k db 50;latime
kfinal db 51
n db 50

.code
mov ax,@data
mov ds,ax
mov ah,0h
mov al,13h; comutare in modul grafic 13h (320 x 200)
int 10h

desen:
mov dx,y1
mov cx,x
mov al,1; culoare
mov bl,l; lungime linie
mov ah,0ch; scriere pixel, cu culoare in al, cx=x, dx=y
mov bh,0
ciclu1: int 10h ; aprindere pixel de coordonate (cx,dx)
push dx
mov dx,y2
call delay
call delay
call delay
call delay
int 10h
pop dx
inc cx
dec bl
jnz ciclu1
mov bl,k; latime

ciclu2: int 10h ; aprinde pixel de coord (cx,dx)
push cx
mov cx,x
call delay
call delay
call delay
call delay
int 10h
pop cx
inc dx
dec bl
jnz ciclu2
int 10h
mov dx,y3
mov cx,x2
mov al,14; culoare
mov bl,l; lungime linie
mov ah,0ch; scriere pixel, cu culoare in al, cx=x, dx=y
mov bh,0

ciclu3: int 10h ; aprindere pixel de coordonate (cx,dx)
push dx
mov dx,y4
call delay
call delay
call delay
call delay
int 10h
pop dx
inc cx
dec bl
jnz ciclu3
mov bl,k; latime
ciclu4: int 10h ; aprinde pixel de coord (cx,dx)
push cx
mov cx,x2
call delay
call delay
call delay
call delay
int 10h
pop cx
inc dx
dec bl
jnz ciclu4
int 10h
mov dx,y5
mov cx,x3
mov al,4; culoare
mov bl,l; lungime linie
mov ah,0ch; scriere pixel, cu culoare in al, cx=x, dx=y
mov bh,0

ciclu5: int 10h ; aprindere pixel de coordonate (cx,dx)
push dx
mov dx,y6
call delay
call delay
call delay
call delay
int 10h
pop dx
inc cx
dec bl
jnz ciclu5
mov bl,kfinal; latime ultimul patratel

ciclu6: int 10h ; aprinde pixel de coord (cx,dx)
push cx
mov cx,x3
call delay
call delay
call delay
call delay
int 10h
pop cx
inc dx
dec bl
jnz ciclu6
ret

delay:
push cx
mov cx, 0ffffh
et1: dec cx
jnz et1
pop cx
ret

mov ah,4ch
int 21h
end

A: Some important observations

*

*What first strikes me is that you've complicated matters by not using descriptive names for the program variables! See below for some better names.

y1 dw 70
x  dw 70
y2 dw 120

x2 dw 130
y3 dw 70
y4 dw 120

x3 dw 190
y5 dw 70
y6 dw 120

Box1Left    dw 70
Box1Top     dw 70
Box1Bottom  dw 120

Box2Left    dw 130
Box2Top     dw 70
Box2Bottom  dw 120

Box3Left    dw 190
Box3Top     dw 70
Box3Bottom  dw 120

*Although you've set your width and height both to 50 (l db 50 ;lungime k db 50 ;latime), the boxes that you draw have a surface of 51x51.

*Your 1st (blue) box and your 2nd (yellow) box use a different system than the 3rd (red) box when it comes to drawing the final LowerRightCorner dot. Why is that?
Why use the extra variable kfinal db 51 ?

*The code that draws the boxes ends with a ret instruction, yet it wasn't call-ed. This is wrong. Moreover the code that terminates to DOS is unreachable because it sits below another ret instruction.

*Instead of repeating the whole box drawing code 3 times, you should place it in a subroutine and have it call-ed 3 times.
    mov  al, 1        ; Blue
    mov  cx, Box1Left
    mov  dx, Box1Top
    mov  bp, Box1Bottom
    call DrawBox
    mov  al, 14       ; Yellow
    mov  cx, Box2Left
    mov  dx, Box2Top
    mov  bp, Box2Bottom
    call DrawBox
    mov  al, 4        ; Red
    mov  cx, Box2Left
    mov  dx, Box2Top
    mov  bp, Box2Bottom
    call DrawBox

    mov  ax, 4C00h    ; DOS.Terminate
    int  21h

DrawBox:
    mov  ah, 0Ch      ; BIOS.WritePixel
    mov  bh, 0        ; DisplayPage
    push cx           ; (1)

    mov  bl, 50       ; Width = Length of the horizontal line
ciclu1:
    int  10h
    xchg dx, bp
    int  10h
    xchg dx, bp
    inc  cx
    dec  bl
    jnz  ciclu1

    pop  bp           ; (1)
    mov  bl, 51       ; Height = Length of the vertical line
ciclu2:
    int  10h
    xchg cx, bp
    int  10h
    xchg cx, bp
    inc  dx
    dec  bl
    jnz  ciclu2
    ret

The answer to your question

Basically I just want to clear the screen and make them appear over and over.

If this is all that you want then you simply need to restart your program. Your program already starts by clearing the screen because it sets video mode 13h.
Please give the user a chance to stop your program. See how I did it in below example code:
    mov  ax, @data
    mov  ds, ax

Again:
    mov  ah, 00h
    mov  al, 13h; comutare in modul grafic 13h (320 x 200)
    int  10h

    ; Here you draw the boxes! Use the above code snippet...

    mov  ah, 00h      ; BIOS.WaitKey Wait for the user to press any key
    int  16h          ; -> AX
    cmp  al, 27       ; Did the user press <ESC> ?
    je   Exit         ; Yes
    jmp  Again        ; No, restart the program (this could be a big jump)

Exit:
    mov  ax, 4C00h    ; DOS.Terminate
    int  21h

; All subroutines go here, below the Exit to DOS!

You can read more about drawing in this post
How to create and draw sprites in emu8086?


text:
Q: Unsure about structures that use pointers and inheritance Hi guys I am still pretty new to coding so give me some grace, but I basically have a error that has something to do with a structure I am sing that contains an object I am calling Records. I am not sure if I should make this object a pointer because when I do the program compile but has a runtime error. The error I am getting is

Undefined reference to 'Records::Records()'
  1d returned 1 exit status

The runtime error I get when I use a pointer to Records in the Employee structure happens as the first reference to it.
Since I don't have much commenting in the program here is my explanation. It is basically a clock in/clock out program. The Date class is self explanatory. The shift class implements this and holds when the employee clocks in and out. The Records class basically holds a week work of shift objects and will be used to write this info to a spread sheet.
Also as I said I am pretty new to coding so if you have any tips about the structure of the program, or anything of the sort I would love to hear them.
main.cpp
*
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include <limits>
#include <fstream>
#include <ctime>
using namespace std;
#include "Date.h"
#include "Shift.h"
#include "Records.h"
bool AdminMenu(int id);
int EmployeeMenu(int id);
void printInfo(int id);
int findEmptySpot();
void addEmployee();
void printEmployeeList();
void generateEmployees();
void degenerateEmployees();
Date blankDate(1,1,1900,0,0);
struct employee{
    string name;
    bool adminStatus;
    int id;
    double wage;
    Records  r;
};
typedef struct employee Employee;
Employee data[100];
ifstream employeeList ("employeeList.txt");
int main()
{
    bool x = true;
    if (employeeList.is_open())
    {
        generateEmployees();
        employeeList.close();
    }
    else
        cout << "Unable to open file";
    Sleep(1000);
    while(x)
    {
        int input,i=0;
        cout<< "Enter your 4 digit id: ";
        cin>> input;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        std::system("cls");
        while(data[i].id!=input)
            i++;
            ;
        if(data[i].adminStatus ==true)
            x = AdminMenu(i);
        else
            EmployeeMenu(i);
    }
    employeeList.close();
    degenerateEmployees();
    return 0;
}
bool AdminMenu(int placeInArray)
{
    while(true)
    {
        time_t now = time(0); // get current time
        struct tm* tm = localtime(&now);
        Date blankDate(1,1,1900,0,0);
        Date currentDate(tm->tm_mon,tm->tm_mday,tm->tm_year,tm->tm_min,tm->tm_sec);
        std::system("cls");
        int input=0;
        cout<<"You are in the admin menu\n1. Print My info\n2. Add Employee\n3. Edit Employee\n4. Delete Employee\n5. Print Employee List\n6. Clock In\n7. Clock Out\n8. Close Program\n9. Finish"<<endl;
        cin>> input;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        if(input<1||input>9)
        {
            cout<< "Invalid input please try again"<<endl;
            Sleep(1000);
            std::system("cls");
        }
        else if(input==1)
        {
            std::system("cls");
            printInfo(placeInArray);
            getch();
            std::system("cls");
        }
        else if(input ==2)
        {
            addEmployee();
        }
        else if (input ==3)
        {
            std::system("cls");
            int placeToEdit, whatToEdit;
            cout << "Please look at the list of employees below and enter the number of the employee you would like to edit";
            printEmployeeList();
            cin>> placeToEdit;
            std::system("cls");
            cout<< "What do you want to change? \n1. Name\n2. ID\n3. Admin Status\n4. Clock In/Out";
            cin>> whatToEdit;
            if(whatToEdit==1)
            {
                std::system("cls");
                cout<<"Enter the employee's new name: ";
                cin >> data[placeToEdit].name;
                cout<< "\nEmployee's name adjusted successfully.";
                Sleep(1000);
            }
            else if(whatToEdit==2)
            {
                std::system("cls");
                cout<<"Enter the employee's new ID: ";
                cin >> data[placeToEdit].id;
                cout<< "\nEmployee's ID adjusted successfully.";
                Sleep(1000);
            }
            else if(whatToEdit == 3)
            {
                std::system("cls");
                cout<<"Enter the employee's new admin status: ";
                cin >> data[placeToEdit].adminStatus;
                cout<< "\nEmployee's Admin status adjusted successfully.";
                Sleep(1000);
            }
            else if(whatToEdit == 4)
            {
               /* std::system("cls");
                int status;
                cout<<"Would you like to clock them in or out?(0 or 1)";
                cin >> status;*/
            }
            else
            {
                std::system("cls");
                cout<< "Error: invalid input. You will be returned to the admin menu";
                Sleep(1000);
            }
        }
        else if(input ==4)
        {
            std::system("cls");
            int placeToEdit;
            cout << "Please look at the list of employees below and enter the number of the employee you would like to delete";
            printEmployeeList();
            cin>> placeToEdit;
            if( data[placeToEdit].id!= 0)
            {
                data[placeToEdit].name = '\0';
                data[placeToEdit].id = '\0';
                data[placeToEdit].adminStatus='\0';
                cout<< "\nEmployee successfully deleted.";
                Sleep(1000);
            }
            else
                cout<< "Error: invalid input. You will be returned to the admin menu";
        }
        else if(input ==5)
        {
            printEmployeeList();
            Sleep(1000);
        }
        else if (input == 6)
        {
            if(tm->tm_wday==1)
            {
                data[placeInArray].r.Monday.Shift::setBeginOFShift(blankDate);
            }
            else if(tm->tm_wday==2)
            {
                data[placeInArray].r.Tuesday.Shift::setBeginOFShift(blankDate);
            }
            else if(tm->tm_wday==3)
            {
                data[placeInArray].r.Wednesday.Shift::setBeginOFShift(blankDate);
            }
            else if(tm->tm_wday==4)
            {
                data[placeInArray].r.Thursday.Shift::setBeginOFShift(blankDate);
            }
            else if(tm->tm_wday==5)
            {
                data[placeInArray].r.Friday.Shift::setBeginOFShift(blankDate);
            }
            std::system("cls");
            cout<< "Successfully clocked in at";
            currentDate.Date::print();
        }
        else if (input == 7)
        {
            if(tm->tm_wday==1)
            {
                data[placeInArray].r.getMonday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==2)
            {
                data[placeInArray].r.getTuesday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==3)
            {
                data[placeInArray].r.getWednesday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==4)
            {
                data[placeInArray].r.getThursday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==5)
            {
                data[placeInArray].r.getFriday().setEndOFShift(currentDate);
            }
        }
        else if(input ==8)
        {
            std::system("cls");
            return false;
        }
        else if(input ==9)
        {
            std::system("cls");
            return true;
        }
    }
}
int EmployeeMenu(int placeInArray)
{
    int input;
    while(true)
    {
        time_t now = time(0); // get current time
        struct tm* tm = localtime(&now);
        Date blankDate(1,1,1900,0,0);
        Date currentDate(tm->tm_mon,tm->tm_mday,tm->tm_year,tm->tm_min,tm->tm_sec);
        cout<< "You are in the Employee Menu\n1. Print My info\n2. Clock in\n3. Clock out\n9. Finish";
        cin>> input;
        std::system("cls");
        if(input<1||input>9)
        {
            cout<< "Invalid input please try again"<<endl;
            Sleep(1000);
            std::system("cls");
        }
        else if(input==1)
            printInfo(placeInArray);
        else if (input == 2)
        {
            if(tm->tm_wday==1)
            {
                data[placeInArray].r.getMonday().setBeginOFShift(currentDate);
            }
            else if(tm->tm_wday==2)
            {
                data[placeInArray].r.getTuesday().setBeginOFShift(currentDate);
            }
            else if(tm->tm_wday==3)
            {
                data[placeInArray].r.getWednesday().setBeginOFShift(currentDate);
            }
            else if(tm->tm_wday==4)
            {
                data[placeInArray].r.getThursday().setBeginOFShift(currentDate);
            }
            else if(tm->tm_wday==5)
            {
                data[placeInArray].r.getFriday().setBeginOFShift(currentDate);
            }
        }
        else if (input == 3)
        {
            if(tm->tm_wday==1)
            {
                data[placeInArray].r.getMonday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==2)
            {
                data[placeInArray].r.getTuesday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==3)
            {
                data[placeInArray].r.getWednesday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==4)
            {
                data[placeInArray].r.getThursday().setEndOFShift(currentDate);
            }
            else if(tm->tm_wday==5)
            {
                data[placeInArray].r.getFriday().setEndOFShift(currentDate);
            }
        }
        else if(input ==9)
        {
            std::system("cls");
            return 0;
        }
    }
}
void printInfo(int placeInArray)
{
    cout<<"Name: "<<data[placeInArray].name<<endl;
    cout<<"ID: "<<data[placeInArray].id<<endl;
    cout<<"Admin status: "<< data[placeInArray].adminStatus<<""<<endl;
}
int findEmptySpot()
{
     int i=0;
     while(data[i].id!=0)
            i++;
     return i;
}
void printEmployeeList()
{
    int x;
    for( x = 0; x<100; x++)
    {
        if( data[x].id!=0)
            cout<<"\n"<<x<<". "<<data[x].name<<endl;
    }
}
void addEmployee()
{
    int newPlace = findEmptySpot();
    std::system("cls");
    cout<<" Enter the employee's name: ";
    cin >> data[newPlace].name;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout<<" Enter the employee's ID: ";
    cin >> data[newPlace].id;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout<<" Enter the employee's admin status: ";
    cin >> data[newPlace].adminStatus;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    std::system("cls");
    cout<< "Your new employee profile has been created!";
    printInfo(newPlace);
}
void generateEmployees()
{
        string n;
        bool a;
        int i, j =0;
        while (employeeList >>n>>i>>a )
        {
            data[j].name=n;
            data[j].adminStatus=a;
            data[j].id=i;
            j++;
        }
}
void degenerateEmployees()
{
    ofstream employeeList("employeeList.txt",ios::trunc);
    int x;
    for( x = 0; x<100; ++x)
    {
        if( data[x].id!=0)
            employeeList<< data[x].name<< " "<< data[x].id<< " "<< data[x].adminStatus<< "\n";``
    }
    employeeList<< "End 0 0";
    employeeList.close();
}

*
Date.cpp
#include <iostream>
#include "Date.h" // include Date class definition
using namespace std;

// constructor confirms proper value for month; calls
// utility function checkDay to confirm proper value for day
//-------------------------------------------------------------
Date::Date( int mn, int dy, int yr, int hr, int minu)
{
    month = mn;
    year = yr;
    day = dy ;
    hour = hr;
    minute=minu;
} // end Date constructor

Date::Date (const Date & dateToCopyFrom) // copy constructor
{
    month = dateToCopyFrom.month;
    day = dateToCopyFrom.day;
    year = dateToCopyFrom.year;
    hour = dateToCopyFrom.hour;
    minute = dateToCopyFrom.minute;
}

Date & Date::operator = (const Date & other) // assignmenrt operator
{
    this->month = other.month;
    this->day = other.day;
    this->year = other.year;
    this->hour = other.hour;
    this->minute= other.minute;
    return *this;
}

/* setDate date from the user */
void Date::setDate()
{
    bool flag = false;
    int mn,dy,yr,hr,minu;
    cin.clear();
    do
    {
        cout << "(month day year hour minute):\n";
        cin >> mn >> dy >> yr >> hr >> minu;
        year = yr;
        month = mn;
        day = dy;
        hour = hr;
        minute=minu;

        if(yr < 1900)
        {
            cout << "Cannot handle dates prior to 1900 AD" << endl;
            cout << "Try again!" << endl;
            flag = false;
        }
        else if(!isValidDate())
        {
            cout << "Invalid date" << endl;
            cout << "Try again!" << endl;
            flag = false;
        }
        else
            flag = true;
    }

    while (!flag);

}//end date constructor

// print Date object in form month/day/year
//-------------------------------------------------------------
void Date::print() const
{
    std::cout << hour<<":"<<minute<< "on"<< month << '/' << day << '/' << year;
} // end function print

// output Date object to show when its destructor is called
//-------------------------------------------------------------
Date::~Date()
{
} // end ~Date destructor

// utility function to confirm proper day value based on
// month and year; handles leap years, too
//-------------------------------------------------------------
int Date::checkDay( int testDay ) const
{
    static const int daysPerMonth[ monthsPerYear + 1 ] =
    { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    // determine whether testDay is valid for specified month
    if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
        return testDay;

    // February 29 check for leap year
    if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
                                          ( year % 4 == 0 && year % 100 != 0 ) ) )
        return testDay;

    std::cout << "Invalid day (" << testDay << ") set to 1.\n";

    return 1; // leave object in consistent state if bad value
} // end function checkDay

bool Date::operator>(const Date &dateOnRight) // greater than operator
{
    bool greater;

    int year = dateOnRight.getYear();
    if(dateOnRight.getYear() > year)
        greater = false;

    else if(dateOnRight.getYear() == year && dateOnRight.getMonth() > month)
        greater = false;

    else if(dateOnRight.getYear() == year && dateOnRight.getMonth() == month && dateOnRight.getDay() >= day)
        greater = false;

    else if(dateOnRight.getYear() == year && dateOnRight.getMonth() == month && dateOnRight.getDay() == day&& dateOnRight.getHour()>= hour)
        greater = false;

    else if(dateOnRight.getYear() == year && dateOnRight.getMonth() == month && dateOnRight.getDay() == day&& dateOnRight.getHour()== hour&& dateOnRight.getMinute()<= minute)
        greater = false;
    else
        greater = true;

    return greater;

}
// add one year to date
void Date::addYears(int nyears)
{
    year = year + nyears;
    //month = month;
    if (day == 29 && !isLeapYear(year))
    {
        day = 28;
    }//end if

}

/***********************************************/
bool Date::isLeapYear(int year)
{
    bool leapYear = false;
    if (year % 400 == 0)
    {
        leapYear = true;
    }
    else
    {
        if (year % 100 == 0)
        {
            leapYear = false;
        }
        else
        {
            if (year % 4 == 0)
                leapYear = true;
            else
                leapYear = false;
        }
    }
    // cout << "leapYear  " << leapYear << endl;
    return leapYear;

}

/************************************************/
bool Date::isValidDate()
{
    bool validDate;
    int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    if(month < 1 || month > 12
            || day < 0 || !((isLeapYear(year) && month == 2 && day <= 29)
                            || (day <= monthDays[month - 1])))
        validDate = false;
    else
        validDate = true;
    // cout << "validDate  " << validDate << endl;
    return validDate;
}

Date.h
#ifndef DATE_H
#define DATE_H

class Date
{
public:
    static const int monthsPerYear = 12; // number of months in a year
    Date (int mn=1, int dy=1, int yr=1900, int hr=0, int minu =0); // constructors
    Date (const Date& dateToCopyFrom); // copy constructor
    Date & operator = (const Date & other); // assignmenrt operator
    void setDate ();
    int getYear() const {return(year);};
    int getMonth() const {return (month);};
    int getDay() const {return (day);};
    int getHour() const {return (hour);};
    int getMinute() const {return (minute);};
    void print() const; // print date in month/day/year format
    bool operator>(const Date &dateOnRight);
    void addYears(int nyears);

    ~Date(); // destructor provided to confirm destruction order
private:
    int month; // 1-12 (January-December)
    int day; // 1-31 based on month
    int year; // any year
    int hour;
    int minute;
    // utility function to check if day is proper for month and year
    int checkDay( int testDay ) const;
    bool isLeapYear(int year);
    bool isValidDate();
};

#endif

Shift.cpp
#ifndef DATE_H

#define DATE_H

class Date
{
public:
    static const int monthsPerYear = 12; // number of months in a year
    Date (int mn=1, int dy=1, int yr=1900, int hr=0, int minu =0); // constructors
    Date (const Date& dateToCopyFrom); // copy constructor
    Date & operator = (const Date & other); // assignmenrt operator
    void setDate ();
    int getYear() const {return(year);};
    int getMonth() const {return (month);};
    int getDay() const {return (day);};
    int getHour() const {return (hour);};
    int getMinute() const {return (minute);};
    void print() const; // print date in month/day/year format
    bool operator>(const Date &dateOnRight);
    void addYears(int nyears);

    ~Date(); // destructor provided to confirm destruction order
private:
    int month; // 1-12 (January-December)
    int day; // 1-31 based on month
    int year; // any year
    int hour;
    int minute;
    // utility function to check if day is proper for month and year
    int checkDay( int testDay ) const;
    bool isLeapYear(int year);
    bool isValidDate();
};

#endif

Shift.h
#include "Date.h"

#ifndef SHIFT_H
#define SHIFT_H

using namespace std;

class Shift: public Date
{
public:
    //Constructor
    Shift();//blankDate,blankDate,(9999),blankDate);
    Shift(Date in, Date out, int identity){beginOfShift=in; endOfShift=out; ident = identity;};

    void setBeginOFShift(Date x);
    void setEndOFShift(Date x);

    Date getBeginOfShift() const{return (beginOfShift);};
    Date getEndOfShift() const{return (endOfShift);};

    Date getLength();
    int getID() const{return (ident);};
    ~Shift();
private:
    Date beginOfShift;
    Date endOfShift;
    Date Length;
    int ident;

};

#endif // SHIFT_H

Records.cpp
#include<iostream>

using namespace std;

#include "Records.h"
#include "Shift.h"
extern Date blankDate;

void Records::setBeginningOfWeek(Date x)
{
    getBeginningOfWeek()=x;
}
void Records::setMonday(Shift x)
{
    getMonday()=x;
}
void Records::setTuesday(Shift x)
{
    getTuesday()=x;
}
void Records::setWednesday(Shift x)
{
    getWednesday()=x;
}
void Records::setThursday(Shift x)
{
    getThursday()=x;
}
void Records::setFriday(Shift x)
{
    getFriday()=x;
}

Records::~Records()
{

}

Records.h
#include "Shift.h"

#ifndef RECORDS_H
#define RECORDS_H

using namespace std;

class Records: public Shift
{
    public:

        Records(Date x){beginningOfWeek=x;};
        Records();
        void setBeginningOfWeek(Date x);
        void setMonday(Shift x);
        void setTuesday(Shift x);
        void setWednesday(Shift x);
        void setThursday(Shift x);
        void setFriday(Shift x);

        Date getBeginningOfWeek() const{return(beginningOfWeek);};
        Shift getMonday() const{return(Monday);};
        Shift getTuesday() const{return(Tuesday);};
        Shift getWednesday() const{return(Wednesday);};
        Shift getThursday() const{return(Thursday);};
        Shift getFriday() const{return(Friday);};
        ~Records();

        Date beginningOfWeek;
        Shift Monday;
        Shift Tuesday;
        Shift Wednesday;
        Shift Thursday;
        Shift Friday;
};

#endif // RECORDS_H

A: Seems like you declared a constructor for Records, but didn't define it.


text:
Q: Woocommerce cart items discount gets reset in checkout I've been trying to implement a discount in my store with the following code:
add_action('woocommerce_before_calculate_totals', 'set_discount', 10 );

function set_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // 50% items discount
        $cart_item['data']->set_price( $cart_item['data']->get_price() / 2 );
    }
}

*

*The code works on the cart page, the discount is applied as it should

*The code works on the checkout page for a second or two, BUT when then the loading spinner has finalized the discount disappears and the original price is shown

It seems the set price is overwritten in the checkout by some standard AJAX request which reuses the original price, or something. I have tried using add_fee() with the same result, I have also tried deactivating all plugins (except woocommerce, of course) and I have tried switching to another theme - nothing works!
Using Wordpress 5.0.3, Woocommerce 3.5.4, Child theme of Storefront 2.4.2

UPDATE: Added screenshots.
1) This is what should be shown on checkout, and is being shown for around 1-2 seconds:

2) This is what is shown once the loading spinner is finalized - the original prices:

A: The correct code to be used since Woocommerce 3.2+ avoiding problems and errors is:
add_action('woocommerce_before_calculate_totals', 'cart_item_discount', 10, 1 );
function cart_item_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        $original_price   = $cart_item['data']->get_price(); // Get original product price
        $discounted_price = $original_price / 2; // 50 % of discount
        $cart_item['data']->set_price( $discounted_price );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works (Tested on last versions: Wordpress 5.0.x | Woocommerce 3.5.x | Storefront 2.4.x)

If it doesn't work, it's because some other things or customizations are interacting with it. You need first to check Woocommerce > Status for red items (where all overridden templates, at the end, need to be up to date).

See: Change cart item prices in Woocommerce 3

A: add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $custom_price = ($value['data']->price)/2;
        //$value['data']->price = $custom_price;
        // for WooCommerce version 3+ use:
         $value['data']->set_price($custom_price);
    }
}


text:
Q: Merge small files into large files for Hadoop Distributed Cache? I have a lot of small files (size ~ 1MB) that I need to distribute. It's known that Hadoop and HDFS prefer large files. But I don't know whether this can also be applied to Distributed Cache since the distributed files are stored on local machines.
If they need to be merged, what is the best way to merge files programmatically on HDFS ?
One more question: what are the benefits of using symlink ? Thanks

A: You can create an archive (tar or zip) of all your small files and add it to the distributed cache as follows:
DistributedCache.addCacheArchive(new URI("/myapp/myzip.zip", job);

And get the files in your mapper/reducer as follows:
public void configure(JobConf job) {
         // Get the cached archives/files
         File f = new File("./myzip.zip/some/file/in/zip.txt");
       }

Read more here

A: Here is a blog from Cloudera on the small files problem.


text:
Q: Getting user information (email specificlyy) before he verified his email Hi,

I am trying to get the user email address, and in a specific scenario I have a problem.
The scenario is:
1.       Register a new facebook user
2.       Do not verify email on FB
3.       Try to do FB connect from the app
4.       On the pop up(FB pop up) that say you have to verify the email(on FB), click on the "allow" button.(DO NOT CLOSE THE POP UP)
5.       Verify the email with FB
6.       Click "allow" once more on the pop up - the pop up will close
-----a.       The app will be allowed on the user FB account but when we will try to get his basic information his email will be show as FB email
7.       To get his real email we need to remove the app from the user FB account and then try again from the app so that the app will get new permissions to the user account.

Is there a way to not be must to remove the app from the user account and re-allow it?

A: This sounds like an extreme edge case my QA people would find and report as a bug. :D  When a user is connecting to an application, they can specify the email (either their real one, or a facebook proxy one). So it appears that when a user has not verified their email, but allows access to the app, they are not given a dropdown to choose which email to use (real vs proxy) because facebook does not have a verified "real" one on file.  So, even with that asside, there is no way for a user to "change" which of the two emails to use for an app without deauthorizing and then reauthorizing the app.


text:
Q: Cumulative sum of a column I have a table that has the below data.
COUNTRY LEVEL   NUM_OF_DUPLICATES
  US    9           6
  US    8           24
  US    7           12
  US    6           20
  US    5           39
  US    4           81
  US    3           80
  US    2           430
  US    1           178
  US    0           430

I wrote a query that will calculate the sum of cumulative rows and got the below output .
COUNTRY LEVEL   NUM_OF_DUPLICATES      POOL
  US    9           6                   6
  US    8           24                  30
  US    7           12                  42
  US    6           20                  62
  US    5           39                  101
  US    4           81                  182
  US    3           80                  262
  US    2           130                 392
  US    1           178                 570
  US    0           254                 824

Now I want to to filter the data and take only where the POOL <=300, if the POOL field does not have the value 300 then I should take the first value after 300. So, in the above example we do not have the value 300 in the field POOL, so we take the next immediate value after 300 which is 392. So I need a query so that I can pull the records POOL <= 392(as per the example above) which will yield me the output as
COUNTRY LEVEL   NUM_OF_DUPLICATES      POOL
  US    9           6                   6
  US    8           24                  30
  US    7           12                  42
  US    6           20                  62
  US    5           39                  101
  US    4           81                  182
  US    3           80                  262
  US    2           130                 392

Please let me know your thoughts. Thanks in advance.

A: declare @t table(Country varchar(5), Level int, Num_of_Duplicates int)
insert into @t(Country, Level, Num_of_Duplicates)
values
('US', 9, 6),
('US', 8, 24),
('US', 7, 12),
('US', 6, 20),
('US', 5, 39),
('US', 4, 81),
('US', 3, 80),
('US', 2, 130/*-92*/),
('US', 1, 178),
('US', 0, 430);

select *, sum(Num_of_Duplicates) over(partition by country order by Level desc),
(sum(Num_of_Duplicates) over(partition by country order by Level desc)-Num_of_Duplicates) / 300 as flag,--any row which starts before 300 will have flag=0
--or
case when sum(Num_of_Duplicates) over(partition by country order by Level desc)-Num_of_Duplicates < 300 then 1 else 0 end as startsbefore300
from @t;

select *
from
   (
    select *, sum(Num_of_Duplicates) over(partition by country order by Level desc) as Pool
    from @t
) as t
where Pool - Num_of_Duplicates < 300 ;

A: The logic here is quite simple:

*

*Calculate the running sum POOL value up to the current row.

*Filter rows so that the previous row's total is < 300, you can either subtract the current row's value, or use a second sum

*If the total up to the current row is exactly 300, the previous row will be less, so this row will be included

*If the current row's total is more than 300, but the previous row is less then it will also be included

*All higher rows are excluded

It's unclear what ordering you want. I've used NUM_OF_DUPLICATES column ascending, but you may want something else

SELECT
    COUNTRY,
    LEVEL,
    NUM_OF_DUPLICATES,
    POOL
FROM (
    SELECT *,
        POOL = SUM(NUM_OF_DUPLICATES) OVER (ORDER BY NUM_OF_DUPLICATES ROWS UNBOUNDED PRECEDING)
        -- alternative calculation
        -- ,POOLPrev = SUM(NUM_OF_DUPLICATES) OVER (ORDER BY NUM_OF_DUPLICATES ROWS UNBOUNDED PRECEDING AND 1 PRECEDING)
    FROM YourTable
) t
WHERE POOL - NUM_OF_DUPLICATES < 300;
-- you could also use POOLPrev above

A: I used two temp tables to get the answer.
 DECLARE @t TABLE(Country VARCHAR(5), [Level] INT, Num_of_Duplicates INT)
 INSERT INTO @t(Country, Level, Num_of_Duplicates)
  VALUES ('US', 9, 6),
      ('US', 8, 24),
      ('US', 7, 12),
      ('US', 6, 20),
      ('US', 5, 39),
      ('US', 4, 81),
      ('US', 3, 80),
      ('US', 2, 130),
      ('US', 1, 178),
      ('US', 0, 254);

SELECT
    Country
    ,Level
    , Num_of_Duplicates
    , SUM (Num_of_Duplicates) OVER (ORDER BY id) AS [POOL]
 INTO #temp_table
FROM
   (
    SELECT
        Country,
        level,
        Num_of_Duplicates,
        ROW_NUMBER() OVER (ORDER BY country) AS id
    FROM    @t
 ) AS A

SELECT
    [POOL],
    ROW_NUMBER() OVER (ORDER BY [POOL] )   AS [rank]
INTO #Temp_2
FROM  #temp_table
WHERE [POOL] >= 300

SELECT *

FROM #temp_table WHERE
[POOL]   <= (SELECT [POOL] FROM #Temp_2 WHERE [rank] = 1 )

DROP TABLE #temp_table
DROP TABLE #Temp_2


text:
Q: Repeat regex n time error in python3 In my code I got answer [('hathatat', 'hat')] but I want [('hathatat')]. And please some one tell how to repeater any whole regex for n time.
import re
x='hathatatlatrat'
y = re.findall("((hat){2}at)",x)
print(y)

A: Try like this:
y = re.findall('((?:hat){2}at)', x)

hat will not be captured this way.


text:
Q: Show only the first image from a list and remove the rest using jquery I have a list of 5 images displaying on my site. Somehow, I want to display only the first image to indicate it is image of the week. The rest can stay with only titles. How do I use jquery to remove the rest images?

Image One

Image Two

Image Three

Image Four

Image Five

Cheers

A: $('li:not(li:first) img').remove();

You can use this
or
$('.wpp-list li:not(li:first) img').remove();

fiddle : http://jsfiddle.net/5SUwp/5/


text:
Q: What is the time complexity of removing the first character in a Python string? I have the following code:
>>> s = "stackoverflow"
>>> tmp = s[0]
>>> s = s[1:]
>>> s
'tackoverflow'

I am performing this "remove first" sort of operation repeatedly and am trying to determine how it affects performance.
Is a single slice operation like the one shown above O(1)? If it is not O(1), is there a way that I can perform the operation with a complexity of O(1)?

A: Python's str() does slicing s[1:] in O(n) time, because str() is immutable and any slicing operations create whole new string and copies all slice data, so for string of length N this operations is O(N).
To do any slicing in O(1) time you need to use special implementations, like Numpy has for its arrays. Numpy arrays keep pointer to allocated array plus three extra fields begin, end, stride.
Before slicing Numpy's array having N elements will start with begin=0, end=N. After slicing e.g. a[1:], unlike str() Numpy array doesn't copy any memory but just changes begin/end/stride. Memory pointer and size remain the same. Thus after a[1:] we will have begin=1, end=N. After one more a[1:] we will have begin=2, end=N.
For strings you can convert them one time at program beginning to Numpy arrays of uint32 elements (because Unicode code point is 32-bit at current time). Then do all the operations inside your program only in Numpy arrays. Numpy also has many string operations implemented for its arrays.
You can do slicing and many other operations very fast, much faster than working with Python's str(). And all slicing operations are done in O(1) time. After you're done with Numpy operations you convert back to Python's str().
Next follows example of code. It first converts Python str() to numpy array. Then does any operations including slicing (slicing is done in O(1) time on numpy arrays). And when we're finished numpy array is converted back to Python's str().
Try it online!
import numpy as np
s = 'abcde'
# Convert string to Numpy array
a = np.frombuffer(s.encode('utf-32-le'), dtype = np.uint32)
# Do any slicing operations in O(1) time
a = a[1:]
a = a[1:]
# Convert Numpy array to string
s = a.tobytes().decode('utf-32-le')
print(s)

Output:
cde


text:
Q: Get pixel color from bitmap data at specified coords [x, y] I want to get pixel color on raster coordinates like for example:
[0,0] - pixel in first row and first column (top left)
[0,1] - pixel in first row and second column and so on.
I'm loading my bitmap like so:
BitsPerPixel = FileInfo[28];
width = FileInfo[18] + (FileInfo[19] << 8);
height = FileInfo[22] + (FileInfo[23] << 8);
int PixelsOffset = FileInfo[10] + (FileInfo[11] << 8);
int size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Pixels.resize(size);
hFile.seekg(PixelsOffset, ios::beg);
hFile.read(reinterpret_cast<char*>(Pixels.data()), size);
hFile.close();

and my GetPixel function:
void BITMAPLOADER::GetPixel(int x, int y, unsigned char* pixel_color)
{
    y = height - y;
    const int RowLength = 4 * ((width * BitsPerPixel + 31) / 32);
    pixel_color[0] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8];
    pixel_color[1] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 1];
    pixel_color[2] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 2];
    pixel_color[3] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 3];
}

I know the data in bitmap are stored up side down, so I wanted to invert it using the y = height - y; but with this line I only get some values which even are not in the image data array. Without inverting the image I get some values which are in the array but they never correspond with the coords given. My bitmap can be 24-bit or 32-bit.

A: For bit depth = 24, 3 bytes are stored. The padding is not done per pixel, only on each row:
const int bytesPerPixel = BitsPerPixel / 8;
const int align = 4;
const int RowLength = (width * bytesPerPixel + (align - 1)) & ~(align - 1);
...
pixel_color[0] = Pixels[RowLength * y + x * bytesPerPixel];
...


text:
Q: c# How to click button using selenium webdriver? I tried to click 'Sign In' button.
but It doesn't click at all.
my code is below.
Can anybody help me?
[FindsBy(How = How.XPath, Using = "//input[@name='ctl00$MainContent$LoginForm$LoginButton' and @value='sign in']")]
    [CacheLookup]
    private IWebElement Submit { get; set; }

    public LoginPage(IWebDriver driver)
    {
        this.driver = driver;
        PageFactory.InitElements(driver, this);
    }

    public void LoginToApplication()
    {
        System.Threading.Thread.Sleep(5000);
        Submit.Click();
     }

A: Try any of these below mentioned xpath.
//button[text()='sign in']

Explanation:- Use text method along with <button> tag.

OR

//button[@class='color'][text()='sign in']

Explanation:- Use class attribute and text method along with <button> tag.

OR

//button[@type='button'][text()='sign in']

Explanation:- Use type attribute and text method along with <button> tag.
Suggestion:- Instead of using absolute xpath, use relative xpath.


text:
Q: Branch.io app indexing is not searching app via google app I have setup following code for app indexing using Branch.io
   BranchUniversalObject branchUniversalObject = new BranchUniversalObject()
                .setCanonicalIdentifier("testing/")
                .setCanonicalUrl("testing") // optional
                .setTitle("irctc")
                .setContentDescription("my tetsing ")
                .setContentImageUrl("http://example.com/xyz")
                .setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC)
                .addContentMetadata("property1", "x")
                .addContentMetadata("property2", "y");

branchUniversalObject.listOnGoogleSearch(this);

Manifest
        <data
            android:host="open"
            android:scheme="testing"  />

I also have enabled in Branch dashboard page:-
Automatic sitemap generation (for Google App Indexing)
But the concern is google app is not searching my app when is search via keyword "testing".
Can anyone tell me where i am mistaken. Any help will be appreciated.

A: Alex from Branch.io here: while theoretically possible, this is not likely to produce results. The steps you've taken will submit this piece of content to Google for indexing (though there is a delay of up to 24 hours before that submission happens on the Branch end). Unfortunately this is simply a submission and not any sort of guarantee that Google will actually do anything with what you have submitted.
The algorithms Google uses for indexing and ranking are not public, so even if the submission is successful, it's very possible that a piece of content like what you have configured above would be ignored as not valuable.
You can read more about the Branch App Indexing implementation on this documentation page


text:
Q: Enroll/Authenticate with FACEIO is always failing on enable `Prevent Face Spoofing Attempts (Presentation Attacks) During Authentication & Enrollment` I am using FACEIO service for enrolling and authenticating users. And enabled : Prevent Face Spoofing Attempts (Presentation Attacks) During Authentication & Enrolment.
When I am trying to detect and prevent the face spoofing by enabling the Prevent Face Spoofing Attempts (Presentation Attacks) During Authentication & Enrolment in dashboard, the authentication is always getting failed in order to prevent face spoofing.
Are there any possible solutions to get it worked ?


text:
Q: SyntaxError: Unexpected number in JSON at position 107 I am trying to learn how to deploy a code on Ropsten network which worked fine on ganache but it keeps throwing an error and I am not able to figure it out. Below is the code
const fs = require('fs');
const HDWalletProvider = require("@truffle/hdwallet-provider");

const gitignore = JSON.parse (
    fs.readFileSync('.gitignore').toString().trim()
);

module.exports = {
    networks: {
        ropsten: {
            provider: () =>
                new HDWalletProvider(
                    gitignore.seed,
                    'https://ropsten.infura.io/v3/${gitignore.projectID}'
                ),
            network_id: 3
        }
    }
};

below are the dependency version
Truffle v5.3.9 (core: 5.3.9)
Node v14.17.0
@truffle/hdwallet-provider: "^1.4.1"


text:
Q: Fatal Exception Main on a null object reference I have an error when I click to see the details of some of my pokemon. He is getting null reference, but I don't know how to solve it so as not to crash. Can someone help me?
Log Error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pokedex, PID: 28852
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object
java.util.List.get(int)' on a null object reference
    at

  com.example.pokedex.ui.detalhesPokemons.
  DetalhesPokemonsFragment$configDetalhes$$inlined$observe$1.onChan
  ged(LiveData.kt:58)
    at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
    at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:151)
    at androidx.lifecycle.LiveData.setValue(LiveData.java:309)
    at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
    at
 com.example.pokedex.ui.detalhesPokemons.DetalhesPokemonsViewModel$getDetalhes$1.
 invokeSuspend(DetalhesPokemonsViewModel.kt:20)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

class DetalhesFragmentPokemon

     private val detalhesViewModel: DetalhesPokemonsViewModel by viewModels{
        DetalhesPokemonsViewModelFactory((activity?.application as MyApplication).repository)
    }
    private val argumentos by navArgs<DetalhesPokemonsFragmentArgs>()
    private val pokemon by lazy { argumentos.pokemon }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
         ): View? {
        return inflater.inflate(
            R.layout.detalhes_pokemon,
            container,
            false
        )

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        configDetalhes()
    }

    private fun configDetalhes() {
       detalhesViewModel.getDetalhes(pokemon.id)
        detalhesViewModel.mResponse.observe(viewLifecycleOwner, {
            if (it.isSuccessful) {
                tv_detalhes_nome_pokemon.text = pokemon.nome
                tv_detalhes_habilidades_pokemon.text = pokemon.abilities[0].name
                tv_hp_detalhes_pokemon.text = pokemon.hp

        })
    }

class DetalhesPokemonsViewModel(

    private val repository: PokedexRepository
    ): ViewModel() {
        val mResponse: MutableLiveData<Response<PokemonItem>> =
    MutableLiveData()

        fun getDetalhes(id: String){
            viewModelScope.launch {
                val response = repository.getPokemonsDetalhes(id)
                mResponse.value = response
            }
        }
    }

Can someone help me? I couldn't fix this error, because it only happens in some cases.
I added the DetalhesPokemonViewModel class, which is where I think the problem lies


text:
Q: How to check for internet connection repeatedly? I am building an app using Swift and Parse. In several different View Controllers, I am using Parse to save and view objects. However, if I must have internet connection to access Parse. Currently, I have developed the following method to check for internet:
    let url = NSURL(string: "http://myeighthours.com/")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in

        print(data)
        print(response)
        print(error)

        if let _ = data {

            UIApplication.sharedApplication().endIgnoringInteractionEvents()
            self.activityIndicator.stopAnimating()

            //Success

        } else {

            UIApplication.sharedApplication().endIgnoringInteractionEvents()
            self.activityIndicator.stopAnimating()

            //Failed

        }

    }

    task.resume()

Now this is in a separate View Controller. If I were to continuously check for internet, I would have to use this code in all of my view controllers every time I try to access Parse. This would be very tedious and inefficient. Also, I would have to 1. Create a segue to a separate "No Internet Connection" View Controller, or 2. Add a button to each View Controller saying "No Internet Connection. Tap to retry". If I turn off my internet connection and run the app, it simply stays there loading. I get this error message in my debug log:
2015-12-29 12:43:19.700 MYAPPNAME[975:354550] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:19.700 MYAPPNAME[975:354550] [Error]: Network connection failed. Making attempt 2 after sleeping for 1.958450 seconds.
2015-12-29 12:43:21.854 MYAPPNAME[975:354549] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:21.855 MYAPPNAME[975:354549] [Error]: Network connection failed. Making attempt 3 after sleeping for 3.916899 seconds.
2015-12-29 12:43:26.132 MYAPPNAME[975:354549] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:26.133 MYAPPNAME[975:354549] [Error]: Network connection failed. Making attempt 4 after sleeping for 7.833799 seconds.

What is the most efficient way to repeatedly check for internet connection? Thanks for your help.

A:
Best way to check for internet connection works and tested on Swift 2.0

1) Create a new swift file connection.swift and include this code below
import Foundation

        import SystemConfiguration

        public class Reachability {

            class func isConnectedToNetwork() -> Bool {

                var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
                zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
                zeroAddress.sin_family = sa_family_t(AF_INET)

                let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
                    SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
                }

                var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
                if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
                    return false
                }

                let isReachable = flags == .Reachable
                let needsConnection = flags == .ConnectionRequired

                return isReachable && !needsConnection

            }
        }

You can use this method anywhere

 if Reachability.isConnectedToNetwork() == true {
                println("Internet connection OK")
            } else {
                println("Internet connection FAILED")
            }
            If the user is not connected to the internet, you may want to show them an alert dialog to notify them.
            if Reachability.isConnectedToNetwork() == true {
                println("Internet connection OK")
            } else {
                println("Internet connection FAILED")
                var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
                alert.show()
        }

Took idea from

https://github.com/Isuru-Nanayakkara/Reach

A: #import <SystemConfiguration/SCNetworkReachability.h>

call isNetworkReachable method by NSTimer once you detect that Internet is not reachable to continuously check connectivity... timer repeat duration should be 2-3 second.Also your NStimer instance should be global not in every view controller
+(BOOL)isNetworkReachable
{
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityRef address;
    address = SCNetworkReachabilityCreateWithName(NULL, "www.google.com" );
    Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
    CFRelease(address);

    bool canReach = success
    && !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
    && (flags & kSCNetworkReachabilityFlagsReachable);

    return canReach;
}


text:
Q: import old data from postgres to elasticsearch I have a lot of data in my postgres database( on a remote). This is the data of the past 1 year, and I want to push it to elasticsearch now.
The data has a time field in it in this format 2016-09-07 19:26:36.817039+00.
I want this to be the timefield(@timestamp) in elasticsearch. So that I can view it in kibana, and see some visualizations over the last year.
I need help on how do I push all this data efficiently. I cannot get that how do I get all this data from postgres.
I know we can inject data via jdbc plugin, but I think I cannot create my  @timestamp field with that.
I also know about zombodb but not sure if that also gives me feature to give my own timefield.
Also, the data is in bulk, so I am looking for an efficient solution
I need help on how I can do this. So, suggestions are welcome.

A:
I know we can inject data via jdbc plugin, but I think I cannot create
  my  @timestamp field with that.

This should be doable with Logstash. The first starting point should probably be this blog post. And remember that Logstash always consists of 3 parts:

*

*Input: JDBC input. If you only need to import once, skip the schedule otherwise set the right timing in cron syntax.

*Filter: This one is not part of the blog post. You will need to use the Date filter to set the right @timestamp value — adding an example at the end.

*Output: This is simply the Elasticsearch output.

This will depend on the format and field name of the timestamp value in PostgreSQL, but the filter part should look something like this:
date {
   match => ["your_date_field", "dd-mm-YYYY HH:mm:ss"]
   remove_field => "your_date_field" # Remove now redundant field, since we're storing it in @timestamp (the default target of date)
}

If you're concerned with the performance:

*

*You will need to set the right jdbc_fetch_size.

*Elasticsearch output is batched by default.


text:
Q: pytest comparing two lists containing dictionaries, by content I have the following structure for illustration:
list1 = [{'dict1':1}, {'dict2':2}]
 list2 = [{'dict2':2}, {'dict1':1}]
Now I as you see both lists are the same in content,
but list1 == list2 produce False.
I have a test using pytest which one of its lines is:
assert list1 == list2
I want the ability to return True (content check), and if there are differences to show them them using pytest in a similar way it would be raised when doing something like:
assert 'hi1'=='hi2'
Any idea will be appreciated


text:
Q: Появляется ошибка System.FormatException: "Input string was not in a correct format."

Помогите разобраться с ошибкой, попытки TryParse не увенчались успехом(((
class Program
    {
        const string data_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        static void Main(string[] args)
        {
            var client = new HttpClient();
            var csv_str = client.GetAsync(data_url).Result;

            //foreach (var data_line in GetDataLines())
            //    Console.WriteLine(data_line);

            //var dates = GetDates();
            //Console.WriteLine(string.Join("\r\n", dates));

            var russia_data = GetData()
                        .First(v => v.Country.Equals("Russia", StringComparison.OrdinalIgnoreCase));

            Console.WriteLine(string.Join("\r\n", GetDates().Zip(russia_data.Counts, (date, count) => $"{date:dd:MM} - {count}")));

            Console.ReadLine();
        }
        //
        private static async Task<Stream> GetDataStream()
        {
            var client = new HttpClient();
            var response = await client.GetAsync(data_url, HttpCompletionOption.ResponseHeadersRead);
            return await response.Content.ReadAsStreamAsync();
        }
        //
        private static IEnumerable<string> GetDataLines()
        {
            using var data_stream = GetDataStream().Result;
            using var data_reader = new StreamReader(data_stream);
            while (!data_reader.EndOfStream)
            {
                var line = data_reader.ReadLine();
                if (string.IsNullOrWhiteSpace(line))
                    continue;
                yield return line.Replace("Korea,", "Korea -"); // тут происходит замена
            }
        }
        //Метод который получает все даты
        private static DateTime[] GetDates() => GetDataLines()
            .First()
            .Split(',')
            .Skip(4)
            .Select(s => DateTime.Parse(s, CultureInfo.InvariantCulture))
            .ToArray();
        //
        private static IEnumerable<(string Country, string Province, int[] Counts)> GetData()
        {
            var lines = GetDataLines()
                .Skip(1)
                .Select(line => line.Split(','));
            foreach (var row in lines)
            {
                var province = row[0].Trim(); // Trim - обрезает всё лишнее в строке (пробелы, спецсимволы)
                var country_name = row[1].Trim(' ', '"');
                var counts = row.Skip(4).Select(int.Parse).ToArray(); // ошибка
                yield return (country_name, province, counts);
            }
        }
    }

A: Skip(4) => Skip(5)
private static IEnumerable<(string Country, string Province, int[] Counts)> GetData()
        {
            var lines = GetDataLines()
                .Skip(1)
                .Select(line => line.Split(','));
            foreach (var row in lines)
            {
                var province = row[0].Trim(); // Trim - обрезает всё лишнее в строке (пробелы, спецсимволы)
                var country_name = row[1].Trim(' ', '"');
                var counts = row.Skip(5).Select(int.Parse).ToArray(); // Верно!
                yield return (country_name, province, counts);
            }
        }


text:
Q: Pushing the ViewController in customize Tableview Cell I'm using Using Customize table cell and have a button action in that cell and tapping on that should take me to another ViewController, I'm using this code inside the button action  but its not working out:
 PhotoViewController *photo = [[PhotoViewController alloc]initWithNibName:@"PhotoViewController" bundle:nil];
  [self.navigationController pushViewController:photo animated:YES];

A: Got the solution :-) thanks Created the IBOutlet and in cellForRowAtIndexPath method declared:
 cell.photoAlbum.tag = indexPath.row; [cell.photoAlbum addTarget:self
action:@selector(photoAblumClicked:) forControlEvents:UIControlEventTouchUpInside];

and in the photoAblumClicked called the above code it's working fine Thanks :-)

A:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *tableIdentifier = @"StaticTableViewCell";
   StaticTableViewCell *cell = (FriendTableViewCell *)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];

if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StaticTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}
    cell.button.tag = indexPath.row;
    [cell.button addTarget:self action:@selector(PhotoAlb:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

-(void)PhotoAlb:(id)sender
{
    PhotoViewController *photo = [[PhotoViewController alloc]initWithNibName:@"PhotoViewController" bundle:nil];
    [self.navigationController pushViewController:photo animated:YES];
}


text:
Q: Porque al usar serialize se muestra así {i:0;s:2:"37";i:1;s:2:"36";}] en mi index.php? Buenas actualmente me encuentro realizando un proyecto y necesito crear un sistema de categorías/tags por publicación. Conseguí que funcionase usando el método de Serialize pero me gustaría que se mostraran las categorías seleccionadas en las publicaciones de mi blog, porque al ingresar
<?php echo $post['topic_id']?>
 me aparece lo siguiente en la web: a:2:{i:0;s:2:"37";i:1;s:2:"36";}
Me dijeron que use Unserialize pero no entiendo muy bien donde agregarlo.
¿Usar este método para crear las categorías es confiable?
Ayuda por favor!.
código: topics.php
if (isset($_POST['add-post'])) {
    $_POST['topic_id']=serialize($_POST['topic_id']);
    $errors = validatePost($_POST);

    if (!empty($_FILES['image']['name'])) {
        $image_name = time() . '_' . $_FILES['image']['name'];
        $destination = "../../images/" . $image_name;

        $result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);

        if ($result){
            $_POST['image'] = $image_name;
        } else {
            array_push($errors, "¡Algo fallo al subir la imagen!");
        }

    } else {
      array_push($errors, "¡Necesitas subir una imagen!");
    }

    if (count($errors) === 0){
        unset($_POST['add-post']);
        $post_id = create($table, $_POST);
        $_SESSION['message'] = '¡Post creado correctamente!';
        $_SESSION['type'] = 'success';
        header('location: ../../admin/posts/index.php');
        exit();
    } else {
        $title = $_POST['title'];
        $body = $_POST['body'];
        $topic = $_POST['topic_id']; // array('test','test2')
    }
}

if (isset($_GET['id'])){
    $id = $_GET['id'];
    $post = selectOne($table, ['id' => $id]);
    $id = $post['id'];
    $title = $post['title'];
    $body = $post['body'];
    $topic = $post['topic_id'];
}

if (isset($_GET['del_id'])){
    $id = $_GET['del_id'];
    $count = delete($table, $id);
    $_SESSION['message'] = '¡Post eliminado correctamente!';
    $_SESSION['type'] = 'success';
    header('location: ../../admin/posts/index.php');
    exit();
}

if (isset($_POST['update-post'])){
    $_POST['topic_id']=serialize(array_values($_POST['topic_id']));
    $errors = validateEdit($_POST);

    if (count($errors) === 0){
        $id = $_POST['id'];
        unset($_POST['update-post'], $_POST['id']);
        $post_id = update($table, $id, $_POST);
        $_SESSION['message'] = '¡Post actualizado correctamente!';
        $_SESSION['type'] = 'success';
        header('location: ../../admin/topics/index.php');
        exit();
    } else {
        $id = $_POST['id'];
        $title = $_POST['title'];
        $body = $_POST['body'];
        $topic = $_POST['topic_id'];
}
}
?>

imágenes:

A:
¿Por qué al usar serialize se muestra así {i:0;s:2:"37";i:1;s:2:"36";}]?

La respuesta a esa pregunta específica es:
a:2:{i:0;s:2:"37";i:1;s:2:"36";}

*

*a:2 quiere decir que se trata de un arreglo con dos elementos

*i:0;s:2:"37" Quiere decir que el primer elemento tiene índice entero (i) con valor cero y el contenido es una cadena (s) de 2 caracteres de longitud y valor "37"

*i:1;s:2:"36" Quiere decir que el segundo elemento tiene índice entero (i) con valor 1 y el contenido es una cadena (s) de 2 caracteres de longitud y valor "36"

En resumen, cuando aplicas unserialize() obtienes un arreglo:
["37", "36"]

Para mostrar las categorías, lo ideal sería que tengas un arreglo asociativo id_categoria => 'nombre_categoria' y solo recorres:
<?php
$topics = [
    36 => 'Test1',
    37 => 'Test2',
];

?>

<?php
// Obtener arreglo de categorías
$categorias = unserialize($_POST['topic_id']);
// Recorrer arreglo para mostrar cada una
foreach($categorias as $cat) {
   echo $topics[$cat];
}
?>

¿Usar este método para crear las categorías es confiable?

La respuesta a esto es meramente basada en opiniones y aquí va la mía: Es tan confiable como puedas y sepas manejarlo, por ejemplo: debes considerar cómo mantener consistencia en el catálogo de categorías, si se elimina una, tienes que verificar que no esté siendo usada en alguna publicación.
Habrá quienes te digan que debes crear una tabla aparte para establecer las relaciones y, probablemente, sea lo más adecuado para programar siempre basado en buenas prácticas.


text:
Q: Error (E_VALIDATION) :: 1 attribute is invalid I'm trying to update one line using sails-orientdb, this way:
      CommentModel.update({
        _id: req.body.reply.commentId
      }, comment).exec(function (err, reply) {
        // *** LOG: LOOK BELOW
        console.log(comment, req.body.reply.commentId, reply);
        // ***
        if (err)
          return next(err);
        UserModel.findOne({
          id: reply.author
        }).exec(function (err, user) {
          reply.author = user.toJSON();
          res.json({
            success: !err,
            reply: reply
          });
        });
      });

comment: { author: '#16:0',   node: '#30:13',   _id: '0dcb0fb8-35e9-4117-87e9-33e2ac21e0e0',   body: 'lkjnn',   replies: '[object Object]',   createdAt: '2015-07-21T08:50:52.000Z',   updatedAt: '2015-07-21T08:50:52.000Z',   id: null }
req.body.reply.commentId: 0dcb0fb8-35e9-4117-87e9-33e2ac21e0e0
reply: undefined

But, I'm getting this error message:

Error (E_VALIDATION) :: 1 attribute is invalid

How to fix this, please? What's wrong?


text:
Q: Big O definition and showing equality On this problem, I'm not sure what Big O definition they are referring. How would the big o definition help show this?
Use the definition of $O$ to show that if $y = y_h + O(h^p)$, then $hy = hy_h + O(h^{p+1})$.

A: The first statement is saying, taking big O as $x$ approaches some $a$ for some $M>0$
$$
|y-y_h|<M|h^p|\implies \frac{|y-y_h|}{|h^p|}<M
$$
for any $|x-a|<\delta$ for some $\delta>0$.
Now what happens if you multiply the LHS by $\frac{|h|}{|h|}=1$?


text:
Q: Picasa-like image viewer for Ubuntu (to flip quickly through large numbers of images) I am looking for an image viewer that allows me to flip through a huge number of images (~10000 images) very quickly so that minute changes are visible. I need this for image classification and testing. Picasa allows me to do it perfectly with easy back and forth switching so that I can identify changes in illumination, small movements, and large movements. Making it into a movie using ffmpeg is not an option as I require the individual images.
For example, say I observed between images 24 and 25 there is an Illumination change and I want to experiment on those two frames.
The problem with the existing image viewers in Ubuntu is that they are very slow compared to Picasa while moving back and forth and hence is inconvenient. Also, I noticed a tendency that after 10.jpeg, the default image viewer in Ubuntu switches to 11000.jpeg. And before 10.jpeg, it passes like 10999 -> 1099 -> 10.
Is there any such image viewer which works like Picasa? Like really smooth while moving between pictures and also in order. Please note that I do not intend to edit any of the images only move through them very fast or at least fast enough.

A: You can install Googles Picasa in Ubuntu by wine. HQ here


text:
Q: Simplification of a double summation in a polynomial ring over a finite field I am looking out to simplify the following double summation in $\mathbb{F}_q[x_1,x_2]$, where $p$ is a prime and $q=p^k$ for some positive integer $k$ and a positive integer $r$ such that $0 \leq r \leq q-2$:
$\sum\limits_{i=0}^{q-2} \sum\limits_{j=0}^r {(q-i)(q-1) \choose j}x_1^{(q-i+j)(q-1)} {(i+2)(q-1) \choose r-j} x_2^{(i+2+r-j)(q-1)}$
(Assume that the sum is taken over only those terms where the binomial coefficients make sense)
This sum arose during my study of invariant theory, on the application of Steenrod operations to certain polynomials in $\mathbb{F}_q[x_1,x_2]$ (you can comment if you want more details). I expect the sum to be a non-zero scalar multiple of the following sum:
$\sum\limits_{i=0}^{q-r-2}x_1^{(q-i)(q-1)}x_2^{(i+r+2)(q-1)}$
I tried changing the order of summation and some changes of variables which didn't turn out to be very helpful.
Any help regarding any techniques that could be used here or references to books/results that could be used for the simplification will be appreciated. Thanks in advance!

A: In order to prove this identity, we first transform it to a simpler form. Firstly, cancel $x_1^{q(q-1)}x_2^{(r+2)(q-1)}$ from both sides. Next, replace $x_1^{q-1}$ and $x_2^{q-1}$ by $z_1$ and $z_2$ respectively, and next, replace $z_2/z_1$ by $z$. Thus, the identity to be proven transforms into:
\begin{equation}
\sum\limits_{i=0}^{q-2}\sum\limits_{j=0}^r {(q-i)(q-1) \choose j}{(i+2)(q-1) \choose r-j} z^{i-j} = {q-1 \choose q-r-1}\sum \limits_{i=0}^{q-r-2} z^{i}
\end{equation}
Now, as we are in $\mathbb{F}_q$, we have ${(q-i)(q-1) \choose j} = {i \choose j}$ and ${(i+2)(q-1) \choose r-j} = {q-i-2 \choose r-j}$ by Lucas' Theorem. Finally, putting $k=i-j$ and suitably modifying the limits for summation, we get:
\begin{equation}
\sum\limits_{i=0}^{q-2}\sum\limits_{k=i-r}^i {i \choose k}{q-i-2 \choose q-2-r-k} z^k = {q-1 \choose q-r-1}\sum \limits_{k=0}^{q-r-2} z^k
\end{equation}
Next, we notice that for $k>i$ and for $k<i-r$, the summand on the LHS becomes 0. So, we can sum over $k$ from $0$ to $q-2$. Then, the coefficient of $z^k$ on the LHS becomes equal to $\sum\limits_{i=0}^{q-2} {i \choose k}{q-i-2 \choose q-2-r-k}$. (For $k>q-2-r$, this is zero exactly as in the RHS). This is the coefficient of $a^kb^{q-2-r-k}$ in:
\begin{align*}
\sum\limits_{i=0}^{q-2} (1+a)^i(1+b)^{q-i-2} &= (1+a)^{q-2} \sum\limits_{i=0}^{q-2} \bigg(\frac{1+b}{1+a} \bigg)^{q-i-2}
\\&=(1+a)^{q-2} \frac{1-\bigg(\frac{1+b}{1+a}\bigg)^{q-1}}{1-\frac{1+b}{1+a}}
\\&=\frac{(1+a)^{q-1} - (1+b)^{q-1}}{a-b}
\\&=\frac{\sum\limits_{i=0}^{q-1}{q-1 \choose i}(a^i-b^i)}{a-b}
\\&=\sum\limits_{i=0}^{q-1} {q-1 \choose i} \sum\limits_{j=0}^{i-1}a^jb^{i-j-1}
\end{align*}
The coefficient of $a^kb^{q-2-r-k}$ in the above expression is exactly ${q-1 \choose q-r-1}$ which is exactly the coefficient of $z^k$ in the RHS of the identity we are trying to prove. Hence the two expressions are equal in $\mathbb{F}_q[x_1,x_2]$.