text:
Q: Select Data At every 3 minutes from starting timestamp I want to select data from table at every 3 minutes interval from the starting timestamp using postgresql.
31-12-2015 10:00:00
31-12-2015 10:01:00
31-12-2015 10:02:00
31-12-2015 10:03:00
31-12-2015 10:04:00
31-12-2015 10:05:00

Required Output is
31-12-2015 10:00:00
31-12-2015 10:03:00

A: With sample table
CREATE TABLE tm (tme TIMESTAMP);

INSERT INTO tm
VALUES ('31-12-2015 10:00:00')
    ,('31-12-2015 10:01:00')
    ,('31-12-2015 10:02:00')
    ,('31-12-2015 10:03:00')
    ,('31-12-2015 10:04:00')
    ,('31-12-2015 10:05:00');

and the select should be
SELECT *
FROM tm
WHERE to_char(tme, 'MI')::INT IN (
        SELECT *
        FROM (
            SELECT to_char(tme, 'MI')::INT col
            FROM tm
            ) t
        WHERE mod(col, 3) = 0
        );

Simplified
select *
from
tm where mod(to_char(tme, 'MI')::int,3)=0

result:
tme
-------------------
2015-12-31 10:00:00
2015-12-31 10:03:00

DEMO


text:
Q: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established im trying to make a socket server so i can receive messages from a client.py on a diffrent network
this is my code for server.py

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 8080))
s.listen(5)

while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} has been established.")
    clientsocket.send(bytes("Hey there!!!","utf-8"))

and this is client.py

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.13', 8080))

while True:
    full_msg = ''
    while True:
        msg = s.recv(8)
        if len(msg) <= 0:
            break
        full_msg += msg.decode("utf-8")

    if len(full_msg) > 0:
        print(full_msg)

this is the full error message
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appending string to input file name in c I need to write a program using system calls to read a file, reverse the string and print it out to an output file. If the input file is test.txt, output should be written to file reverse_test.txt. Please let me know how I can append the string reverse_ to the name of the output file where I would be writing the results.
I tried the code below but it gives error.
strcat("reverse_",argv[1]);

I have written the rest of the code and it works fine but unable to solve this part.

A: You can't append to the literal "reverse_". Try something like this:
char str[ENOUGH] = {0};
snprintf(str, sizeof(str), "reverse_%s", argv[1]);

A: in your example "reverse_" is a string constant literal and you are attempting to append some other memory locations to the constant literal, which is not possible.
You can do the following:
 char *buffer;

 buffer = malloc (sizeof (char) * BUFSIZ);

 strcpy (buffer, "reverse_");
 strcat (buffer, argv[1]);

 /* Work here */

 free (buffer); /* before termination */

Or you can also define the buffer as a static array with BUFSIZ length.

A: The strcat() standard library function accepts two parameters: the destination and the source string.
This means that, when you try something like this:
strcat( "reverse_", argv[1] );

You're actually saying something like this:
"reverse_" = "reverse_" + argv[ 1 ]

..which is incorrect, since you cannot modify (or, at least, you shouldn't) the literal "reverse_". It is certain that you won't be able to change its length, since in the process you'd be breaking other literals of use in your code.
@cnicutar has given you a hint about how to achieve the result you are seeking, but in case you would like to adhere to the process you were following, here is the explanation:
a) You need to reserve a place in memory in which you will store the reversed file name.
b) You need to write "reverse_" there.
c) Finally, you need to concat the file name in argv[ 1 ]
The first step is shockingly the most difficult one. How much space is needed? A given file name can be of a maximum of 255 characters:
http://en.wikipedia.org/wiki/NTFS
http://en.wikipedia.org/wiki/Ext4
...however, nothing stops the user of entering an absolute or relative path. This means that probably we should give the maximum character length that the command line can handle, which is...
http://support.microsoft.com/kb/830473
¡8192 characters!... this is leading us nowhere.
A much better method, leading to best accuracy, is to count the number of characters in the argv[ 1 ] string, then add the characters needed for the prefix, and reserve that amount plus one, since we need to also store the mark for the end of string:
const char * prefix = "reserve_";
int needed = strlen( argv[ 1 ] ) + strlen( prefix ) + 1;

char store[ needed ];

strcpy( store, prefix );                    // store <- prefix
strcat( store, argv[ 1 ] );                 // store <- store + argv[ 1 ]

printf( "%s\n", store );

In case you cannot use these kind of vectors, you should reserve and use dynamic memory.
const char * prefix = "reserve_";
int needed = strlen( argv[ 1 ] ) + strlen( prefix ) + 1;

char * store = (char *) malloc( sizeof( char ) * needed );

strcpy( store, prefix );                    // store <- prefix
strcat( store, argv[ 1 ] );                 // store <- store + argv[ 1 ]

printf( "%s\n", store );
free( store );

Hope this helps.


text:
Q: Error while writing to array plsql how to fix? Extend doesn't work also so I am trying to write to an array in PL/SQL, and I always get the subscript outside of limit error. I've seen similar posts and implemented everything based on those answers, I can't seem to find what I'm doing wrong. The line giving the error is "arr_quartosLivres(counter) := q.id;" I've tried to extend the array and it still doesn't work, however, either way, the look only runs 21 times (because there are only 21 values in the table quarto) so it shouldn't even need to be extended. Any help would be highly appreciated! Thank you
SET SERVEROUTPUT ON;

DECLARE
    p_idReserva reserva.id%type := 408;
    v_dataEntradaReserva reserva.data_entrada%type;
    counter integer := 0;

    type arr_aux IS varray(21) of quarto.id%type;
    arr_quartosLivres arr_aux := arr_aux();

BEGIN
    SELECT data_entrada INTO v_dataEntradaReserva FROM reserva WHERE id = p_idreserva;

    FOR q IN (SELECT * FROM quarto)
    LOOP
        BEGIN
            IF isQuartoIndisponivel(q.id, v_dataEntradaReserva)
            THEN    DBMS_OUTPUT.PUT_LINE('nao disponivel' || counter);
                arr_quartosLivres(counter) := q.id;
            ELSE DBMS_OUTPUT.PUT_LINE('disponivel' || counter);
            END IF;
            counter := counter + 1;
        END;
    END LOOP;
END;

A: The index values for varray begin with 1. Your logic is trying to use index value 0. Thus index out of range. BTW extend does not apply to varray, when declared a varray has a fixed size. You have 3 solutions: initialize counter to 1 instead of 0, or move incrementing it prior to its use as an index. Since as it stands you increment every time through the loop, even when the IF condition returns false and you do not use the counter as an index, leaving a NULL value in the array.But you use counter for 2 different purposes: Counting rows processed and index into the array. Since the row value may not be put into the array then your 3rd option is to introduce another variable for the index. Further there is no need for the BEGIN ... End block in the loop.
declare
    p_idreserva reserva.id%type := 408;
    v_dataentradareserva reserva.data_entrada%type;
    counter integer := 0;

    type arr_aux is varray(21) of quarto.id%type;
    arr_quartoslivres arr_aux := arr_aux();
    varray_index integer := 1 ; -- index varaibal for varray.
begin
    select data_entrada into v_dataentradareserva from reserva where id = p_idreserva;

    for q in (select * from quarto)
    loop
         if isquartoindisponivel(q.id, v_dataentradareserva)
         then
             dbms_output.put_line('nao disponivel' || counter || ' at index ' || varray_index);
             arr_quartoslivres(varray_index) := q.id;
             varray_index :=  varray_index + 1;
         else
            dbms_output.put_line('disponivel' || counter);
         end if;
         counter := counter + 1;
    end loop;
end;


text:
Q: java web server and js client - cors problems I build a web server in java (simple one) and a client in js
but when i try to send req its not get the json data the over in the body
may someone know what the problem?
I tried mode: cors / no cors,
I assume that problem is cors problem,
if I set mode: no-cors its work one way (no getting response)
and mode cors not work at all
The java server and it's handler:
public class server implements Runnable {

    public static void main(String[] args) {
        Runnable runnable  = new server();
        Thread thread = new Thread(runnable);
        thread.start();
    }

    @Override
    public void run() {
        HttpServer server = null;
        try {
            server = HttpServer.create(new InetSocketAddress(3000), 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        server.createContext("/getMaze/prim", new PrimHandler());
        server.createContext("/getMaze/kruskal", new PrimHandler());
        server.createContext("/solveMaze/AStar", new AStarHandler());
        server.createContext("/solveMaze/DFS", new DfsHandler());
        server.createContext("/solveMaze/BFS", new BfsHandler());
        server.setExecutor(null); // creates a default executor
        server.start();

    }

}

    public void handle(HttpExchange he) throws IOException {
        // parse request
        he.getResponseHeaders().add("Access-Control-Allow-Origin","*");
        he.getResponseHeaders().add("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization");
        he.getResponseHeaders().add("Access-Control-Allow-Methods","PUT, POST, GET,PATCH, DELETE");
        InputStreamReader isr = new InputStreamReader(he.getRequestBody(), "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String query = br.readLine();
        String response = jsonQuery(query);
        he.sendResponseHeaders(200, response.length());
        OutputStream os = he.getResponseBody();
        os.write(response.toString().getBytes());
        os.close();
    }

here is the js client request
await fetch('http://localhost:3000/'+url, {
        mode:'cors',
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            "Access-Control-Allow-Origin":"*",
            "Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization",
            "Access-Control-Allow-Methods":"PUT, POST, GET,PATCH, DELETE",
        },
        body: JSON.stringify(jsonObj),
        }).then(response => {
            console.log(response.json);
        return response;
        }).then(jsonResponse => {
        console.log(jsonResponse);
        }).catch (error => {
        console.log(error)
        });


text:
Q: Spring Boot JPA Query modify dynamically Using Spring boot,I am working on one business use case where i need to modify the JPA query generated at runtime based on configuration.
For Example .. if query that JPA generates is
select * from customers where id=1234

I want to modify it in runtime like based on user's logged in context. (Context has one attribute business unit) like given below ..
select * from customers where id=1234 and ***business_unit='BU001'***

Due to certain business use case restrictions i can't have statically typed query.
Using Spring boot and Postgres SQL.

A: Try JPA criteria builder , it let you to create dynamics query programmatically.
Take look in this post

A: What is stopping you to extract the business unit from the context and pass it to the query?
If you have this Entity
@Entity
CustomerEntity {
  Long id;
  String businessUnit;
  //geters + setters
}

you can add this query to your JPA Repository interface:
CustomerEntity findByIdAndBusinessUnit(Long id, String businessUnit)

This will generate the following "where" clause:
… where x.id=?1 and x.businessUnit=?2

for complete documentation check Spring Data Jpa Query creation guide.

A: you would do something like this, this lets you dynamically define additional predicates you need in your query. if you don't want to have all the conditions in your query with @Query
The below example just adds a single predicate.
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import study.spring.data.jpa.models.TicketPrice;

@Component
public class TricketPriceCriteriaRepository {
    @Autowired
    TicketPriceJpaRepository ticketPriceJpaRepository;

    public List<TicketPrice> findByCriteria(int price) {
        return ticketPriceJpaRepository.findAll(new Specification<TicketPrice>() {
            @Override
            public Predicate toPredicate(Root<TicketPrice> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (price > 0) {
                    predicates.add(
                            criteriaBuilder.and(criteriaBuilder.greaterThan(root.get("basePrice"), price)));
                }
                // Add other predicates here based on your inputs
                // Your session based predicate
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        });
    }
}

Your base repository would be like
// Other imports
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface TicketPriceJpaRepository
        extends JpaRepository<TicketPrice, Long>, JpaSpecificationExecutor<TicketPrice> {}

the model consists basePrice
@Column(name = "base_price")
private BigDecimal basePrice;


text:
Q: PrimeFaces custom menu icon not rendered I'm on a process of developing a JSF application which uses PrimeFaces component library as well. I wanted to apply some menubar component in my application; however, the icon that I created couldn't get rendered. In PrimeFaces documentation, it is stated that for custom icon I should have a css class. I created the css with an image and feed it to the menubar icon attribute but it didn't work. The following is my css.
.mainPageIcon {
    background: url(/images/motorStop.png) no-repeat;
    height: 16px;
    width: 16px;
}

<p:menubar>
     <p:menuitem icon="mainPageIcon" value="mainPage"/>
</p:menubar>

What should I do for the matter?

A: In Primefaces, to use a CSS class, you use the attribute styleClass.
It is equivalent to class in Html.
So,
 <p:menuitem styleClass="mainPageIcon" value="mainPage"/>


text:
Q: Make objects inside a group collide with themselves in Phaser.io? This question is regarding phaser.io. Can someone show me how to make objects inside a group collide with each other.
Right now when i do,
//board is the group and it has many elements
//Floor is where all the elements fall to
game.physics.arcade.collide(this.board, this.floor);

All the elements inside the group stack on top of each other when they hit the floor at the same position. In other words the stack builds at one position, the latest one hiding the previous element and not upwards in the sense one on top of another at a higher position. How can i make the stack build upwards? If you could just show me how to make elements inside a group collide would be great. Thanks.

A: You can collide a Group with itself:
game.physics.arcade.collide(this.board, this.board);
Although on that note I would point you at this tutorial on adding a simple 1d sort array, which will help considerably if the Group is densely populated: http://ra3s.com/wordpress/dysfunctional-programming/pruning-collision-detection-with-a-1d-sort/

A: Just to update accepted answer..
In phaserjs version 3.55.2 following code should be used:
game.physics.world.addCollider(this.board, this.board);


text:
Q: Pandas Json : "TypeError: to_json() got an unexpected keyword argument 'indent' " Using this simple piece of code, i'm getting an error.
import json
import pandas as pd
df = pd.DataFrame(
    [["a", "b"], ["c", "d"]],
    index=["row 1", "row 2"],
    columns=["col 1", "col 2"],
)

result = df.to_json(orient="split",indent=None)

I am getting this error :
"TypeError: to_json() got an unexpected keyword argument 'indent' "
But in the documentation, it seems pretty clear that it is one of the parameter possible.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html
Do you know what is happening here? Or i don't know how to read documentation. Thank you!


text:
Q: Google API 3 expires after some time I'm using Gmap3-Jquery plugin to generate Google maps in one of my web application.
Currently i downloaded the Google API  to my local drive and using the same in my HTML page.
However all the actions working fine for me, but after 3-4 days Google API stops working. If i download the fresh Google API from the same link to my local drive everything works fine. What may be the cause for such problem? Is it because of API Key? or is it because i downloaded to my local drive and referencing it from locally?
But I'm downloading Google maps API3, which doesn't require API key.
Here is the code:

A: Are you saving the following file to your hard drive/web app:

http://maps.google.com/maps/api/js?sensor=false

If so, then the answer to your question...

or is it because i downloaded to my local drive and referencing it
  from locally?

...is Yes.
That file you are referencing is cached, so it is always changing. I've never used the jQuery maps plugin that you mentioned above (it looks really cool, though!), but in looking at their API it mentions that you should call that script from Google, and not store it directly.
Also, remember, let Google handle that JS load and bandwidth for you, and try to stay away from storing that locally. The API could change, and with your cached version, your map might break because it's not loading the most recent version.
I'll also add one more thing: let Google load your jQuery, too - people using the site will have a better experience. This article will explain why more.


text:
Q: Laravel 5.5 Add validation for multiple attributes I have a form that has firstname, middlename and lastname fields. I wanted to validate all three of them so that there will be no identical employee with that record. If it has identical user I wanted it to throw an error into the MessageBag.

A: You'll want to use the unique validation provided by Laravel's validation component, you can also put this code inside your FormRequest, instead of this.

unique:[table_name],[column_name]

$validator = Validator::make($request->all(), [
    'first_name' => 'unique:employees,first_name',
    'middle_name' => 'unique:employees,middle_name',
    'last_name' => 'unique:employees,last_name'
]);

To get the error bag, just use the withErrors and pass the $validator.
return redirect('to.where.it.is')->withErrors($validator);


text:
Q: Capybara not loading entries on index page Just getting started with testing so sorry if I'm missing something really obvious.
I'm trying to test that a user is able to edit an entry on an index page using the edit button in a drop down for each entry. Capybara is loading the index page with the headings successfully but isn't displaying the entries for any models I prepare.
I've gone in with pry and found that the records have been created as expected and have the correct ids for each-other, show page was working find in a create. Using factory bot but I did try fixtures, same result.
I've fiddled around with everything I can think of and changing the structure of the tests themselves. Could it be something to do with using bootstrap table or the way I've set up my partials?
#spec/features/crop_spec.rb
it 'user can edit a crop and see their changes' do
    user = create(:user)
    create(:crop, name: 'cartoon foxes', farm: user.farm)
    login_as(user)
    visit crops_path
    expect(page).to have_content('cartoon foxes') #At this point correct page is shown but doesn't contain the prepared crop
    click_button('Options')
    click_on('edit')
    expect(page).to have_content('Update Crop')
  end

#views/crops/index.html.erb

Crops

  <%= link_to "Add", crops_new_url, class: "btn btn-success" %>

      #
      Crop
      Year
      Hectares
      Location

    <%= render 'rows' %>

#views/crops/_rows.html.erb
 <% @crops.each_with_index do |crop, i| %>

      <%= "#{i + 1}" %>
      <%= crop.name %>
      <%= crop.year %>
      <%= crop.hectares %>
      <%= crop.farm.name %>
      <%= render 'shared/model_dropdown', model: crop %>

<% end %>

#views/shared/_model_dropdown.html.erb

  <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" id="option_button">
    Options
  </button>

      <%= link_to 'View', model, class:'dropdown-item' %>

      <%= link_to 'Edit', edit_path(model), class:'dropdown-item' %>

      <%= link_to 'Delete', model, method: :delete, data: {confirm:'Are you sure?'}, class:'dropdown-item' %>

Sorry if this is way too much code, first question here and I've been tinkering with this for way too long, cheers!


text:
Q: Generate individual H5 files for each and every video My code is about to create an H5 file for Each and Every video in the folder, Extracting the feature from the video and stored into the H5 file.
in Below shown code extraction feature from multi videos and all the features are stored in the single H5 file
H5 file order:
video1:
   - feature
video2:
   - feature

issues:

*

*How to create an H5 file for every video after a process is done

Code: Create_data.py
import argparse
from utils.generate_dataset import Generate_Dataset

parser = argparse.ArgumentParser(""Welcome you to fraction)
# Dataset options

parser.add_argument('--input', '--split', type=str, help="input video")
parser.add_argument('--output', type=str, default='', help="out data")

args = parser.parse_args()
if __name__ == "__main__":
    gen = Generate_Dataset(args.input, args.output)
    gen.generate_dataset()
    gen.h5_file.close()

Code: Generate_Dataset.py :
import os
from networks.CNN import ResNet
from utils.KTS.cpd_auto import cpd_auto
from tqdm import tqdm
import math
import cv2
import numpy as np
import h5py
import numpy as np

class Generate_Dataset:
    def __init__(self, video_path, save_path):
        self.resnet = ResNet()
        self.dataset = {}
        self.video_list = []
        self.video_path = ''
        self.h5_file = h5py.File(save_path, 'w')

        self._set_video_list(video_path)

    def _set_video_list(self, video_path):
        # import pdb;pdb.set_trace()
        if os.path.isdir(video_path):
            self.video_path = video_path
            fileExt = r".mp4",".avi"
            self.video_list = [_ for _ in os.listdir(video_path) if _.endswith(fileExt)]
            self.video_list.sort()
        else:
            self.video_path = ''

            self.video_list.append(video_path)

        for idx, file_name in enumerate(self.video_list):
            self.dataset['video_{}'.format(idx+1)] = {}
            self.h5_file.create_group('video_{}'.format(idx+1))

    def _extract_feature(self, frame):
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame = cv2.resize(frame, (224, 224))
        res_pool5 = self.resnet(frame)
        frame_feat = res_pool5.cpu().data.numpy().flatten()

        return frame_feat

    def _get_change_points(self, video_feat, n_frame, fps):
        n = n_frame / fps
        m = int(math.ceil(n/2.0))
        K = np.dot(video_feat, video_feat.T)
        change_points, _ = cpd_auto(K, m, 1)
        change_points = np.concatenate(([0], change_points, [n_frame-1]))

        temp_change_points = []
        for idx in range(len(change_points)-1):
            segment = [change_points[idx], change_points[idx+1]-1]
            if idx == len(change_points)-2:
                segment = [change_points[idx], change_points[idx+1]]

            temp_change_points.append(segment)
        change_points = np.array(list(temp_change_points))

        # temp_n_frame_per_seg = []
        # for change_points_idx in range(len(change_points)):
        #     n_frame = change_points[change_points_idx][1] - change_points[change_points_idx][0]
        #     temp_n_frame_per_seg.append(n_frame)
        # n_frame_per_seg = np.array(list(temp_n_frame_per_seg))
        # print(change_points)
        arr = change_points
        list1 = arr.tolist()
        list2 = list1[-1].pop(1) #pop [-1]value
        print(list2)
        print(list1)

        print("****************") # [-1][-1] value find and divided by 15

        cps_m = math.floor(arr[-1][1]/15)
        list1[-1].append(cps_m)             #append to list
        print(list1)

        print("****************") #list to nd array convertion

        arr = np.asarray(list1)
        print(arr)

        arrmul = arr * 15
        print(arrmul)

        print("****************")
        # print(type(change_points))
        # print(n_frame_per_seg)
        # print(type(n_frame_per_seg))
        median_frame = []
        for x in arrmul:
          print(x)
          med = np.mean(x)
          print(med)
          int_array = med.astype(int)
          median_frame.append(int_array)
        print(median_frame)
        #   print(type(int_array))
        return arrmul

    # TODO : save dataset
    def _save_dataset(self):
        pass

    def generate_dataset(self):
        print('[INFO] CNN processing')
        for video_idx, video_filename in enumerate(self.video_list):
            video_path = video_filename
            if os.path.isdir(self.video_path):
                video_path = os.path.join(self.video_path, video_filename)
            video_basename = os.path.basename(video_path).split('.')[0]
            video_capture = cv2.VideoCapture(video_path)
            fps = video_capture.get(cv2.CAP_PROP_FPS)
            n_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
            frame_list = []
            picks = []
            video_feat = None
            video_feat_for_train = None
            for frame_idx in tqdm(range(n_frames-1)):
                success, frame = video_capture.read()
                if frame_idx % 15 == 0:

                    if success:

                        frame_feat = self._extract_feature(frame)
                        picks.append(frame_idx)

                        if video_feat_for_train is None:
                            video_feat_for_train = frame_feat
                        else:
                            video_feat_for_train = np.vstack((video_feat_for_train, frame_feat))
                        if video_feat is None:
                            video_feat = frame_feat
                        else:
                            video_feat = np.vstack((video_feat, frame_feat))
                    else:
                        break
            video_capture.release()
            arrmul = self._get_change_points(video_feat, n_frames, fps)
            self.h5_file['video_{}'.format(video_idx+1)]['features'] = list(video_feat_for_train)
            self.h5_file['video_{}'.format(video_idx+1)]['picks'] = np.array(list(picks))
            self.h5_file['video_{}'.format(video_idx+1)]['n_frames'] = n_frames
            self.h5_file['video_{}'.format(video_idx+1)]['fps'] = fps
            self.h5_file['video_{}'.format(video_idx + 1)]['video_name'] = video_filename.split('.')[0]
            self.h5_file['video_{}'.format(video_idx+1)]['change_points'] = arrmul

Expected results :
Folder: video
          video_1:
              video1.mp4
              video2.mp4

Files are in this structure, now read video files and create separate H5 files after the process is over.
For more Code reference

A: You need to :

*

*remove self.h5_file = h5py.File(save_path, 'w') from __init__()

*remove self.h5_file.create_group('video_{}'.format(idx+1)) from _set_video_list()

*remove gen.h5_file.close() from main()

*change last block of generate_dataset() into something like:

.
video_capture.release()
arrmul = self._get_change_points(video_feat, n_frames, fps)

h5_dir = os.path.dirname(video_path)
h5_full_path = os.path.join(h5_dir, 'video_{}'.format(video_idx+1))
with h5py.File(h5_full_path, 'w') as h5_file:
   h5_file['features'] = list(video_feat_for_train)
   h5_file['picks'] = np.array(list(picks))
   h5_file['n_frames'] = n_frames
   h5_file['fps'] = fps
   h5_file['video_name'] = video_filename.split('.')[0]
   h5_file['change_points'] = arrmul

Please note that your inner video file indices and actual video file name numbers may not match. So I suggest to change
h5_dir = os.path.dirname(video_path)
h5_full_path = os.path.join(h5_dir, 'video_{}'.format(video_idx+1))

from above into
h5_full_path = video_path.split('.')[0] + '.h5'

This will create features file with the name matched to the video file.


text:
Q: Question about preg_replace I need to do a preg_replace:

and replace it to:

but i'll have alot of:

then i need to do a preg_replace to replace all them.
it's possible do to with preg_replace?
thanks.

A: By default preg_replace will replace all the matches it encounters. You can limit the number by adding a parameter.
preg_replace( '/regex/', 'replaceWith', $string, $noOfMatches );

Hope that answers your question, Good luck.
If you're looking for the regex itself then a quick match to that string would be..
'#
<\/p>#'

I just escaped the special characters. Here is a cheatsheet on regex. If you're parsing HTML a lot, you might want to check into something called DOMDocument in PHP. It lets you manipulate the dom structure and makes the process simple when you learn how to use it.
If you're just starting out I recommend SimpleHTMLDom parser, which comes in a single file to drag onto your server. It's simpler and a good introduction. There are a lot of examples as well. It's maintained here.
Edit: Okay, to get the video id first with regex..
preg_match_all( '#img\.youtube\.com\/vi\/(.*?)\/#', $searchString, $matches );
foreach( $matches[1] as $vid_id )
{
  $iframe_string = '';
  preg_replace( '#
<\/p>#', $iframe_string, $searchString );
}

A: is the expresion

always regular?? you could use a substr to get everything but the video number PZVfZ9TmW6w out

A: Doing this kind of conversion using preg_replace or any RegEx for HTML is just a bad idea.
If you're not so much hung up on the function as the results, you can use phpquery or querypath to get all instances within an HTML page and recurse through to replace whatever's needed.
Probably the best article on StackOverflow IMHO that deals with parsing HTML in PHP is this one:
How to parse HTML with PHP?
It also talks about why and why not to parse HTML using regular expressions. Mostly why not. For myself and a lot of other Developers it has been nothing but a recipe for pain to try to parse HTML (which may have slight differences from link to link or even from line to line) using regular expressions. HTML is just too loose and permissive a markup to have a RegEx that will work 100% of the time.


text:
Q: How to call pypdfocr functions to use them in a python script? Recently I downloaded pypdfocr, however, in the documentation there are no examples of how to call pypdfocr as a library, could anybody help me to call it just to convert a single file?. I just found a terminal command:
$ pypdfocr filename.pdf

A: If you're looking for the source code, it's normally under the directory site-package of your python installation.  What's more, if you're using a IDE (i.e. Pycharm), it would help you find the directory and file.  This is extremly useful to find class as well and show you how you can instantiate it, for example :
https://github.com/virantha/pypdfocr/blob/master/pypdfocr/pypdfocr.py
this file has a pypdfocr class type you can re-use and, possibly, do what a command-line would do.
In that class, the developper has put a lot of argument to be parsed :
def get_options(self, argv):
    """
        Parse the command-line options and set the following object properties:
        :param argv: usually just sys.argv[1:]
        :returns: Nothing
        :ivar debug: Enable logging debug statements
        :ivar verbose: Enable verbose logging
        :ivar enable_filing: Whether to enable post-OCR filing of PDFs
        :ivar pdf_filename: Filename for single conversion mode
        :ivar watch_dir: Directory to watch for files to convert
        :ivar config: Dict of the config file
        :ivar watch: Whether folder watching mode is turned on
        :ivar enable_evernote: Enable filing to evernote
    """
    p = argparse.ArgumentParser(description = "Convert scanned PDFs into their OCR equivalent.  Depends on GhostScript and Tesseract-OCR being installed.",
            epilog = "PyPDFOCR version %s (Copyright 2013 Virantha Ekanayake)" % __version__,
            )

    p.add_argument('-d', '--debug', action='store_true',
        default=False, dest='debug', help='Turn on debugging')

    p.add_argument('-v', '--verbose', action='store_true',
        default=False, dest='verbose', help='Turn on verbose mode')

    p.add_argument('-m', '--mail', action='store_true',
        default=False, dest='mail', help='Send email after conversion')

    p.add_argument('-l', '--lang',
        default='eng', dest='lang', help='Language(default eng)')

    p.add_argument('--preprocess', action='store_true',
            default=False, dest='preprocess', help='Enable preprocessing.  Not really useful now with improved Tesseract 3.04+')

    p.add_argument('--skip-preprocess', action='store_true',
            default=False, dest='skip_preprocess', help='DEPRECATED: always skips now.')

    #---------
    # Single or watch mode
    #--------
    single_or_watch_group = p.add_mutually_exclusive_group(required=True)
    # Positional argument for single file conversion
    single_or_watch_group.add_argument("pdf_filename", nargs="?", help="Scanned pdf file to OCR")
    # Watch directory for watch mode
    single_or_watch_group.add_argument('-w', '--watch',
         dest='watch_dir', help='Watch given directory and run ocr automatically until terminated')

    #-----------
    # Filing options
    #----------
    filing_group = p.add_argument_group(title="Filing optinos")
    filing_group.add_argument('-f', '--file', action='store_true',
        default=False, dest='enable_filing', help='Enable filing of converted PDFs')
    #filing_group.add_argument('-c', '--config', type = argparse.FileType('r'),
    filing_group.add_argument('-c', '--config', type = lambda x: open_file_with_timeout(p,x),
         dest='configfile', help='Configuration file for defaults and PDF filing')
    filing_group.add_argument('-e', '--evernote', action='store_true',
        default=False, dest='enable_evernote', help='Enable filing to Evernote')
    filing_group.add_argument('-n', action='store_true',
        default=False, dest='match_using_filename', help='Use filename to match if contents did not match anything, before filing to default folder')

    # Add flow option to single mode extract_images,preprocess,ocr,write

    args = p.parse_args(argv)

You can use any of those argument to be passed to it's parser, like this :
import pypdfocr

obj = pypdfocr.pypdfocr.pypdfocr()
obj.get_options([]) # this makes it takes default, but you could add CLI option to it.  Other option might be [-v] or [-d,-v]

I hope this help you understand in the mean time :)


text:
Q: Returning multiple sets of data using JSON with Java and JQuery I want to send sets of data from servlet to the jsp using JSON. To elaborate, what exactly I want to do is take multiple rows from the database and print their values in jsp. I done with the part of DB connectivity and fetching of data. But I could not find a way to forward them to jsp using JSONObject. Each row has multiple attributes(column values). Please help me solve the problem.
What I'm doing is:
Collection <JsonObject> c=new ArrayList();
JsonObject j[] = null;

for(int i=0;i<uid_list.size();i++){//uid_list contains all the user_id's from the database
               j[i].add("uid", j[i]);
               j[i].add("fname", j[i]);
               j[i].add("lname", j[i]);
               j[i].addProperty("uid", uid_list.get(i).toString());
               j[i].addProperty("fname", fname_list.get(i).toString());
               j[i].addProperty("lname", lname_list.get(i).toString());
               c.add(j[i]);
}

Also, is there any difference between JsonObject and JSONObject? The latter could not be recognized in servlet and by using JsonObject the put method is not recognized.

A: Aside from your code trying to insert into an uninitialized array, there are many JSON library for Java. You need to provide more details which one you're using
Also if your objective is just passing the JSON string into the browser, you might not even need jsp, you can just write the string version of the JSON object directly into the HttpResponse

A: Firstly, the JspnObject array has to be instantiated before it is used. Therefore, this means the following:
JsonObject j[] = new JsonObject[noOfObjects to be iterated]


text:
Q: How to improve SQL performance for search of top level domains Trying to find a decent .com domain name so I downloaded complete list of .com domains from Verisign with the aim of running some SQL queries against it. One key goal is to run a query that checks dictionary sized list of English words to see if any don't have a.com domain. I don't use online service in part because I haven't found a service that gives me this sort of fine tune query control but it's also because I'm curious how to do this.
My first step was to import Verisign's com.zone file (a text file) into local developer version of SQL Server using built-in import flat file wizard. It created a column I named RawData (datatype nvarchar(450), no nulls) in a table I named Com. It has ~352 million records. The records need some cleanup (e.g. don't need nameserver details, and some records don't seem parsed the same as others) but the domain names themselves seem to have been imported successfully.
I also created another table (~372K records, nvarchar(450), no nulls) named Words which a column named Word that's a listing of most English words (e.g. the, internet, was, made, for, cat, videos, etc.. no definitions, just one word per record).
An immediate hurdle I've run into though is performance. Even a basic query to check availability of a single domain name is slow. When I run
SELECT *
FROM Com
WHERE RawData = '%insert-some-domain-name-here%'

the execution time is approximately 4 minutes (using laptop with i9-9880h, 32GB RAM, 2TB NVMe SSD).
Seeing as I'd prefer not to die of old age before any theoretical dictionary sized query ended, any suggestions on how to write the query and/or database alterations to get me to the end goal of reasonably fast search that generates a list of English words that don't have domain names.

A:
Trying to find a decent .com domain name so I downloaded complete list
  of .com domains from Verisign with the aim of running some SQL queries
  against it. One key goal is to run a query that checks dictionary
  sized list of English words to see if any don't have a.com domain.

Forget about the idea. The pool of available domain names has been mined to death a long time ago. You are not the first to try the idea. The names that are still unregistered are obscure dictionary words that are not really usable and have no commercial use.
There are interesting things you can do, but finding good names 'overlooked' by others is not among them. But you will see for yourself.
Regarding the parsing of the zone file: here is what today's .com zone file looks like:
; The use of the Data contained in Verisign Inc.'s aggregated
; .com, and .net top-level domain zone files (including the checksum
; files) is subject to the restrictions described in the access Agreement
; with Verisign Inc.

$ORIGIN COM.
$TTL 900
@ IN    SOA     a.gtld-servers.net. nstld.verisign-grs.com. (
                  1587225735 ;serial
                  1800 ;refresh every 30 min
                  900 ;retry every 15 min
                  604800 ;expire after a week
                  86400 ;minimum of a day
                  )
$TTL 172800
 NS A.GTLD-SERVERS.NET.
 NS G.GTLD-SERVERS.NET.
 NS H.GTLD-SERVERS.NET.
 NS C.GTLD-SERVERS.NET.
 NS I.GTLD-SERVERS.NET.
 NS B.GTLD-SERVERS.NET.
 NS D.GTLD-SERVERS.NET.
 NS L.GTLD-SERVERS.NET.
 NS F.GTLD-SERVERS.NET.
 NS J.GTLD-SERVERS.NET.
 NS K.GTLD-SERVERS.NET.
 NS E.GTLD-SERVERS.NET.
 NS M.GTLD-SERVERS.NET.
COM. 86400 DNSKEY 257 3 8 AQPDzldNmMvZFX4NcNJ0uEnKDg7tmv/F3MyQR0lpBmVcNcsIszxNFxsBfKNW9JYCYqpik8366LE7VbIcNRzfp2h9OO8HRl+H+E08zauK8k7evWEmu/6od+2boggPoiEfGNyvNPaSI7FOIroDsnw/taggzHRX1Z7SOiOiPWPNIwSUyWOZ79VmcQ1GLkC6NlYvG3HwYmynQv6oFwGv/KELSw7ZSdrbTQ0HXvZbqMUI7BaMskmvgm1G7oKZ1YiF7O9ioVNc0+7ASbqmZN7Z98EGU/Qh2K/BgUe8Hs0XVcdPKrtyYnoQHd2ynKPcMMlTEih2/2HDHjRPJ2aywIpKNnv4oPo/
COM. 86400 DNSKEY 256 3 8 AwEAAbbFc1fjkBCSycht7ah9eeRaltnLDK2sVyoxkjC6zBzm/5SGgfDG/H6XEupT7ctgCvnqexainTIfa8nnBYCOtAec7Gd1vb6E/3SXkgiDaMUJXmdt8E7obtVZqjFlN2QNnTljfMiECn16rZXlvXIi255T1wFkWtp5+LUCiufsLTeKc9xbQw7y0ucsR+GKz4yEStbYi98fnB5nOzzWhRUclf0=
COM. 86400 DNSKEY 256 3 8 AwEAAcpiOic4s641IPlBcMlBWA0FFomUWuKDWN5CzId/la4aA69RFpakRxPSZM8fegOQ+nYDrUY6UZkQRsowPr18b+MqyvHBUaT6CJUBkdRwlVcD/ikpcjvfGEiH5ttpDdZdS/YKZLBedh/uMCDLNS0baJ+nfkmMZGkYGgnK9K8peU9unWbwAOrJlrK60flM84EUolIIYD6s9g/FfyVB0tE86fE=
COM. 86400 NSEC3PARAM 1 0 0 -
COM. 900 RRSIG SOA 8 1 900 20200425160215 20200418145215 39844 COM. ItE0mu9Hb2meliHlot2/6f0cMvCJThPps/BxbyRkDDYesfLBVXqtIRHiDN+wlf7HS+lxFtLHIUzT0GAPf2y5cA0s3pUdBxyRft0fC76GEJq7g0Tcpifdxft4T/6XTv77rP8pFE7aSp+SMDtUMRFIGnGTGBo7WRhjIx1G0peGXMr13xRg4Pa9kigGtjSRi3SWyNT9x1IjVVVJtsFzP9sELQ==
COM. RRSIG NS 8 1 172800 20200423045013 20200416034013 39844 COM. D9BeOQ8drx8LiXXBOk6KlxKacpno/tPujwOAPd482Kj+yAQkFxVVL1bqU03WA7c12W/mkLxk665OQDfOOoirqMePDuamvQCguaSFVKVm5no42JsxoitzwOo+g0kwm9u2F/xGO9ybPfcEQ/nrH9de/RluVSVc0MPsCMja2sCuohEMSYApMjFs4XcXsED0lFTzllIESW7JvK8xb8RFId0TOw==
COM. 86400 RRSIG NSEC3PARAM 8 1 86400 20200423045013 20200416034013 39844 COM. l37dFS1JFXDg9gr1oGACX2rI/iegsIX3RlAEpshuIsT4isZ0FAw0pkAVJQvyqd5a3IOO1TjczWN1U/eYB2ynvX1MKLg3NEp01zUo67eJgowjV+g3zF3XtifhoW///Tqqz0GuAk443jol/Ue00SX3k6XgzxbycX9GKR9FmsLaIIowvz991eJyL1mgOpzQvLnIL1/EAZi9felFilkrj5JaIA==
COM. 86400 RRSIG DNSKEY 8 1 86400 20200430182421 20200415181921 30909 COM. Zkw5YJzP75sdfLN8kN/y8/ywFX+DvotF6fVdxKQGdmgJyyUnDliP6q0VXqVpHHDwtW2WfOlwskiW6007+MIGqV5VtTL6tGeZLv4hJDYZkAwIrl/xBN+aQmIvan4UdBROkOAnfi5Atf1adX5iCqn1jfIGMXb8kKVMrDuDJc/V6XbXEL8NysnqRQtdC6bVuunDQOg/Edw1Uy+B9ly9njU/EmlISkNZo2jo+cXJBFS+Is/6Xcn04+jkHiSRuAFwaGPxKPLeG92v+5ea7pWXBpSIwiqD7Gp/yJCvCUrRZP8eJcoYGav0TT7Bsp2ml15dV20FmNnBPdTqKZHtT8HAIp60Qw==
KITCHENEROKTOBERFEST NS NS1.UNIREGISTRYMARKET.LINK.
KITCHENEROKTOBERFEST NS NS2.UNIREGISTRYMARKET.LINK.
KITCHENFLOORTILE NS NS1.UNIREGISTRYMARKET.LINK.
KITCHENFLOORTILE NS NS2.UNIREGISTRYMARKET.LINK.
KITCHENTABLESET NS NS1.UNIREGISTRYMARKET.LINK.
KITCHENTABLESET NS NS2.UNIREGISTRYMARKET.LINK.
KITEPICTURES NS NS1.UNIREGISTRYMARKET.LINK.
KITEPICTURES NS NS2.UNIREGISTRYMARKET.LINK.
BOYSBOXERS NS NS1.UNIREGISTRYMARKET.LINK.
BOYSBOXERS NS NS2.UNIREGISTRYMARKET.LINK.

What you are interested in is the lines that contain NS in second position. In this example KITCHENEROKTOBERFEST.COM has two name servers declared. Since this is the .com zone file, .com has to be assumed when the name does not end with a dot. So you have to filter on those lines and remove duplicates. You should end up with about 140 million .com domain names. Definitely not 352 million - either you have duplicates or you have imported the wrong data.
That gives you an idea of how crowded the .com zone is. Don't be surprised that any name that remotely makes sense is already registered.
When you have loaded the data to a table, the remaining problem is indexing the data to achieve good performance while making queries. I understand this issue has now been addressed so I won't be making further suggestions on that.
One thing you can do to highlight pure dictionary domains is to do a JOIN of two tables: your domain table and the keyword table. This should need indexes on both sides to run optimally, and I don't have details about your table structure. Or try each keyword by one by one against the domain table in a loop (can use a cursor).
I too feel like this is a whole new question.


text:
Q: jquery detect overlap multiple sections I'm trying to make my fixed navigation change color when it overlaps different parts of my website.
Much like the navigation on this website: http://andpizza.com/
My html exists of divs and sections.

Work

About

Contact

For the JS I use an overlaps library I found on github.
This jquery I added myself:
$(document).scroll(function() {

    var contactColl = $('ul li.contact').overlaps('section');
    $('ul li.contact')[contactColl.hits.length? 'addClass' : 'removeClass']('white');

    var aboutColl = $('ul li.about').overlaps('section');
    $('ul li.about')[aboutColl.hits.length? 'addClass' : 'removeClass']('white');

    var workColl = $('ul li.work').overlaps('section');
    $('ul li.work')[workColl.hits.length? 'addClass' : 'removeClass']('white');

});

Or view here on Codepen.
It works perfectly for the first section. But it ignores the second section. I get that it picks the first section it comes across, but I can't figure out how to make it work for the other section(s).
I tried naming the sections separately like this:
var contactColl = $('ul li.contact').overlaps('#green, #yellow');

or
var contactColl = $('ul li.contact').overlaps('#green');
$('ul li.contact')[contactColl.hits.length? 'addClass' : 'removeClass']('white');

var contactColl2 = $('ul li.contact').overlaps('#yellow');
$('ul li.contact')[contactColl2.hits.length? 'addClass' : 'removeClass']('white');

This just broke everything.
Can anybody help me with this?

A: The Overlaps plugin deals with only one object, over which your target overlaps. just little fix like this:
$.fn.overlaps = function(objs) {
    var elems = {targets: [], hits:[]};
    this.each(function() {
        var bounds = $(this).offset();
        bounds.right = bounds.left + $(this).outerWidth();
        bounds.bottom = bounds.top + $(this).outerHeight();

        $(objs).each(function(){
          var obj = this;
          var compare = $(obj).offset();
          compare.right = compare.left + $(obj).outerWidth();
          compare.bottom = compare.top + $(obj).outerHeight();

          if (!(compare.right < bounds.left ||
                compare.left > bounds.right ||
                compare.bottom < bounds.top ||
                compare.top > bounds.bottom)
             ) {
              elems.targets.push(this);
              elems.hits.push(obj);
          }
        });
    });

    return elems;
};

}(jQuery));
Iterating thru' a collection of objects $(objs).each instead of taking just the first of them - will fix that.
Working demo


text:
Q: How would I enable and disable a function by using the OnKeyDown in Visual C++? I'm fairly new to Visual Studio and C++ in general and am just trying to do some basic stuff with it. Right now I'm trying to figure out how I could enable the function when pressing 'e' and then disabling it when pressing 'd'. This is the code for the functions:
    void draw_line_paint(HDC DC, int x, int y, int a, int b, COLORREF color)
{
    HPEN Stift = CreatePen(PS_SOLID, 3, color);
    SelectObject(DC, Stift);
    MoveToEx(DC, x, y, NULL);
    LineTo(DC, a, b);
    DeleteObject(Stift);
}
//*************************************************************************
void OnKeyDown(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags)
    {

    switch (vk)
        {

            case 68://d
                //disable the function
                break;
            case 69://e
                //enable the function
                break;

            default:break;

        }
    }

A: Do you know what a flag is in programming? It's a boolean variable that can be used to enable or disable something. Set or clear the flag (make it true or false) and check it in the function that you want enabled/disabled.


text:
Q: when i use as.numeric all my latitude and longitude become to "1" [enter image description here][1]
$ latitude : Factor w/ 2 levels "43.0678901152949",..: 1 1 1
$ longitude: Factor w/ 2 levels "-76.1734713936105",..: 1 1 1
current data type is factor, but I want to change them to Numeric, so I use
no3$latitude <- as.numeric(no3$latitude)
no3$longitude <- as.numeric(no3$longitude)

1.I use "as.numeric" in r, to change the data type, but it doesn't work
it becomes to
[enter image description here][2]
$ latitude : num  1 1 1 1 1 1 1 1 1 1 ...
$ longitude: num  1 1 1 1 1 1 1 1 1 1 ...
[1]: https://i.stack.imgur.com/HMj9C.png
[2]: https://i.stack.imgur.com/egcsx.png

A: Sometimes introducing as.character() in a class coercion chain seems to rectify such problems. I think the reason why your code exhibits this behaviour is because under the hood (mode-wise), factor vectors are numeric vectors that go from 1 to n where n is the number of levels.
> x <- as.factor("43.0678901152949")
> as.numeric(x)
[1] 1

> x <- as.character(as.factor("43.0678901152949"))
> as.numeric(x)
[1] 43.06789


text:
Q: How to get the height of a body element Here the total height of all
's are 900 pixels, but the jQuery function returns the height of the body as 577 pixels. (If I remove the body CSS, it's working).
Is there a solution for this problem?
$j(function() {
    alert($j("body").height());
})

html, body {
    height:100%;
}

header

content

footer

A: Simply use
$(document).height() // - $('body').offset().top

and / or
$(window).height()

instead of $('body').height();

A: Set
html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.
The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

A: $(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.

A: I believe that the body height being returned is the visible height. If you need the total page height, you could wrap your div tags in a containing div and get the height of that.

A: We were trying to avoid using the IE specific
$window[0].document.body.clientHeight

And found that the following jQuery will not consistently yield the same value but eventually does at some point in our page load scenario which worked for us and maintained cross-browser support:
$(document).height()


text:
Q: Write Python stdout to file immediately When trying to write the stdout from a Python script to a text file (python script.py > log), the text file is created when the command is started, but the actual content isn't written until the Python script finishes. For example:
script.py:
import time
for i in range(10):
    print('bla')
    time.sleep(5)

prints to stdout every 5 seconds when called with python script.py, but when I call python script.py > log, the size of the log file stays zero until the script finishes. Is it possible to directly write to the log file, such that you can follow the progress of the script (e.g. using tail)?
EDIT It turns out that python -u script.py does the trick, I didn't know about the buffering of stdout.

A: This is happening because normally when process STDOUT is redirected to something other than a terminal, then the output is buffered into some OS-specific-sized buffer (perhaps 4k or 8k in many cases).  Conversely, when outputting to a terminal, STDOUT will be line-buffered or not buffered at all, so you'll see output after each \n or for each character.
You can generally change the STDOUT buffering with the stdbuf utility:
stdbuf -oL python script.py > log

Now if you tail -F log, you should see each line output immediately as it is generated.

Alternatively explicit flushing of the output stream after each print should achieve the same.  It looks like sys.stdout.flush() should achieve this in Python. If you are using Python 3.3 or newer, the print function also has a flush keyword that does this: print('hello', flush=True).

A: This should do the job:
import time, sys
for i in range(10):
    print('bla')
    sys.stdout.flush()
    time.sleep(5)

As Python will buffer the stdout by default, here i have used sys.stdout.flush() to flush the buffer.
Another solution would be to use the -u(unbuffered) switch of python. So, the following will do too:
python -u script.py >> log

A: Variation on the theme of using python's  own option for unbuffered output would be to use #!/usr/bin/python -u as first line.
With #!/usr/bin/env python that extra argument not gonna work, so alternatively,one could run PYTHONUNBUFFERED=1 ./my_scriipt.py > output.txt or do it in two steps:
$ export PYTHONUNBUFFERED=1
$ ./myscript.py

A: You should pass flush=True to the print function:
import time

for i in range(10):
    print('bla', flush=True)
    time.sleep(5)

According to the documentation, by default, print doesn't enforce anything about flushing:

Whether output is buffered is usually determined by file, but if the
  flush keyword argument is true, the stream is forcibly flushed.

And the documentation for sys's strems says:

When interactive, standard streams are line-buffered. Otherwise, they
  are block-buffered like regular text files. You can override this
  value with the -u command-line option.

If you are stuck with an ancient version of python you have to call the flush method of the sys.stdout stream:
import sys
import time

for i in range(10):
    print('bla')
    sys.stdout.flush()
    time.sleep(5)


text:
Q: Unwrapping creates barrier for Value types Looking at the following code (playground ready).
I'm unable to append data to an unwrapped optional array from within an if let statement.
What's the best method to allow appending for an optional array?
class ValueTypeTest {
    var data: [Int]?

    func tryAppend() {
        if var unwrappedData = self.data {
            unwrappedData += [2, 3] // problem !
            self.data! += [4, 5]    // works
        } else {
            // Initialize paging and initial results
            self.data = [0, 1]
        }

    }
}

var v = ValueTypeTest()
v.data // nil
v.tryAppend()
v.data // [0, 1]
v.tryAppend()
v.data // expected: [0, 1, 2, 3, 4, 5] actual: [0, 1, 4, 5]

A: Because Array is a value type and will be copied when you do the if var operation. So you're not changing self.data but unwrappedData.
Try this:
self.data = (self.data ?? [0, 1]) + [2, 3, 4, 5]

This is what I mean.
func tryAppend() {
    if let unwrappedData = self.data {
        self.data = unwrappedData + [2, 3, 4, 5]
    } else {
        // Initialize paging and initial results
        self.data = [0, 1]
    }
}

A: var unwrappedData declared inside the function tryAppend() is a local variable for that function.
The result pane at that line shows you the output containing: [0, 1, 2, 3] for unwrappedData.


text:
Q: LaunchAgents zip/tar not working in plist? I created the plist for a  'custom' backup agent (via LaunchAgent). The (zip) program is called, but I keep getting a 'zip error: Nothing to do!' in my logs.
I assume it has something todo with permissions. I did add sh and zip to my Full Disk Access security settings. But it did not help.
On a side-note, when I move the zip command in a shell (sh) script, it works.
I would like to know why using the zip command directly doesn't?
Running the command for the terminal works also without issues, like so:
/usr/bin/zip /Users/username/Backup/test.zip /Users/username/Documents/*.pdf

LaunchAgent script:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.myuser.DailyBackup</string>
    <key>Program</key>
    <string>/usr/bin/zip</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/username/Backup/test.zip</string>
        <string>/Users/username/Documents/*.pdf</string>
    </array>
    <key>StandardOutPath</key>
    <string>/tmp/my.backup.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/my.backup.err</string>
    <key>Debug</key>
    <true/>
    <key>StartInterval</key>
    <integer>10</integer>
</dict>
</plist>

A: From man launchd.plist
ProgramArguments <array of strings>
This key maps to the second argument of execvp(3) and specifies the argument vector to be passed
to the job when a process is spawned. This key is required in the absence of the Program key.
IMPORTANT: Many people are confused by this key. Please read execvp(3) very carefully!

So you need to use
    <key>Program</key>
    <string>/usr/bin/zip</string>
    <key>ProgramArguments</key>
    <array>
        <string>zip</string>
        <string>/Users/username/Backup/test.zip</string>
        <string>/Users/username/Documents/*.pdf</string>
    </array>

It still won't work though because launchd doesn't expand wildcards and zip doesn't either. It's easier to use launchd to start a shell script which does all the work then.


text:
Q: Access latest file in repository with gradle I've created a task that can extract local .tar files (which I previously manually downloaded from Artifactory) as a test. How can I reference the files when they are on Artifactory from my gradle script? Should I just use the server path? All I've done with gradle is basic stuff and haven't worked with repositories.
I'd also like to perform a certain action based on whether the file has changed since I last ran the script, is that possible?

A: One way of doing this would be to create a new configuration for your TAR file. In my example I gave it the name myTar. In the repositories closure you define the URL to your Artifactory repository and reference the TAR file as dependency in the dependencies closure. When running Gradle it will download the file for you and put it in your local repository. As I read you already created a task that extracts the TAR file. I created a task named extractMyTar which references your downloaded TAR file by its configuration name and untars it into a local directory.
configurations {
    myTar
}

repositories {
    mavenRepo urls: 'http://my.artifactory/repo'
}

dependencies {
    myTar 'your.org:artifact-name:1.0@tar'
}

task extractMyTar << {
    File myTarFile = configurations.getByName('myTar').singleFile

    if(myTarFile.exists()) {
        ant.untar(src: myTarFile, dest: file('myDestDir'))
    }
}


text:
Q: Create Recursive Form Elements I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell  me.

A: It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:

var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");

for (let i = 0; i < rQty; i++) {
    var row = table.insertRow();
    for (let j = 0; j < cQty; j++) {
        var cell = row.insertCell();
        var input = document.createElement('input');
        input.type = 'text';
        input.name = 'input_r' + i + '-c' + j;

        cell.appendChild(input);
    }
}
td {
    border: 2px ridge #333;
    text-align: center;
}


text:
Q: jQuery 1.8 Ajax Request type "HEAD" returns null xhr object on success but worked in 1.7 I seem to have found an undocumented breaking change in jQuery 1.8.3.
While upgrading a page from jQuery 1.7 to 1.8.3 one of our ajax calls of type "HEAD" stopped working.
Upon debugging the success callback is fired but the parameter, "xhr" is null when I use the google CDN to run the page in jQuery 1.8.3.
If I switch back to 1.7 the xhr object is fully operational and not null.
I have scoured google and jQuery site for breaking changes in 1.8.* but can find nothing on point. I need to upgrade this as another library I need to use requires the latest jQuery so I am now between a rock and a hard place.
Code is as follows:
$.ajax({
    type: "HEAD",
    async: false,
    cache: false,
    url: pth + b,
    error: function (xhr) {

    // always succeeds

    },
    success: function (xhr) {
        // in jQuery 1.7.0 ONLY xhr is a non-null object - 1.8.3/1.9.0 receive a null object as a parameter
        c = xhr.getResponseHeader('x-amz-meta-mix');
        if (c == null) c = b;

    }
});

Thanks!
PS- I should add that in Fiddler the response is always 200 and the information I am looking for is always present. The issue is that the xhr object is null if I do not use jQuery 1.7.0 in favor of 1.8.3 or 1.9.0

A: It seems that jQuery has changed the format of the success callback. In 1.8 and later it is:

Type: Function( Object data, String textStatus, jqXHR jqXHR )

The jqXHR is now the third argument, rather than the first, so change your success handler to:
success: function (data, status, xhr) {
    ...


text:
Q: Selecting columns by regex created from different frame I want to select by regex a number of columns from a data frame. The problem is, I want to use pairs of words stored in another frame to do so. To be more specific, column names of mycounts data frame:
aa1 aa2 aa3 bb1 bb2 bb3 ff1 ff2 ff3 cc1 cc2 cc3 dd1 dd2 dd3

and I want to extract to separate frames following pairs (mypairs):
aa bb
aa cc
bb cc
cc dd
dd ff

where aa and bb denote starting patter for columns to select from mycounts.
I can get stuff manually putting desired patterns like this:
tmpdf <- subset(mycounts.test, select=(names(mycounts)[grep('^aa|^bb',names(mycounts))]))

do something with tmpdf
select next pair from mypairs
extract columns from mycounts
do again the same thing with tmpdf etc.
but it will be good to always have pattern of output columns enforced by mypairs. With "|" in grep instead of getting dd then ff columns I have it ff then dd. So I am doing:
tmpdf1 <- subset(mycounts.test, select=(names(mycounts)[grep('^dd',names(mycounts))]))
tmpdf2 <- subset(mycounts.test, select=(names(mycounts)[grep('^ff',names(mycounts))]))
tmpdf <- cbind(tmpdf1, tmpdf2))

Most importantly, naive constructing regex from just first column of mypairs does not work:
for (i in 1:nrow(mypairs)) { foo <- paste('^', mypairs[i,1], sep=""); print(grep(foo, mycounts)) }

This where I am stuck. Many thanks for your help.

A: You did not use the names function in the last command:
Replace
print(grep(foo, mycounts))

with
print(grep(foo, names(mycounts)))


text:
Q: Paramiko: ssh.exec_command to collect output says open channel in response I have python script with paramiko and ssh somewhat as below
import paramiko

# setup ssh connection this works. no problem.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn = ssh.connect(MACHINEIP, username=ROOTUSER, password=ROOTUSER_PASSWORD, port=22)

# This first ssh exec works perfect.
(sshin1, sshout1, ssherr1) = ssh.exec_command(cmd1)

# When I print the output of 2nd and 3rd ssh exec, I get output saying of channel open
(sshin2, sshout2, ssherr2) = ssh.exec_command(cmd2)
print sshout2
(sshin3, sshout3, ssherr3) = ssh.exec_command(cmd3)
print sshout3

Channel open messages in output when exec_command is used more than once to collect output:
<paramiko.ChannelFile from <paramiko.Channel 2 (open) window=2097152
   -> <paramiko.Transport at 0x1d42bd0L (cipher aes128-ctr, 128 bits)
(active; 1 open channel(s))>>>

<paramiko.ChannelFile from <paramiko.Channel 6 (open) window=2097152
   -> <paramiko.Transport at 0x1d42bd0L (cipher aes128-ctr, 128 bits)
(active; 2 open channel(s))>>>

How can I close this open channel? Or any solution on this? I am using python 2.7.

A: Should have used as sshout.read() and rather I used sshout only while printing.


text:
Q: replace dataframe value in group by with previous one I have this data structure :
data = [(1, '5G', '620'), ( '', '5G', '620'), ( 3, '3G', '620'),('', '6G', '620'), (267, '3G', '620')]

df = pd.DataFrame(data, columns=['num', 'ticker', 'value'])

print(fd)

    date    ticker  value
0   1       5GA     620
1   None    5GA     620
2   3       3GA     620
3   None    6HD     620
4   267     6HD     620

By grouping by on the ticker and  value I want to  replace the date with the previous num within the group when the num is none:
for index, row in df.groupby(['ticker','value']).iterrows():
        df.loc[pd.isnull(df['num']), 'date'] = df.loc[df['num']]
print(df)

the output should be as follows :
   date ticker  value
0   1   5GA     620
1   1   5GA     620
2   3   3GA     620
3   267 6HD     620
4   267 6HD     620

I'm stuck, how can I do that?


text:
Q: removing a file in remote repo using a single command Normally when we want to remove a file from remote repo, we remove the file locally, add it to staging, committing and pushing to the remote repo.
But I want to remove a file from my remote repo using a single command in local repo.

A: Try using this:
git rm file_you_want_remove
After that, push all the changes to your remote repo.

A: If you are using GitHub…

*

*Login.

*Maybe fulfill two-factor authentication.

*Click the file you want to delete.

*Click the bin symbol Delete this file.

*Click Commit changes.

Probably slower than…

*

*git rm <FILE>

*git commit -am "lolcats"

*git push


text:
Q: How to exchange data from android to a (html + php) server? I have in a server web page in html + php and I need that information is exchanged in both directions with Andorid application.
For example if the server had some language like python or java (It is not the case), normally I would use a socket server that is running continuously. But using php, I think it's not a good way because it has a maximum time limit of run script and the socket server would be run indefinitely waiting for clients.
The idea is to have a html form, where data of Android phone in real time can be seen, and also can send commands to andorid from html interface.
What is the best way to do this?


text:
Q: Django update single field in model entry with request I try to update a model entry with a POST request.
<QueryDict: {u'is_locked': [u'False']}>

I tried with a model form :
modelEntry = model.get(pk=pk)
modelForm (request.POST, initial= modelEntry)
if modelForm.is_valid():
    modelForm.save()

This was not valid (csrf_exempt)..
And also tried without modelform, directly into the model :
model.objects.filter(pk=pk).update(**request.POST)

Nothing happen ..
Ideally I search a solution with modelform (to check and clean my datas before saving).
There is a proper way for this ?
Cheers

A: You should pass instance, instead of initial to your model form so that it knows which object to update.
modelForm (request.POST, instance = modelEntry)
if modelForm.is_valid():
    modelForm.save()


text:
Q: What happens if we don't check for "if (self)" in init methods? I started to look into the code done by our senior, I found the init method always have code -(id)init method. They used the code with the following ways. The code below is used for all viewControllers.
    self = [super initWithNibName:@"ViewController" bundle:[NSBundle mainBundle]];
    return self;

What is the use of the if(self) and self in this part?
    //And in some viewcontroller contains.
    self = [super initWithNibName:@"ViewController" bundle:[NSBundle mainBundle]];
    if (self) {
        //Do some stuff
    }
    return self;

A: When you access instance variables in your methods the code is equivalent to addressing them via self pointer:
- (void)method {
  iVar = 1;
  // actually the following line will be executed:
  self->iVar = 1;
}

So if for some reason self pointer is nil and you access your ivars in init method, your application will crash as you will try to derefenrence null pointer. e.g. the following simple example will crash:
@implementation TestObj {
  int a;
}

- (id) init {
  self = [super init];
  self = nil;

  a = 1; // Crash
  return self;
}
@end

Also if your [super init] method returned nil for any reason, that might be indicator that something went wrong and you should not proceed with object initialization and any other required work with it.

A: The code regarding the check if self exists :
if (self) {
   //Do some stuff
}
return self;

Is only necessary, if you want to set initial property values. This is why there is the comment
// Do some stuff

If you are not going to set any initial values to variables or properties, no check for self is necessary and it is okay to return self immediately.

A: if (self)  is checking that the call to super actually returns an object after initializing. If something goes wrong it makes no sense to continue, and it would also generate runtime errors.
Keep in mind that the init method is supposed to initialize an object of the type you are creating a class for, and return that object. Your init method overrides the super method, and that is why you call super, so that the code from Apple is run first, and then you do some stuff with the object returned from the init method on i.e. UIViewController.
Then, of course, YOUR init method must also return that object (self).

A: There's always the possibility that the [super initWith...] method failed, thus returning a self that is nil because it's not been created.
In this eventuality, it's a good practice to test if self has been correctly initialized, before operating on it.
The if (self) is actually a "shortcut" to if (self != nil), as any valid object will have a non-null memory address, and thus the if test will succedd with anything different than 0 (null).

A: if(self) is checking to make sure that whatever 'self' is exists before it actually starts doing things to it.
self is an object, so if it doesnt exist then self will be undefined and if(self) will evaluate to false, skipping the code block.


text:
Q: How do i create a IOcspClient, ICrlClient instance in C# I'm using itextSharp in C# to sign a pdf. I have created a method but after the pdf  is signed, it isn't ltv enabled. I searched and found the code snippet below which adds ltv enable to pdf but I don't know how I'm supposed to create the variables ocsp, and crl. What I'm really confused about is the type of information this variables should contain for example should ocsp be a string url or signature name etc? The documentation for these variable on the itextsupport site is very poor and I can't understand what I'm required to provide. Please any help on how to create these two variables ocsp and crl (with an example and a brief explanation), will be greatly appreciated.
using (FileStream fos = new FileStream(@"d:\test.pdf", FileMode.Create))
            {
                PdfReader r = new PdfReader(signedDocument);
                PdfStamper stp = new PdfStamper(r, fos, '\0', true);
                LtvVerification v = stp.LtvVerification;
                AcroFields fields = stp.AcroFields;
                List<String> names = fields.GetSignatureNames();
                String sigName = names[names.Count - 1];
                PdfPKCS7 pkcs7 = fields.VerifySignature(sigName);
                if (pkcs7.IsTsp)
                {
                    v.AddVerification(sigName, ocsp, crl,
                            LtvVerification.CertificateOption.SIGNING_CERTIFICATE,
                            LtvVerification.Level.OCSP_CRL,
                            LtvVerification.CertificateInclusion.YES);
                }
                else
                {
                    foreach (string name in names)
                    {
                        v.AddVerification(name, ocsp, crl,
                                LtvVerification.CertificateOption.WHOLE_CHAIN,
                                LtvVerification.Level.OCSP_CRL,
                                LtvVerification.CertificateInclusion.NO);
                    }
                }

                stp.Close();
                r.Close();
            }

A: You can use the chain:
IList<ICrlClient> crlList = new List<ICrlClient>(); crlList.Add(new CrlClientOnline(chain.ToArray()));
or hard coded url:
ICrlClient crlClient = new CrlClientOnline("https://crl.cacert.org/revoke.crl");


text:
Q: problem recording tweets on a given topic I would like to point out that I already know how to save a user's tweets in a file. Now my problem is that I would like to be able to save the tweets of a given topic in a file.
The problem is that as soon as I try to "convert" the program, I get the error "Status" object is not iterable as below:
Thanks to those who will be able to help :)
search_word = input("subject ? \n")

for tweet in tweepy.Cursor(api.search, q = search_word, lang = "en", since = "2019-04-01").items(3000):
    z = [x for x in tweet]
    with open('%s_tweets.json' % search_word, 'w') as f:
        json.dump(z, out)

Traceback (most recent call last):
  File "C:/Users/TheoLC/Desktop/python/twitter_search/collect+200tw.py", line 17, in <module>
    z = [x for x in tweet]
TypeError: 'Status' object is not iterable

A: It's not entirely clear what you're hoping to do with the code above. There are quite a few things that don't fit together for someone looking at only a snippet, so I've got a few examples to help in a couple of things you may be trying to do.

The reason your current code is failing, is because you're trying to iterate over a Status object with your z= line. This object is JSON like in structure. You can see an example of this here.
This means that you have to access particular attributes in order to iterate over them, you can't iterate over the object itself. For example, if you wanted to get the text from a tweet, you could change your line to:
z = [x for x in tweet.text]

If you're trying to just get the entirety of information of the tweet into a JSON file (i.e the Status object into a JSON file), then you don't need to iterate over it at all, you could just json.dump() the object. To do this, remove your z= line, and change your json dump line to
json.dump(tweet._json, out)

Leaving your code as:
search_word = input("subject ? \n")

for tweet in tweepy.Cursor(api.search, q = search_word, lang = "en", since = "2019-04-01").items(3000):
    with open('%s_tweets.json' % search_word, 'w') as f:
        json.dump(tweet._json, out)

Hope that helps. (You've not asked about this, but as an addendum, I think the amount you have in .items() may be too high. I think the API limits will force you to reduce this).


text:
Q: PowerShell Math Problem? function other3($x, $y)
{
    $tmp = $x + $y
    return $tmp
}

$x = 5
$y = 10

$a = other3($x, $y)
Write-Host $a

Keeps returning 5 10 when it should be returning 15, what's the deal?

A: You're passing a list (5,10) to the parameter $x and $null to $y.
When the function adds $null to the list, you just get the list back.
Adding some write-host statements to the function should make this clear:
function other3($x, $y)
{
    $tmp = $x + $y
    write-host "`x=($x)"
    write-host "`y=($y)"
    return $tmp
}

$x = 5
$y = 10

$a = other3($x, $y)
Write-Host $a

A: To call other3 with two parameters, drop the parenthesis "()" e.g.
$a = other3 $x  $y

The way you're currently calling it, actually passes one parameter, an array with two elements, i.e. 5 and 10. The second parameter is empty (probably defaults to null), meaning the addition does nothing and you simply return the $x parameter.


text:
Q: Git submodules still with detached head When I fetch my git project that uses submodules, the submodules have a detached head. I read many posts here on stackoverflow and they say that that problem should be solved - so I'm doing something wrong, but can't detect what.
That's what happens:
M.Grunwald % git clone -b BranchName ssh://git@10.128.28.106:7999/~m.grunwald/repo_with_submodules.git some_repo
Cloning into 'some_repo'...
remote: Counting objects: 26, done.
remote: Compressing objects: 100% (26/26), done.
remote: Total 26 (delta 9), reused 0 (delta 0)
Receiving objects: 100% (26/26), done.
Resolving deltas: 100% (9/9), done.
M.Grunwald % cd some_repo
M.Grunwald % cat .gitmodules

[submodule "Library/MyLib"]
        path = Library/MyLib
        url = ssh://git@10.128.28.106:7999/~m.grunwald/my_lib.git
        branch = BranchName

M.Grunwald % git submodule init
Submodule 'Library/MyLib' (ssh://git@10.128.28.106:7999/~m.grunwald/my_lib.git) registered for path 'Library/MyLib'
M.Grunwald % git submodule update --remote
Cloning into
'/cygdrive/c/Users/m.grunwald/Documents/TMP/some_repo/Library/MyLib'...
Submodule path 'Library/MyLib': checked out '5c665e00cca5eb24d9b615294807520a6036fa90'
git submodule update --remote  4.31s user 10.61s system 10% cpu 2:21.52 total
M.Grunwald % cd Library/MyLib
M.Grunwald % git status
HEAD detached at 5c665e0
nothing to commit, working tree clean

So, the .gitmodules contains the submodule, including "branch = branchname" and I call submodule update with --remote ... What is still missing?
% git --version
git version 2.12.3
That's what happens if I switch to BranchName (cwd is some_repo/Library/MyLib):
M.Grunwald% git branch -r
  origin/HEAD -> origin/master
  origin/BranchName
M.Grunwald % git checkout BranchName
Branch BranchName set up to track remote branch BranchName from origin.
Switched to a new branch 'BranchName'
M.Grunwald % git status
On branch BranchName
Your branch is up-to-date with 'origin/BranchName'.
nothing to commit, working tree clean
M.Grunwald % cd ..
M.Grunwald % ..
M.Grunwald % git status
On branch BranchName
Your branch is up-to-date with 'origin/BranchName'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)

        modified:   Library/MyLib (new commits)

M.Grunwald % git diff Library/MyLib
diff --git a/Library/MyLib b/Library/MyLib
index 1341b30..5c665e0 160000
--- a/Library/MyLib
+++ b/Library/MyLib
@@ -1 +1 @@
-Subproject commit 1341b30ae55df1afc7265a9110fbf09661dd627b
+Subproject commit 5c665e00cca5eb24d9b615294807520a6036fa90

A: Looks normal to me. What exactly is your problem? A submodule is always in a detached head state, even if it is properly set up to track a branch (see link below). When you switch branches in your parent repository, you have to run git submodule update to update your submodules to the commit of the new branch, if it is different.
From this answer, which seems to adress exactly what you want to know:

Note that the result, for each updated submodule, will always be a
  detached HEAD, as Dan Cameron note in his answer.


text:
Q: Why ( float: right; ) doesn't work? Blue box should be on the right I have list of items on the left hand side (coral box) and I need main content to be in the Blue box (on the right next to coral box), but instead they are overlapping (image below)
Here is my HTML and CSS below, what do you think causing the overlapping and how to fix it?
Thanks!

.category-tree {
  width: 300px;
  height: 900px;
  font-size: 14px;
  padding-top: 20px;
  background-color: coral;
}

.left-menu li {
  padding-top: 30px;
  padding: 6px 0 2px;
  list-style: none;
}

.left-menu-categories {
  width: 240px;
  color: black;
}

.left-menu-categories a {
  color: black;
  padding-left: 40px;
}

.category-tree a:hover {
  text-decoration: underline;
}

hr {
  margin-top: 18px;
  margin-bottom: 15px;
  width: 200px;
  height: 1px;
  border-width: 0;
  background-color: #b8b8b8
}

.blue-box {
  float: right;
  position: absolute;
  display: flex;
  background-color: lightblue;
  width: 800px;
  height: 900px;
}

Category

Category

Category

Category

Category

Category

Text Here

A: Dont use float for styling purpose. It is a mis-used hack from pre 2012. Since 2012 you have Flexbox and since 2015 Flexbox and CSS-Grid are well established and not causing so many possible issue as float. Float was never intended as styling tool just to float images within a paragraph (like newspaper).
Simply use flexbox:

*

*Give the wrappe the flex property and change its width to 100% to be responsive.

.category-tree {
  width: 100%
  min-height: 900px;
  font-size: 14px;
  padding-top: 20px;
  display: flex;
}

*Give the blue textbox the property flex-grow: 1; to consume the remaining space

.category-tree {
  width: 100%
  min-height: 900px;
  font-size: 14px;
  padding-top: 20px;
  display: flex;
}

nav {
  background-color: coral;
}

.left-menu li {
  padding-top: 30px;
  padding: 6px 0 2px;
  list-style: none;
}

.left-menu-categories {
  width: 240px;
  color: black;
}

.left-menu-categories a {
  color: black;
  padding-left: 40px;
}

.category-tree a:hover {
  text-decoration: underline;
}

hr {
  margin-top: 18px;
  margin-bottom: 15px;
  width: 200px;
  height: 1px;
  border-width: 0;
  background-color: #b8b8b8
}

.blue-box {
  display: flex;
  background-color: lightblue;
  flex-grow: 1;
}

Category

Category

Category

Category

Category

Category

Text Here

A: Instead of using float or flexbox I actually recommend you use grid
This is your html:

Category

Category

Category

Category

Category

Category

Text Here

Grid would allow you to make it super responsive for mobile etc.
Your CSS would look something like this
CSS:
category-tree{
 display:grid;
 grid-templates-column: auto auto ;
 /* you can add any padding here as well */
}

What happens here is that you are saying the first element inside the major div with class category-tree will be the first element on the left, the next element which is your div with the blue box will be on the right. When you go to work with mobile you can change the css in a media query with the correct sizing then your css would be:
category-tree{
     display:grid;
     grid-templates-column: auto ;
     /* you can add any padding here as well */
    }

This would be a great way to arrange everything. You can add spacing between them by adding grid-column-gap: 2rem; or any other value you would like. Then with each element you can add padding or anything you need with the other classes you created for each element.


text:
Q: Accessing Registers on NModbus I've been working with using Nmodbus to communicate with two computers. I've gotten the actual communication working, but there's a lot I don't know about using Nmodbus.
The package I've been using is found here, installed as a nuget package.
https://github.com/NModbus/NModbus
Within Modbus protocols, Discrete inputs and Input registers are read-only from the master's perspective. How do I change them on the slave side in order to simulate a compute reading something? Secondly, I want to be able to print out a few specific holding registers in order to prove that the protocol is sending data from one computer to another. Is there a way to address a slave device such to read a specific value (on the slave side, not using ReadMultipleRegisters).
IF that doesn't make sense, I'm imagining something like this;
slave.DataStore.HoldingRegisters[3] = 7
Then, if the master read all data values, register 3 would read 7, and everything else would be as it was.


text:
Q: How to update a field with random numbers? I have to update all the rows of the TaxId column in my table with random numbers.
UPDATE myTable
SET TaxID = abs(checksum(NewId()) % 10000)

I tried the above code on one record, and it updated the TaxId with a random number of ONLY 4 digits. How do I get it to update with 9 random digits?

A: Increase zeros in mod as below
UPDATE myTable
 SET TaxID = abs(checksum(NewId()) % 1000000000)


text:
Q: Find all positive real solutions of the system
Find all positive real solutions of the system of equations
  $$\begin{cases}
x_1+x_2+...+x_{1994}=1994 \\
x_1^4+x_2^4+...+x_{1994}^4=x_1^3+x_2^3+....+x_{1994}^3
\end{cases}$$

''By Hölder, we have in general
$(x_1+x_2+\dots+x_n)(x_1^3+\dots+x_n^3) \le n \cdot (x_1^4+\dots+x_n^4)$ with equality iff the $x_i$ are all equal.
So in this case we must have $x_1=\dots=x_{1994}=1$.''
Theory a more algebraic solution? (sum, subtraction, etc ...)

A: Notice that $$ x^4-x^3\geq x-1$$
with equality iff $x=1$. Let
$$E:= x_1^4+x_2^4+...+x_{1994}^4-(x_1^3+x_2^3+....+x_{1994}^3)$$
So we have $$0=E\geq x_1+...+x_{1994}-1994=0$$
and thus all $x_i=1$.


text:
Q: Topic Words Selection in Topic Modeling I understand how generative model of topic modeling works; for each topic there is a distribution of words, and for each document there is a distribution of topics.
Question is how words are determined for each individual topic ? Does this change algorithm to algorithm ?
Edit:
Such as:
Topic-1 : internet, web, search etc.
Topic-2 : literature, novel, etc
I wonder how "internet, web, search" are chosen for topic-1. Why "internet" and "web" take place in same topic instead of separate topics? Is it because they frequently coexist in different documents?

A: In standard topic modeling, each topic is a discrete probability distribution over the entire vocabulary. However, after performing inference it is generally the case that only a few words have significant probability mass in each topic. For example:
Word        Probability
----------  -----------
internet    0.2
web         0.15
search      0.08
  .
  .
milkshake   0.000002

The above topic assigns very high probability to words related to the internet, but it also assigns some non-zero probability to every other word in the vocabulary (including, for example, milkshake).
Since most words in the vocabulary have very small probability under this topic, we can summarize the topic by only showing the highest-probability words. Such summaries might make it look like each topic is a distribution over a different subset of words, which I think is the source of your confusion.

A: Yes, it is because they frequently co-occur across documents. LDA is a probabilistic model that describes a process for how documents are generated, namely by randomly choosing a set of topics and then randomly choosing words from those topics. The topics themselves are hidden variables which seek to account for why groups of words tend to co-occur together within documents. So, the goal of topic modeling is to use some inference method that seeks to discover the hidden topics that best explain the co-occurrence patterns of words across documents. It is closely related to probabilistic latent semantic analysis.


text:
Q: Enabling Swipe-to-delete while showing reorder controls on UITableView I am looking to allow reordering of UITableViewCells and deleting via swipe to delete, but not via the red delete circle.
- (void)loadView
{
    [super loadView];
    [table setEditing:YES animated:NO];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Perform delete here
    }
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    // Perform move here
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

Additionally, I've tried disabling the edit mode and calling -[UITableViewCell setShowsReorderControl:YES] with no luck.

(source: booleanmagic.com)

A: I think you'll have to do some custom touch event interception.
In english:
if finger moved, x distance, horizontally across cell, in that cell only, then show delete control.
Not sure how to turn off the circles to the left, but I do think it's a property like "shows reorder control"


text:
Q: How can I create a TypeScript type that reduces an array of const objects to a const record object? I want to write a TypeScript type that "reduces" an input array of objects to a record object, with the object keys taken from a property of the input array members.
This will be used for const inputs and therefore the resulting object should have correct types for each member.
This is my current attempt, but the ExtractName<Args[N]> is not working.
How can I solve this?
type TypedArguments<Args extends readonly ArgumentSpec[]> = {
  // what I would like is to output an object type with
  // fixed string keys taken from each member of the (const) input
  readonly [N in keyof Args as ExtractName<Args[N]>]: ExtractValue<Args[N]>

  // this works but output is an array
  // readonly [N in keyof Args]: ExtractValue<Args[N]>
};

type ExtractName<
  T extends ArgumentSpec
> = T['name']

type ExtractValue<
  T extends ArgumentSpec
> =
  T['multiple'] extends true ? string[] : string

export interface ArgumentSpec {
  name: string
  multiple: boolean
}

function mapArguments<Args extends readonly ArgumentSpec[]>(args: Args): TypedArguments<Args> {
    // content here is not important, this would do some parsing of
    // input and then do the as TypedArguments<Args> at the end
    return args.reduce(
      (arg: ArgumentSpec, agg) => ({ ...agg, [arg.name]: arg.multiple ? ['foo', 'bar'] : 'baz' }),
      {} as any
    ) as unknown as TypedArguments<Args>
}

const mapped = mapArguments([
    { name: 'key1', multiple: true },
    { name: 'key2', multiple: false }
] as const)

// Now I want this to work
mapped.key1.map((x: string) => x.toUpperCase())
mapped.key2.toUpperCase()

// when using the commented-out line in the TypedArguments type instead,
// then this works. I'd like an object though, not an array.
// mapped[0] is string[]
// mapped[1] is string
// mapped[0].map(x => x.toUpperCase())
// mapped[1].toUpperCase()

See also in Typescript Playground
Expected this to work as outlined above. Did not find a TypeScript construct that would make it work.

A: The issue here is the way you are trying to use a mapped type to "iterate" over a tuple but you also want an object type as the result. keyof Args will produce not only the elements but also all the other properties that arrays can have and that messes with your return type.
Intead, map over the union of elements with Args[number].
type TypedArguments<Args extends readonly ArgumentSpec[]> = {
  readonly [N in Args[number] as N["name"]]: ExtractValue<N>
};

Also, I used the Expand utility type so we can properly see the expanded return type of the function.
type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;

function mapArguments<Args extends readonly ArgumentSpec[]>(args: Args): Expand<TypedArguments<Args>> {
    // content here is not important, this would do some parsing of
    // input and then do the as TypedArguments<Args> at the end
    return args.reduce(
      (arg: ArgumentSpec, agg) => ({ ...agg, [arg.name]: arg.multiple ? ['foo', 'bar'] : 'baz' }),
      {} as any
    ) as unknown as Expand<TypedArguments<Args>>
}

Playground


text:
Q: Responsive Navbar using CSS no Bootstrap I'm relatively new to coding and I've researched this topic and can't find an answer that fully fixes my issue of creating a responsive navbar. I've used the @media screen query in my #CSS and it works to an point, but then my navbar begins to stack up vertically rather then scale down while keeping its postion. Here is what I have for code:

body{
 background: url('alt_largemouthbass.jpg') no-repeat center center fixed;
 background-size: cover;
 background-color:black;
 font-family: 'Amatic SC', cursive, arial;
}

.navigation{
 text-align:center;
}

ul.navbar{
 margin:0px;
 padding:0px;
 list-style-type:none;
 display:inline-block;

}

.navbar li{
 float:left;
 width:300px;
 height:50px;
 background-color:black;
 text-align:center;
 line-height:50px;
 opacity:.8;
 border:solid white 1px;
 text-shadow:2px 2px 2px white;
}

.navbar li ul {
 display:block;
 position:relative;
 left:-41px;

}

.navbar li ul li{
 border:solid white 1px;
 display:none;
 border-radius:15px;
}

.navbar li a{
 text-decoration:none;
 display:block;
 position:relative;
}

.navbar li ul a:hover{
 background-color:grey;
}

.navbar li:hover ul li{
 display:block;
 overflow:hidden;
 -webkit-border-radius:15px;

}

a{
 color:green;
 font-weight:bold;
 font-size:30px;
 padding-bottom:.5px;
 padding-top:.25px

}

@media screen and (max-width:1200px){
 .navigation{
  width:100%;
 }
 .navbar li{
  width:25%;

 }
}
<!DOCTYPE HTML>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Amatic+SC" rel="stylesheet">
<title>Lorem Ipsom docnectuer</title>
<link rel="stylesheet" type="text/css" href="experiment.css"/>

Home

Lorem ipsum

ispum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

About

I'm trying to make the navbar scale down while retaining its position and drop down menus. It currently works when I scale the browser down approx 20-50px but any more shrinking and it stacks the navbar vertically and the the dropdown menus become blocked by the parent li/ parent element. On a phone the viewport is so small I'm sure they would have to stack vertically and then I would end up using some sort of z-index and some conditions. But I'm currently trying to solve this problem with html and CSS. Everything I've seen has pointed to using bootstrap. Any and all assistance would be greatly appreciated.


text:
Q: Error The statement did not return a result set @Query(nativeQuery=true,value="update tbl_runningNumber set autoNum= autoNum+1 where cycle=:cycle and module=:module")
String updateByCycle(@Param ("module")String module,@Param("cycle") int cycle);

I want to update data form spring to database
when i click on update at database is work normal but at my spring error messages
2023-02-01 16:17:47.651  WARN 21588 --- [nio-8082-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: null
2023-02-01 16:17:47.651 ERROR 21588 --- [nio-8082-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper   : The statement did not return a result set.

A: Make return type for the method to void as the update query does not return anything.
Also for update query you should annotate method with below annotations along with @Query.
@Transactional
@Modifying

A: Try to annotate your update method with @Modifying annotation.


text:
Q: How to execute piped command using ProcessStartInfo API in windows? I need to execute the following command in Visual Studio:
dsquery group -name "groupname" |dsget group -members

This works fine in command prompt, but doesn't give any output in Visual Studio.
I am using following code snippet.
private void button1_Click(object sender, EventArgs e)
{
string groupname =" " + "group" + " " + "-name" + " " + search_box.Text+"dsget"+" "+"group"+" "+"-members";
    ProcessStartInfo psi = new ProcessStartInfo("dsquery", groupname);
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    psi.CreateNoWindow = true;
    var proc = Process.Start(psi);
    string s = proc.StandardOutput.ReadToEnd();
    textBox1.Text = s;
}

Please let me know what is wrong with this code?


text:
Q: Inserting data into two databases, where one is a third party I need to insert data into two different databases. One is locally, and the other is a third party CRM that provides me with path to their php file. This is the code I am right now using to insert data into their database.
     <form accept-charset='ISO-8859-1' enctype='application/x-www-form-urlencoded;charset=ISO-8859-1' name='opt_in_form' id='opt_in_form' action='https://www.thirdpartyurl.com/index.php' method='post'>

 <input type='text' id='somevalue' name='somevalue'>

 <input type='text' id='somevalue' name='somevalue'>

 <input type='text' id='somevalue' name='somevalue'>

 </form>

How do I grab the same data and dump it into another php that feeds a local MySQL? Can I call two actions in the  ? Or do I have to do something else?

A: Since you have to insert data in 2 databases, you have to do 2 actions. One local action, and one "remote" action.
Possibilty:

*

*Create a php file on your own server where you POST the values to

*This PHP has to do a POST to the 3rd party URL (i.e. by using curl, http://www.php.net/manual/en/book.curl.php)

*Insert the values into the local database (i.e. MySQL database?)


text:
Q: Dynamic Xelement query in LINQ I'm just wondering if it is possible to query a dynamic named xml element using LINQ.
See below sample XML doc:

<attendees>
<name>linda talor<name/>
<jur_a_credits>1.0<jur_a_credits/>
<jur_a_title>course 1<jur_a_title/>
<jur_f_credits>2.5<jur_f_credits/>
<jur_b_qualifier>self-study<jur_b_qualifier/>
<attendees/>

I want now to select all xelement which contains a named "jur" then iterate the list to retrieves its value. Meaning,  I want to have below

    1.0
    course 1
    2.5
    self-study

as in a collection so that I can iterate each of them to get there values.
Is it possible to query it in LINQ?

A: Sure:
// You could use "Contains" instead of "StartsWith" of course
var query = doc.Descendants()
               .Where(x => x.Name.LocalName.StartsWith("jur"))
               .ToList();