text:
Q: Hibernate @ManyToOne remove entry at One side, set FK to NULL at Many side I'm trying to learn to work with Hibernate but probably i don't understand @ManyToOne and inverse relations. I have two entities Author and Department. One Author has one Department, One Department has Many Authors.
When I remove Author, nothing should happen with Department. When I remove Department, FK in Author's table should be updated to NULL value (Author should NOT be removed).
I've found nice explanation of inversion and figured out that Author is an owning side and according to this thread when I remove child (Department) the FK should be set to NULL. But it doesn't happen because only Department is removed and FK remains in Author table (which leads to org.hibernate.ObjectNotFoundException: No row with the given identifier exists).
When I add CascadeType.REMOVE to @OneToMany annotation in Department entity then all Authors tied to Department are also removed. Neither of aforementioned states are desirable. I just want to remove Department and set FK in Author table to NULL. How to do that?
Author and Department entities with annotations:
@Entity
@Table(name = "author")
public class Author implements Serializable {

    @Id
    @Column(name = "idauthor")
    @GeneratedValue
    private Integer idAuthor;

    @DepartmentFormat
    @ManyToOne
    @JoinColumn(name = "department", nullable = true)
    private Department department;
}

@Entity
@Table(name="department")
public class Department implements Serializable {

    @Id
    @Column(name="iddepartment")
    @GeneratedValue
    private Integer iddepartment;

    @OneToMany(mappedBy = "department", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    private Set<Author> authors;
}

Thanks in advance

A: There is no automatic way of setting all the foreign keys to null when some entity is removed. You have to explicitely get all the authors of the department, set their departement to null, and then remove the department.
You could also use a bulk update query to do this:
update Author a set a.department = null where a.department = :department

(and thus have just one query instead of n + 1), but be aware that the version field won't be updated, that there won't be any optimistic locking check, and that the already loaded departments of the session won't be affected (in memory) if you do so.
Note that you shouldn't have an ObjectNotFoundException when you're deleting an entity referenced by another one. Instead, you should enable a foreign key constraint in the database so that the removal of the department fails if there is still an author referencing it. That way, your data stays in a coherent state.


text:
Q: which linux kernel code create /dev/sda or /dev/sda1 for SATA device? Someone told me udev create /dev/sda device when SATA device is detected.
But as I read or understand udev. udev can run program or add symblink but can not create device /dev/sda.
Image related to device node

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does this line do? df = df[~df[runner].str.contains("[a-z]").fillna(False)] may I check what does this line do?
df = df[~df[runner].str.contains("[a-z]").fillna(False)]

Is this code remove all rows that contain string that start with alphabet?
2nd question is what is the purpose of ~? What does it do?
Thanks

A: This code is masking a DataFrame.
The RegEx "[a-z]" means contains any character 'a to z' (not 'starting with', as this would be "^[a-z]").
The .fillna(False) means every NaN is treated as False for this Mask.
The ~ is inverting the Mask, so that the unselected rows are returned.
Be aware that the rows containing NaN are included. If this is not intended you must use .fillna(True).


text:
Q: Bound UIView frame to Method frame inside another class Currently I have an Method inside a UIView that has been added as a subview. I would like to know how I can keep the Method's properties so its frame dictates the size of the UIView.
NSObject:
public class func drawCanvas1(frame frame: CGRect = CGRect(x: 0, y: 0, width: 86, height: 31)) {

    let rectanglePath = UIBezierPath(rect: CGRect(x: frame.minX + frame.width - 86, y: frame.minY + floor((frame.height) * 0.00000 - 0.5) + 1, width: 86, height: frame.height - 1 - floor((frame.height) * 0.00000 - 0.5)))
    UIColor.grayColor().setFill()
    rectanglePath.fill()

}

UIView:
class shapeTestUI: UIView {

    override func drawRect(rect: CGRect) {
        StyleKitName.drawCanvas1()
    }
}

View Controller:
var block1: shapeTestUI = shapeTestUI()

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor(red: 38.0 / 255, green: 151.0 / 255, blue: 68.0 / 255, alpha: 1)

    let block = createBlock(block1)
    self.view.addSubview(block)

}

func createBlock(blocks:UIView) -> UIView {

    let block = blocks as UIView!
    //block.frame = CGRectMake(0, 0, 50, 50)

    return block
}

A: First, your code does not show a "method" being added as a subview as this is not possible. Read this: https://en.wikipedia.org/wiki/Method_(computer_programming).
Second, Overriding the drawRect function does not add a subview but instead draws the UIView itself according to the code inside it (i.e. the PaintCode StyleKit function).
Third, If you want the frame of the UIView to be dictated by the drawing code alter your PaintCode function like so:
public class func drawCanvas1(frame: CGRect) {
   let rectanglePath = UIBezierPath(rect: CGRect(x: frame.minX + frame.width - 86, y: frame.minY + floor((frame.height) * 0.00000 - 0.5) + 1, width: 86, height: frame.height - 1 - floor((frame.height) * 0.00000 - 0.5)))
   UIColor.grayColor().setFill()
   rectanglePath.fill()
}

Next, in shapesTestUI, you should pass the parameter rect of drawRect to the modified PaintCode function:
class shapeTestUI: UIView {

   override func drawRect(rect: CGRect) {
      StyleKitName.drawCanvas1(rect)
   }
}

And last, you should give the desired CGRect when initializing block1 in your View Controller
var block1: shapeTestUI = shapeTestUI(frame: CGRect(x: 0, y: 0, width: 86, height: 31))


text:
Q: Визуализация черной дыры в Tkinter Задание:
Реализуйте отрисовку стимуляции параллельного пучка фотонов, подходящего вблизи черной дыры и искривляющегося под действием ее гравитации.
Вопрос:
Как реализовать притяжение фотонов к черной дыре?(По сути должны изменяться координаты фотонов)
В моей реализации я пытался задавать движение в функции movePhoton класса Photon, однако успеха не достиг.
Мой код:
import tkinter as tk
import math

width = 600
height = 600
root = tk.Tk()
c = tk.Canvas(root, width=width, heigh=height, bg="white")

class BlackHole:
    """Класс черной дыры"""
    def __init__(self, c, x1, y1, radius, mass, color="black"):
        self.c = c
        self.x1 = x1
        self.y1 = y1
        self.radius = radius
        self.mass = mass
        self.color = color
        self.drawBlackHole()

    def drawBlackHole(self):
        """Отрисовка черной дыры"""
        self.greyField = c.create_oval(self.x1 - self.radius*4, self.y1 - self.radius*4, self.x1 +
                                  self.radius*4, self.y1 + self.radius*4, fill="grey", outline="grey")

        self.whiteFieldOne =  c.create_oval(self.x1 - self.radius*2.7, self.y1 - self.radius*2.7, self.x1 +
                                  self.radius*2.7, self.y1 + self.radius*2.7, fill="white", outline="white")

        self.orangeField = c.create_oval(self.x1 - self.radius*2, self.y1 - self.radius*2, self.x1 +
                                  self.radius*2, self.y1 + self.radius*2, fill="#f3be62", outline="#f3be62")

        self.whiteFieldTwo =  c.create_oval(self.x1 - self.radius*1.5, self.y1 - self.radius*1.5, self.x1 +
                                  self.radius*1.5, self.y1 + self.radius*1.5, fill="white", outline="white")

        self.blackhole = c.create_oval(self.x1 - self.radius, self.y1 - self.radius, self.x1 +
                                  self.radius, self.y1 + self.radius, fill=self.color)

    def setMass(self, new_mass):
        self.mass = new_mass

class Photon:
    """Класс фотона"""

    def __init__(self, x1, y1, massPh, massHole, x2, y2, radiusHole, radius=2):
        """
        x1, y1 - координаты фотона
        radius - радиус фотона
        massPh - масса фотона
        massHole - масса черной дыры
        distance - расстояние между фотоном и черной дырой
        x2, y2 - координаты черной дыры
        """
        # Фотон
        self.x1 = x1
        self.y1 = y1
        self.radius = radius
        # Дыра
        self.x2 = x2
        self.y2 = y2
        self.radiusHole = radiusHole
        self.massPh = massPh
        self.massHole = massHole
        self.drawPhoton()

    def drawPhoton(self):
        """Отрисовка фотона"""
        self.photon = c.create_oval(self.x1 - self.radius, self.y1 - self.radius, self.x1 +
                                  self.radius, self.y1 + self.radius, fill="red")

    def movePhoton(self):
        """Движение фотона"""
        # След фотона
        c.create_oval(c.coords(self.photon)[0] + 1, c.coords(self.photon)[1] + 1, c.coords(self.photon)[0] +
                                  1, c.coords(self.photon)[1] + 1, fill="red")

        distance = math.sqrt(math.pow((self.x2 - c.coords(self.photon)[0] - self.radius), 2) + math.pow((self.y2 - c.coords(self.photon)[1] + self.radius), 2))
        # Притяжение, но не знаю как реализовать
        gravity = 0.02*(self.massPh * self.massHole)/ distance
        c.move(self.photon, -2, gravity)

        root.after(16, self.movePhoton)

def scale_processing(number):
    """Обработка значения ползунка"""
    number = int(number)

def main():
    root.title("Черная Дыра")
    c.pack()
    radiusHole = 40
    blackhole = BlackHole(c,width/2, height/2, radiusHole, 80)

    # Создание фотонов
    PhoCount = 4
    photon_list = [(Photon(580, 250+i*10, 10, blackhole.mass, blackhole.x1, blackhole.y1, radiusHole)) for i in range(PhoCount)]
    for pho in photon_list:
        pho.movePhoton()

    scale = tk.Scale(
        root, from_=0, to=100, resolution=2, command=blackhole.setMass, orient=tk.HORIZONTAL,
    )
    scale.pack(side=tk.LEFT, padx=5)

    root.mainloop()

if __name__ == "__main__":
    main()

PS:
Знаю, что такое задание было реализована на JavaScript, но данный ЯП не знаю. Поэтому тот код, ничем не поможет.
Чтобы лучше понять какого результата я хочу достигнуть, можете посмотреть результат в видеоролике 2d black hole visualization на ютубе


text:
Q: How to Connect a System that has only JSON input and output with another that has XML input and output Let's assume there are two systems (A and B) that need to send data files back and forth, however both have been engineered independently and one supports JSON only, while the other supports XML only.
What are potential solutions to enable them connect?
System A, which deals with JSON only files cannot be altered. System B, which deals with XML only files potentially could be altered, but only as a last resort, and at great cost.
On a high level, I'd anticipate that something sits between, which does some format conversion. What forms could this intermediary take, what are the pros and cons of these options, considering security, reliability, ease of deployment and performance impact.
All relevant views welcome.
Thanks!

A: There are many libraries that do that. If you're e.g. programming C#, there's JSON.NET, a library that can do that for you but there are libraries for just about every imaginable language, due to its popularity.
From a design point of view, XML and JSON are two formats that are typically used in web services and they, in turn are typically used for inter-machine communication. To allow for two-way conversion, each web service would have a method that can convert from A to B.
As you'll read on json.org, there's really no reason to churn out your own conversion code, unless you really want to.
In terms of ease of use, as I said, web services are the de facto standard for this kind of serialized inter-machine communication and are pretty straight-forward. Performance and security are of course web- or network-related and you should look into what the data volumes and project requirements are before you jump to conclusions.


text:
Q: discord bot change nicknames if in bad words Hello i have a problem with my discord bot. I want to create event where it change someone nickname if its in bad words and I dont know how to do it.
I have not found anything concrete anywhere on how to do this and I would appreciate it if someone could help get my feet wet on how to do this.
@client.event
async def on_member_update(before, after):
    n = after.nick
    bad_words = ["chuj"]
    if n.lower().count (bad_words) > 0:
        await after.edit(nick="ZMIEN NICK")

A: This is not valid Python syntax:
if n.lower().count (bad_words) > 0:

I'm guessing you mean something like
if any(x in n.lower() for x in bad_words):

This looks for any of the words in bad_words as a substring of n. If you mean something else, it should generally not be hard to find an existing question just by articulating a search for the kind of matching you are looking for.


text:
Q: Java cannot find symbol error I know that "cannot find symbol" shows up when there misspelled something or the variable is not in the scope it is used or something like this. But still I cannot figure out what causes that problem in my situation. I have two classes: Driver.java and DisplayPanel.java
Driver.java code :
package csHW9;

import javax.swing.JFrame;
import csHW9.DisplayPanel;

public class Driver {

    public static void main(String[] args){
        JFrame frame = new JFrame("Dungeon Diver");
        DisplayPanel panel = new DisplayPanel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

}

DisplayPanel.java code:
package csHW9;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

import javax.swing.JPanel;
public class DisplayPanel extends JPanel{
private Dungeon dungeon;

public DisplayPanel(){
    setPreferredSize(new Dimension(600, 600));
    this.dungeon = new Dungeon();
    addKeyListener(new KListener());
    setFocusable(true);
}

Dungeon is just another class and I'm making its instance in DisplayPanel class.
The error I get is this:
 Driver.java:12: cannot find symbol
symbol  : class DisplayPanel
location: class csHW9.Driver
        DisplayPanel panel = new DisplayPanel();

I don't understand what I'm doing wrong. Any suggestions?

A: You need to add import statement in Driver class at top.
Example:
import yourpackage.Driver


text:
Q: why does the chronology of the child view in navigationdrawer matters? I ran into this issue while developing a navigation drawer for my app,when the chronology of the child views are as follows everything works like a charm
    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:openDrawer="start">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/main_nav_graph" />

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_menu" />
    </androidx.drawerlayout.widget.DrawerLayout>

and the menu items stop responding to the clicks if the child views are as follows
    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:openDrawer="start">

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_menu" />

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/main_nav_graph" />
    </androidx.drawerlayout.widget.DrawerLayout>

So thereby the chronology of the child views inside the navigation drawer matters, I wanna know why?

A: In the documentation for DrawerLayout it says this:

To use a DrawerLayout, position your primary content view as the first child with width and height of match_parent and no layout_gravity>. Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.

Documentation source: DrawerLayout
So my guess for this is that content needs to be the first child because the menu is sliding over your content. It is probably in the background on how DrawerLayout handles these layouts. So if you put it as a second child it will somehow overlap and disable click events on the menu itself. Hope this explains it.


text:
Q: Missing Organization Feature: Event__c.Sharing I am trying to upgrade a package in a subscriber org.  This org has a locally created custom object, Event__c.
I get the following error message:

Missing Organization Feature: Event__c.Sharing Custom Object Records
  Package install error
  There are problems that prevent this package from being installed.

The new version of the package has a brand new custom object, nsPrefix_Event_c.
From reading around, I believe that this message is saying that the new Event object is private, so private sharing settings must be present.  And yet this is a brand new object so I can't see why it would fail there.  This is a package that has already been installed successfully many times.
The only possibility I can think of is that SFDC gets confused between Event_c (Controlled By Parent) and nsPrefix_Event__c (Private) and thinks they are the same object.  Could this be happening here?

A: If the custom object's name is Event__c, then yes, SF can get "confused" with the API name. You can log a case to get more details, but if you change the API name you might be able fix this. Give it a try.

A: SFDC Case Response

I am following up your case number xxxxxxx.
Please be advise that I consulted our Backline Engineer and he
  identified that this currently reported as a known issue (Bug). Also,
  this issue has been reported on R&D team and they are still reviewing
  the final details but please know that currently, there are no
  tentative date for the fix at this time.
For the interim please use the workaround by changing the sharing
  settings.
We do apologize for the inconvenience regarding this concern.
The solution initially provided by SFDC support was to:
  1. You can make the Event_c sharing settings to private BEFORE you install the package. THEN change it back to its original state
  (Controlled by Parent) once done installing.
OR

*

*Rename the object Event_c because it is not recommended to name custom object the same as standard Event object name.

A few comments
- We can't change sharing settings from Controlled By Parent since it is the detail of a master-detail relationship
- Asking the client to change the API Name of one of their local objects is absurd since there can be thousands of dependencies.
- "it is not recommended to name custom object the same as standard Event object name" <- the issue here is not with the standard Event object, it is with a locally created Event custom object and a package Event custom object.  I would love to know how they think we can enforce this "recommendation".


text:
Q: $http.post() does not work - (AngularJS) I am trying to create a form with a dropdown input field and a submit button in AngularJS. Everything works fine except the output is empty xD. I am using . And if it's any help on server side I am using PHP Version 5.5.36-1+donate.sury.org~trusty+1.
Here's the Angular code:
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', function($scope, $http) {
            $scope.myTxt = "You have not clicked submit, yet!";
            $scope.show_result = false;

            $scope.myFunc = function() {
                $scope.myTxt = "You clicked submit!";
                $scope.show_result = true;
            }

            $scope.categories = [
                {"value": 0, "categoryname": "standard"},
                {"value": 1, "categoryname": "premium"},
                {"value": 2, "categoryname": "gold"}
            ];

            $scope.submitData = function() {
                $scope.category = {};
                console.log($scope.category);
                var jsonString = JSON.stringify($scope.category);
                $http.post('ServerController.php', jsonString, {'Content-Type': 'application/x-www-form-urlencoded'})
                        .success(function(data, status) {
                            $scope.status = status;
                            $scope.data = data;
                        });
            }
        });

Here is the ServerController.php :
$jsonString = file_get_contents('php://input');
        $form_data = json_decode($jsonString, true);
        if ($form_data != null) {
            echo 'Success!!!';
            var_dump($form_data);
        } else {
            echo 'Sorry!!!';
            var_dump($form_data);
        }

Here is the HTML:

                <form ng-submit="myFunc()" ng-controller="MainCtrl">
                    Category:
                    <select ng-model="category" ng-options="x.categoryname for x in categories track by x.value">
                        <option value="">Choose a Category</option>
                    </select>

Model: {{category}}

                    <input ng-click="submitData()" type="submit" value="Submit"></input>
                    {{myTxt}}

Submitted result: {{data}}

                </form>

Here is how the form looks on page load:

This is after you select category in the dropdown:

And finally after clicking submit:

Note: The server controller is sending the output in Submitted result ie. Sorry!!!
 array (size=0) empty

Any ideas?


text:
Q: React 0.13.3 can't show a simple thing I'm learning react and doing a small tutorial here. When I refresh the browser i should see text "My Component" but there is nothing. Maybe someone can see what I'm missing.
<!DOCTYPE html>

    <title>React components</title>

A: Looks like you have a syntax error in your React.render line. You used a comma instead of a period in document.getElementById.


text:
Q: Can I answer my own question?
Possible Duplicates:
Should I not answer my own questions?
Should I ask questions I already know the answer to and answer them myself?
Should I ask a question I know the answer to?

This is related to my question Detect Autoscrollposition Value Change In Panel.
Can I answer this question myself? This is an effort to share knowledge.

A: You can answer you own question, and usually even accept it after 2 days
(at least on SO and SF)


text:
Q: ImageMagick: How to apply one gif's per-frame delays to another gif? I have a workflow where I take gifs from a client, convert them from gif to sprite sheets (png) I can work on, then convert them back to gifs to send back.  The Client's frame delays in their gifs are important though, so I need to preserve them.
Is there a way I can grab the frame delays in one gif, and apply them to another gif, using ImageMagick commandline utilities?  I'm doing these through a .bat batch file on windows.  The gifs have the same dimensions and frame counts.

A: In Imagemagick 6, you can use the string format %T to get the animation delay. Put it into a variable and then use the variable for the delay of the next animation. See https://imagemagick.org/script/escape.php
convert -delay 100 rose: rose: rose: -loop 0 anim.gif

convert anim.gif -format "%T\n" info: | head -n 1
100

Note that without piping to head -n 1, Imagemagick will repeat the delay once for each frame.
For Imagemagick 7, use magick rather than convert. In Windows .bat, double the % to %%.
For Windows you may need to find an equivalent tool to head -n 1 or just parse the text output from  %T to extract only one value from all the repeats for each frame.


text:
Q: Spring Data Elasticsearch: Multiple Index with same Document I'm using spring-data-elasticsearch and for the beginning everything works fine.
@Document( type = "products", indexName = "empty" )
public class Product
{
...
}

public interface ProductRepository extends ElasticsearchRepository<Product, String>
{
...
}

In my model i can search for products.
@Autowired
private ProductRepository repository;
...
repository.findByIdentifier( "xxx" ).getCategory() );

So, my problem is - I've the same Elasticsearch type in different indices and I want to use the same document for all queries. I can handle more connections via a pool - but I don't have any idea how I can implement this.
I would like to have, something like that:
ProductRepository customerRepo = ElasticsearchPool.getRepoByCustomer("abc", ProductRepository.class);
repository.findByIdentifier( "xxx" ).getCategory();

Is it possible to create a repository at runtime, with an different index ?
Thanks a lot
Marcel

A: Yes. It's possible with Spring. But you should use ElasticsearchTemplate instead of Repository.
For example. I have two products. They are stored in different indices.
@Document(indexName = "product-a", type = "product")
public class ProductA {

    @Id
    private String id;

    private String name;

    private int value;

    //Getters and setters
}

@Document(indexName = "product-b", type = "product")
public class ProductB {

    @Id
    private String id;

    private String name;

    //Getters and setters

}

Suppose if they have the same type, so they have the same fields. But it's not necessary. Two products can have totally different fields.
I have two repositories:
public interface ProductARepository extends ElasticsearchRepository<ProductA, String> {
}

public interface ProductBRepository
    extends ElasticsearchRepository<ProductB, String> {

}

It's not necessary too. Only for testing. The fact that ProductA is stored in "product-a" index and ProductB is stored in "product-b" index.
How to query two(ten, dozen) indices with the same type?
Just build custom repository like this
@Repository
public class CustomProductRepositoryImpl {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public List<ProductA> findProductByName(String name) {
        MatchQueryBuilder queryBuilder = QueryBuilders.matchPhrasePrefixQuery("name", name);

        //You can query as many indices as you want
        IndicesQueryBuilder builder = QueryBuilders.indicesQuery(queryBuilder, "product-a", "product-b");

        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();

        return elasticsearchTemplate.query(searchQuery, response -> {
            SearchHits hits = response.getHits();
            List<ProductA> result = new ArrayList<>();
            Arrays.stream(hits.getHits()).forEach(h -> {
                Map<String, Object> source = h.getSource();
                //get only id just for test
                ProductA productA = new ProductA()
                        .setId(String.valueOf(source.getOrDefault("id", null)));
                result.add(productA);
            });
            return result;
        });
    }

}

You can search as many indices as you want and you can transparently inject this behavior into ProductARepository adding custom behavior to single repositories
Second solution is to use indices aliases, but you had to create custom model or custom repository too.

A: We can use the withIndices method to switch the index if needed:
NativeSearchQueryBuilder nativeSearchQueryBuilder = nativeSearchQueryBuilderConfig.getNativeSearchQueryBuilder();
// Assign the index explicitly.
nativeSearchQueryBuilder.withIndices("product-a");
// Then add query as usual.
nativeSearchQueryBuilder.withQuery(allQueries)

The @Document annotation in entity will only clarify the mapping, to query against a specific index, we still need to use above method.
@Document(indexName="product-a", type="_doc")


text:
Q: Add a value to a column of DASK data-frames imported using csv_read Suppose that five files are imported to the DASK using csv_read. To do this, I use this code:
import dask.dataframe as dd
data = dd.read_csv(final_file_list_msg, header = None)

Every file has ten columns. I want to add 1 to the first column of file 1, 2 to the first column of file 2, 3 to the first column of file 3, etc.

A: Let assume that you have several files following this scheme:
dummy/
├── file01.csv
├── file02.csv
├── file03.csv

First we create them via
import os
import pandas as pd
import numpy as np
import dask.dataframe as dd
from dask import delayed

fldr = "dummy"

if not os.path.exists(fldr):
    os.mkdir(fldr)

for i in range(10):
    df = pd.DataFrame(np.random.rand(5,3))
    df.to_csv("{}/file{:02}.csv".format(fldr,i+1),
              index=False)

The list of file created is fns = sorted(os.listdir(fldr))
Then we write a function that given the path fn:

*

*read the file

*takes the number XX in fileXX.csv

*insert int(XX) on the first column

That is
def addCol(fn):
    df = pd.read_csv(os.path.join(fldr, fn))
    first = int(fn.split(".")[0][-2:])
    df.insert(0, "first", first)
    return df

We wanted this fun to be delayed and we can achieve it using the decorator @delayed or wrapping the function with delayed. So to obtain the desired output we should fire (accordingly)

*

*ddf = dd.from_delayed([addCol(fn) for fn in fns])

*ddf = dd.from_delayed([delayed(addCol)(fn) for fn in fns])


text:
Q: javascript and jquery functions are not working/exexcuting While inspecting the elements it gives 304 code.and after hitting Ctrl+shift+r
reposnse code is 200.but still it's not working..

<script type="text/javascript">
$(document).ready(function() {
    $("#viewCRM").hide();
    $("#viewSearch").hide();
    $("#viewCamp").hide();
    $("#viewSearchTable").hide();
});
$(function() {

    $(".home").click(function() {
        alert("Opening CRM");
        $("#viewCRM").slideToggle();
        $("#viewSearch").hide();
        $("#viewCamp").hide();
        $("#viewSearchTable").hide();
    });
    $("#camp").click(function() {
        alert("Opening Campaign");
        $("#viewCamp").slideToggle();
        $("#viewCRM").hide();
        $("#viewSearch").hide();
        $("#viewSearchTable").hide();
    });
    $("#search").click(function() {
        alert("Opening Search");
        $("#viewSearch").slideToggle();
        $("#viewCRM").hide();
        $("#viewCamp").hide();
        $("#viewSearchTable").Toggle();
    });
    $("#littleMerit").click(function() {
        $("#viewCamp").hide();
        $("#viewCRM").slideToggle();

    });
</script>

Why is my code not working?

A: End of your script needs a closing }); for the $(function () {. Working code:
<script type="text/javascript">
  $(document).ready(function() {
    $("#viewCRM").hide();
    $("#viewSearch").hide();
    $("#viewCamp").hide();
    $("#viewSearchTable").hide();
  });
  $(function() {
    $(".home").click(function() {
      alert("Opening CRM");
      $("#viewCRM").slideToggle();
      $("#viewSearch").hide();
      $("#viewCamp").hide();
      $("#viewSearchTable").hide();
    });
    $("#camp").click(function() {
      alert("Opening Campaign");
      $("#viewCamp").slideToggle();
      $("#viewCRM").hide();
      $("#viewSearch").hide();
      $("#viewSearchTable").hide();
    });
    $("#search").click(function() {
      alert("Opening Search");
      $("#viewSearch").slideToggle();
      $("#viewCRM").hide();
      $("#viewCamp").hide();
      $("#viewSearchTable").Toggle();
    });
    $("#littleMerit").click(function() {
      $("#viewCamp").hide();
      $("#viewCRM").slideToggle();
    });
  });
</script>

And noticing your code, there are few things:

*

*.Toggle() doesn't look like a jQuery function. Are you trying to use .toggle()?


text:
Q: android read usb asynchronously I'm trying to read a string from Arduino on Android device asynchronously, using a library downloaded here
https://github.com/mik3y/usb-serial-for-android
I managed to do it, but the code works only once and not in a loop cycle.
I've tryed to do it in asyncTask but the program crashes, so i managed to do the cycle by executing a runnable in loop, but the program freezes every time the runnable is executed, and un-freeze when the runnable ends the work.
This is the code used to read from the usb:
try
{
     UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
     driver = UsbSerialProber.acquire(manager);
     if (driver != null) {

            driver.open();
            driver.setBaudRate(9600);
            new Thread(runnable).start();
            buffer = new byte[3000];
                    numBytesRead = driver.read(buffer, 3000);
                String str = new String(buffer, "UTF-8");
                buffer = null;
                numBytesRead = 0;
        }
}
catch(Exception ex){//do nothing}

I structured the runnable to be executed this way:
@Override
protected void onCreate(Bundle savedInstanceState) {
try
{
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
     driver = UsbSerialProber.acquire(manager);
     if (driver != null) {

            driver.open();
            driver.setBaudRate(9600);
            handler.postDelayed(runnable, 1);
        }
}
catch(Exception ex){//do nothing}
}

private Runnable runnable = new Runnable() {
       @Override
       public void run() {
           try {
                buffer = new byte[3000];
                numBytesRead = driver.read(buffer, 3000);
                String str = new String(buffer, "UTF-8");
                buffer = null;
                numBytesRead = 0;
            handler.postDelayed(this, 1);  //here is where the runnable is executed again. This generates the loop
              }
        catch (IOException e) {//do nothing}
       }
    };

Hope you can help!

A: Solved!
I changed the parameter 1 in
handler.postDelayed(runnable, 1);

and
handler.postDelayed(this, 1);

to
handler.postDelayed(runnable, 0);
handler.postDelayed(this, 0);

and also i've changed the buffer size here:
buffer = new byte[3000];
numBytesRead = driver.read(buffer, 3000);

from 3000 to 40, that's the reason why the program was so slow.
Thank you anyway!


text:
Q: java jsoup get text fail I am very new in java jsuop
I want to get the last price in follow line:
http://www.aastocks.com/en/forex/quote/quote.aspx?symbol=NZDHKD&process=y
and i have the follow code:
Elements answerers = document.select("div.content div.inline_block.vat.float_l div.boxForex div.font26 span.neg");
But it return an error:
java.net.SocketTimeoutException: Read timed out
I think i am wrong at the  "document.select" part, can someone help me?
Many thanks.

A: The response from the server takes too long, so the default timeout is reached and an exception is thrown:

If a timeout occurs, an IOException will be thrown. The default
  timeout is 3 seconds (3000 millis).

So just set a higher timeout:
Example Code
String url = "http://www.aastocks.com/en/forex/quote/quote.aspx?symbol=NZDHKD&process=y";
String userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36";

try {
    Document doc = Jsoup.connect(url).userAgent(userAgent).timeout(5000).get();
    System.out.println(doc.select("div.content div.inline_block.vat.float_l div.boxForex div.font26 span.neg").first().text());
} catch (IOException e) {
    e.printStackTrace();
}

Output
5.6813


text:
Q: auth_user.username gives 'NoneType' object has no attribute 'username' so im trying to save a sqlform to be saved with the user that filled the form.
db = DAL("sqlite://storage.sqlite")
db.define_table('Pedido',
            Field('Usuario',default=auth.user.username,readable=False, writable=False),
            Field('Nome','string'),
            Field('Telefone', 'string',),
            Field('Email', 'string'),
            Field('CEP','string'),
            Field('Rua', 'string'),
            Field('Tipo_de_cliente',requires=IS_IN_SET(['Cliente Fisico', 'Cliente Juridico'])),
            Field('Tipo_de_servico', requires=IS_IN_SET(['Reparo', 'Ajusto', 'Confecção','Outros'])),
            Field('Tipo_de_peca', requires=IS_IN_SET(['Camisa', 'Jaqueta', 'Saia','Calça','Vestido','Shorts','Camiseta'])),
            Field('Descricao', 'text'),
            Field('Data_de_recebimento_do_pedido','date'),
            Field('Data_de_entrega','date'),
            Field('Valor','double'),
            Field('Tipo_Pagamento',requires=IS_IN_SET(['Dinheiro','Cartão','Cheque'])),
            Field('Pago','boolean'))

with the above code only allow me to save the form if the user is logged otherwise it gives
'NoneType' object has no attribute 'username'

and my controller
@auth.requires_login()
def pedido():
Pedido = SQLFORM(db.Pedido)
Pedido.element('input[type=submit]')['_onclick'] = "return confirm('Deseja salvar?');"
if Pedido.process().accepted:
    response.flash = 'Salvo com sucesso'
return dict(Pedido=Pedido)

i already look all over and with every answer it just dont work,
anyone has the solution for this error? wherever i logout which i cant login again i must comment the usuario field so im able to login again

A: auth.user is the record of the currently logged in user, so it is None when no user is logged in. You can change your code as follows:
Field('Usuario', default=auth.user.username if auth.user else None)


text:
Q: How can i customize toolbar button in Extjs using Compass/Saas? I want to customize toolbar button theme in Extjs using Compass/Sass in order to eliminate the gradient effect.
@include extjs-button-ui(
        'my_button',

        $background-gradient:null,
        $background-gradient-over:null,
        $background-gradient-focus:null,
        $background-gradient-pressed:null,
        $background-gradient-disabled: null
);

But it returns compass compile error :
WARNING: @theme-background-image: Theme image not found: ../images/btn/btn-topbar_button-corners.gif
         on line 18 of /Users/user/Documents/workspace/sihalon/war/extjs/resources/themes/stylesheets/ext4/default/mixins/_theme-background-image.scss

WARNING: @theme-background-image: Theme image not found: ../images/btn/btn-topbar_button-sides.gif
         on line 18 of /Users/user/Documents/workspace/sihalon/war/extjs/resources/themes/stylesheets/ext4/default/mixins/_theme-background-image.scss

    error my-ext-theme.scss (Line 693 of _button.scss: Invalid null operation: "null plus 4px".)
overwrite ../css/my-ext-theme.css

A: You must put
$icon-size:16px,

For example:
@include extjs-button-ui(
'yellow',
$background-color:yellow,
$icon-size:16px,
$font-size:18px
);

A: Shuold use none for no gradient;
For example:
@include extjs-button-ui(
        'my_button',

        $background-gradient:none,
        $background-gradient-over:none,
        $background-gradient-focus:none,
        $background-gradient-pressed:none,
        $background-gradient-disabled: none
);


text:
Q: Laravel Sanctum: Machine-to-Machine I've previously implemented Laravel Passport for validating users of an API.
I'm currently looking to use Laravel Sanctum. This will not be for validating users but for validating machine to machine interactions (i.e. API to API).
I've read through the documentation here: https://laravel.com/docs/8.x/sanctum
The above documentation is focussed around generating tokens for users upon logging in. This application has no users and simply needs to generate API tokens for machine to machine authentication.
How would a token be generated without users?

A: For Machine, to Machine, you have to use Laravel Passport.


text:
Q: Disabling a specific warning in a specific line in Xcode I'm writing an iPhone app against the Base 4.0 SDK, but I'm targeting OS 3.1.3 so OS 3 users can use the app.
I call:
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];

which is deprecated in iOS 4.0. I'm aware of this, and have measures in place to call the newer "withAnimation" version if we are running under iOS 4.0 or greater.
However, I'm getting a warning that I'm calling a deprecated SDK.
I'd like to disable this specific warning in this specific place. I want all other warnings (including the same deprecated warning in other locations)
Can this be accomplished in Xcode?

A: For CLANG, this works:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  // Here I like to leave a comment to my future self to explain why I need this deprecated call
  NSString *myUDID = [[UIDevice currentDevice] uniqueIdentifier];
#pragma clang diagnostic pop

You can use it inside a method, which allows you to be very specific about the line that causes the warning you want to have ignored.

A: You can use NSInvocation to get around the warnings independent of the compiler used:
UIApplication *app = [UIApplication sharedApplication];
SEL sel = @selector(setStatusBarHidden:animated:);
NSMethodSignature *sig = [app methodSignatureForSelector:sel];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];
BOOL b = YES;
[inv setTarget:app];
[inv setSelector:sel];
[inv setArgument:&b atIndex:2];
[inv setArgument:&b atIndex:3];
[inv invoke];

Or in a less error-tolerant way:
UIApplication *app = [UIApplication sharedApplication];
SEL sel = @selector(setStatusBarHidden:animated:);
IMP imp = [app methodForSelector:sel];
imp(app, sel, YES, YES);

A: you can perform it like this to overcome the warnings at once
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
(void) methodUsingDeprecatedStuff { //use deprecated stuff }

or
Just paste this line before using your deprecated stuffs every time to avoid warnings
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
this will remove the warnings.
Hope it will help you.

A: You might be able to use GCC pragmas. This should disable the deprecated warning for the enclosed function.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
-(void)foo{
    // As Georg Fritzsche notes below, the pragmas only work outside of functions
    [[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];
}
#pragma GCC diagnostic pop

I don't know if this will work with Clang, but it should work with GCC.
Basically, it saves the state of the warnings/errors, disables the deprecated warning, compiles the function, then restores the state of the diagnostics.


text:
Q: Create 2d array in javascript I have problem creating 2d array in javascript. Here is my code:
var arr = new Array([]);
arr[0][0] = "1st data from array";
arr[1][0] = "2nd data from array";
document.write(arr[0][1] + " " + arr[1][0]);

What I should do to make it work?

A: You need to initialize an item in arr before setting arr[i][x]:
var arr = new Array([]);
arr[0] = arr[1] = [];
arr[0][1] = "1st data from array";
arr[1][0] = "2nd data from array";
document.write(arr[0][1] + " " + arr[1][0]);

A: It will throw an error because arr[0] and arr[1] are not set to be arrays yet. Try:
var arr = [[],[]];


text:
Q: Avoid shell=True with command line arguments in python I want to run inside my test.py script a shell command line which takes a couple of arguments. The test.py is run as:
python test.py filename file_2 int

The test.py looks inside analogous to this:
import sys

filename = sys.argv[1]
file_2 = sys.argv[2]
num = sys.argv[3]

subprocess.call("xargs /bin/bash  build/install/programme/bin/programme option -n "+num+" --csv-file="+str(filename)+" -c files/"+str(file_2)+ "< /tmp/my_ids_"+str(file_2)+"_"+str(num),shell=True)

The point is that I want to avoid using shell=True, but all the options I found so far do not provide a good solution for the arguments I am adding in the command line.
So far I have tried different options via splitting it with Popen, as for example:
import sys

filename = sys.argv[1]
file_2 = sys.argv[2]
num = sys.argv[3]

subprocess.Popen(["xargs","/bin/bash","build/install/programme/bin/programme","option","-n", str(num),"--csv-file=",str(filename),"-c","files/",str(file_2),"<",str("/tmp/my_ids_"+str(file_2)+"_"+str(num))])

But I got no working results. Also tried with shlex, but again in the documentation I saw no options for being able to add arguments in the command.
Thanks in advance for your help!

A: Your original code was equivalent to running the following bash command:
xargs \
  /bin/bash \
  build/install/programme/bin/programme \
  option \
  -n            "$int" \
  "--csv-file=" "$filename" \
  -c            "files/"           "${file_2}" \
  '<'           "/tmp/my_ids_${file_2}_${int}"

That wouldn't have worked either, and for all the same reasons.

import sys

filename = sys.argv[1]
file_2 = sys.argv[2]
num = int(sys.argv[3])

subprocess.Popen([
  "xargs",
  "/bin/bash",
  "build/install/programme/bin/programme",
  "option",
  "-n", str(num),
  "--csv-file=%s" % filename,
  "-c", "files/%s" % file_2,
], stdin=open("/tmp/my_ids_%s_%s" % (file_2, num), 'r')

Note the differences:

*

*A single argument is always passed as a single list member. That means --csv-file=filename is all one thing, and that the prefix files/ and the string contained in the variable file_2 need to be passed within the same list element.

*Redirections (<) are instructions to the shell, not arguments to your program. You thus can't use them here, but should use other options (such as the stdin and stdout arguments to Popen) to simulate their effect.

*int is the name of the integer type; using the variable name num keeps the original name available.


text:
Q: $\sum_{i = 1}^{n} f(\xi_{n})\Delta x_{i}$ notation explanation This task comes from my text book, can someone help me solve it, please?

Let $$R_{n} = \sum_{i = 1}^{n} f(\xi_{n})\Delta x_{i} =
> f(\xi_{1})\Delta x_{1} + f(\xi_{2})\Delta x_{2} + f(\xi_{3})\Delta
 x_{3} + ...+f(\xi_{n})\Delta x_{n}$$ be a Riemann sum of a function
  $f$. Explain the notation and provide the assumptions for:

*

*$\Delta x_{i}$ -

*$\xi_{i}$ -

*$f(xi_{i})$ -

*$n$ -

*$f$ is -

Can someone help me solve this theory task?
My attempt following the same order:

*

*$\Delta x_{i} = x_{i} - x_{i - 1}$ - partition of equal size, the length of subinterval

*$\xi_{i} \in [x_{i-1}, x_{i}]$

*$f(xi_{i}) - $ no idea

*$n $ is a number of subintervals

*f is continuous (?)

Can someone help me fix it? The text book left little space to fill, so I expect something basic is required from me.
Thank you.

A: I think that $f(xi_{i})$ means $f(\xi_i)$, the value of $f$ at the point $\xi_i.$
$f$ should be Riemann - integrable.
The rest of your answers is o.k.

A: No, the $Δx_i$ need not have equal length. The partition of the interval $[a,b]$ is given by the points $x_i$ with
$$
a=x_0<x_1<...<x_n=b.
$$
Yes to $\xi_i\in [x_{i-1},x_i]$ and $f(\xi_i)$ being the function values.
There is nothing more to this sum, and all these properties come from the "Riemann" in "Riemann sum".

If you want the discussion to extend to the Riemann integral, then you need to add the bounded total variation of $f$ and that the maximal interval length of the subdivision goes to zero.

As to the $\xi_i$, Riemann starts his exploration of the integral with a continuously differentiable function $F$ and the mean value theorem
$$
\frac{F(x_i)-F(x_{i-1})}{x_i-x_{i-1}}=F'(\xi_i)
$$
for some $\xi_i\in (x_{i-1},x_i)$. In reversing this he found
$$
F(b)-F(a)=\sum_{i=1}^n F'(\xi_i)Δx_i.
$$
Then he turned this around and asked for the condition that, replacing $F'$ with $f$, these sums for infinitesimal partitions will all give the same result in the limit of the partition sub-interval lengths going to zero.
See chapter 4 in Bernhard Riemann (1867): "Ueber die Darstellbarkeit einer Function durch eine trigonometrische Reihe."


text:
Q: No keyboard is recognized at POST My motherboard is ASUS PRIME Z270-AR.
I have a USB keyboard that works fine in the OS. I've also tried a PS/2 keyboard without luck.  I was able to reach the BIOS last summer.  I think I've updated firmware since I last accessed the BIOS, so maybe the new version is broken?
Here's a list of things that have been attempted:

*

*made sure Fast Startup is turned off

*2 different USB keyboards

*switched current keyboard's polling switch to BIOS

*USB to PS/2 connector on a USB keyboard

*an old PS/2 keyboard

*disconnected the CPU fan from the motherboard (attempting to force BIOS)

*removed CMOS battery

*tried advanced startup, but no UEFI option was available

A: For this specific motherboard, the solution was updating the BIOS.  At some point, something changed that prevented the keyboard from working.  I never found out why or if it could be fixed, but updating the BIOS got rid of the problem.


text:
Q: What is a name of System.runAs construction As I know Apex is a combination of Java and C# languages (maybe this list should contain more languages).
Speaking about System.runAs, documentation says that it is a method. It looks like it is a static method of System class. But how can then we send written code in block of this method?
System.runAs(u){
    //any lines of code are here
}

Normally we can't pass code lines to method, so it doesn't look like method. So we can't call System.runAs as "method".
I didn't find something relevant in Java. Is it an anonymous method, implementation of some interface with anonymous class? Is it something specific only for Apex ?
What is a name of construction System.runAs(u){} ?

A: EDIT: In C# they're just called "statements". See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement


text:
Q: Casting into grouping row I dont know why i am getting the following exception how can I cast into grouping Row ? What does grouping row means

A: Quick answer: change the code to
foreach(var InvoiceHeader in InvoiceHeadercollection)

The linq code has generated a new class, which you can think of like this:
class AutoGeneratedClass :  IEnumerable<DataRow>
{
    public string Key { get; }  // The InvoiceAccount field
}

(It's not called "AutoGeneratedClass"; I'm just using that so it follows the syntax we know). Because there's no name for this automatically generated class, you have to use "var".

A: Look at your LINQ query, you are using group by  - InvoiceHeaderCollection is not a collection of data rows, it's an IGrouping<DataRow>, a different group for each different "Invoice account".
 - what did you want to do with the grouping? Or did you intend to order your rows by Invoice account?

A: InvoiceHeaderCollection is a collection of groups, the groups is something like:
      Key               Value
 invoice account1      datarow1 //the value is a `DataRow`
                       datarow2
                       datarow4
 invoice account2      datarow3
 invoice account3      datarow5

So I think you need:
foreach(var g in InvoiceHeaderCollection)
{
    DataRow[] rows = g.ToArray();   //to get all the DataRows in the group
    //maybe another loop through the rows
}


text:
Q: How to turn off "REAL" PCIe power for a GPU device on Llinux I want to turn off "REAL" PCIe power for a GPU device on Linux.
I found some home pages, but they could not cut the "REAL" power.
I monitored the AC power usage, but all of them could not cut the real power usage. Could you tell me how to turn off PCI power for a device?
The followings are the methods I tired.
Method.1
Turn off
# echo "0" > /sys/bus/pci/slots/"SLOT No."/power
turn on
# echo "1" > /sys/bus/pci/slots/"SLOT No."/power

Method.2
Unbind. 0000:0c:00.0 is device ID.
# echo -n "0000:0c:00.0" > /sys/bus/pci/drivers/"DEVICE NAME"/unbind
Bind.
# echo -n "0000:0c:00.0" > /sys/bus/pci/drivers/"DEVICE NAME"/bind

Method.3
Remove. 0000:0c:00.0 is device ID.
# echo "1" > /sys/bus/pci/devices/0000\:0c\:00.0/remove
Recover.
# echo "1" > /sys/bus/pci/rescan

I confirm that ASPM (Active State Power Management) is supported on the BIOS and effective on Linux. The Linux is booted with "pcie_aspm=force" kernel option.

A: You can't. The hardware to do that doesn't exist -- on all normal PC hardware, PCIe slots receive power whenever the computer is running.
Cutting off power to individual PCIe slots would require a significant amount of additional power management hardware on PC motherboards. None of this hardware would ever be used in normal operation, so there would be no benefit to the added cost (and hardware complexity) of such a design.


text:
Q: Git и GitHub на windows от новичка
*

*
Обязательно ли надо иметь repo на GitHub.com (или другом подобном хостинге)? Над проектом работаю один на компьютере и нетбуке, поэтому GitHub мне не нужен. (Возможно спросите зачем мне тогда Git. Отвечаю: а)интересно б)нужно знать в этом мире хотя бы одну систему контроля версий в)для удобства)

*
Взаимодействие между всеми repo происходит одинаково? Например, есть ли разница между взаимодействием repo на одном компьютере с repo на другому компьютером и repo на компьютере с repo на GitHub?

*
GitHub предоставляет свою программу GitHub. Для чего это программа? Она обязательна для работы с repo на GitHub.com?. Я так понимаю, эта программа нужна, чтобы работать с repo на GitHub.com и для упрощения взаимодействия Git'а с repo на GitHub.com. Так?

*
Как лучше работать с Git: с GUI или через Bash или еще что-то? А как проще? Наверняка будут аргументы и за GUI и за Bash или еще что-то. Ведь не зря существуют разные варианты.

*
Допустим есть repo для своего проекта на GitHub. Создан проект в MS VisualStudio. Где должен находиться repo на компьютере? В папке с проектом? А какие обычно файлы попадают в repo? Все файлы? Только файлы кода? Файлы кода и ресурсы (картинки, видео и т.д.)? Или еще что-то?

*
Как проходит обычный процесс работы над проектом? Допустим, поработал над проектов в MS Visual Studio. Теперь надо зайти в Git (GUI или Bash) и там закоммитить все изменения. Так?

*
В Git Bash на windows не работает ни Ctrl+V, ни ПКМ+вставить. Непонятно как работать с редактором, который открывается после выполнения команды git commit. Как сохранить запись в этом редакторе? Если есть 2 или более коммита и если написать git log -p -2, то покажет только первый коммит, на втором остановится и надо что-то ввести, иначе ничего нельзя сделать. Откуда узнать что надо вводить? Это вообще все так и должно быть? Как с этим "бороться"? Есть ли нормальная альтернатива Git Bash?

*
Почему в заголовке Git Bash написано "MINGW32:~"?

A: *

*Можно не иметь. Но лучше иметь, там ваш проект защищён, и никуда не денется. А пользоваться git-овым репозиторием локально для проекта, даже без удалённого репозитория — отличная идея.

*Не совсем понятен вопрос. Попробуйте разобраться с тем, что такое локальный и удалённый (remote) репозитории, тогда вам будет более понятна разница между репозиторием из папки .git и github'ом (или любым другим git сервером).

*Совсем не обязательно. Рекомендую изучить работу с командной строкой.

*Что удобнее — каждый выбирает для себя сам. Но есть случаи, когда без командной строки не обойтись.

*Локальный репозиторий находится в подпапке .git вашего проекта. В него попадают все файлы, которые вы туда добавите. Если какие-то файлы или папки не должны туда попадать, например, скомпилированные двоичные файлы, то их можно исключить, занеся их в файл .gitignore.

*Так. Иногда даже лучше это делать чаще. Ведь предыдущий коммит можно дополнить. А вот испорченный код можно откатить только до состояния предыдущего коммита (когда Ctrl+Z уже не помогает). Изучите ветки — это так же просто, как копировать папку проекта целиком в папки вида backup1, но гораздо удобнее.

*Попробуйте воспользоваться средней клавишей мыши для вставки, предварительно убедившись, что вы можете впечатывать туда с клавиатуры. Либо нажмите Esc и потом P. Редактор для коммитов предполагает, что вы знакомы с редактором Vim и его сочетаниями клавиш. Записать будет ZZ, добавить строку - o, перейти из режима ввода текста в командный - Esc, обратно - a, i или o. Если не умеете пользоваться редактором, пользуйтесь заданием сообщения для коммита через командную строку, вот так:
git commit <file> -m 'здесь сообщение коммита'

Если есть 2 или более коммита и если
  написать git log -p -2, то покажет
  только первый коммит, на втором
  остановится и надо что-то ввести,
  иначе ничего нельзя сделать.

Можно проматывать стрелочкой вниз или клавишами J/K, можно искать клавишей /.

Есть ли нормальная альтернатива Git Bash?

bash тут в общем-то ни при чём. Основные команды редактора Vim знать полезно, они работают во многих стандартных утилитах (less, man и т.п).


text:
Q: androidx.compose.ui.tooling.preview.PreviewActivity is not an activity subclass or alias I updated my compose and kotlinCompilerExtensionVersion to 1.0.0-rc02 from beta09, Kotlin  version to 1.5.21, Gradle version to 7.1 and Gradle plugin version to 7.1.0-alpha04
Ever since - on trying to run MyScreen - I'm getting this error:

androidx.compose.ui.tooling.preview.PreviewActivity is not an activity
subclass or alias

I am not able to resolve this. How do I resolve this?

A: I'm experiencing this error using Bumblebee (AKA, 2021.1.1) Canary 6, 7, and 8, using compose version 1.0.0, 1.0.1, and 1.1.0-alpha01. I've just raised a bug on the Studio issue tracker:
https://issuetracker.google.com/issues/196248459
To quote myself:

It seems clear this is a "left hand doesn't know what right hand is doing" thing, because PreviewActivity is not in that package, but rather androidx.compose.ui.tooling – it hasn't been in android.compose.ui.tooling.preview since compose 1.0.0-beta09.

UPDATE
I was able to get previews working again by clearing off all the preview run configurations. Here were my steps:

*

*Click on the "run configurations" selector and select Edit Configurations...

*Expand the Compose Preview grouping

*Select all the preview configurations (you can select the first and shift-select the last)

*Click the - button to remove all the collections

*Click Ok

*Run Invalidate Caches... in the file menu

*After AS restarts and your cache repopulates, run a preview. It should work now.

Apparently AS was caching "junk" in the temporary run configurations it was creating every time I launched a preview. The "junk" was valid for earlier versions of AS, but broke later versions. Clearing out this cache got me working again.

A: I've got the same error with Compose 1.0.0 and Kotlin 1.5.10 (which is recommended).

I fixed these with adding the following dependence debugImplementation "androidx.compose.ui:ui-tooling:$compose_version" in my gradle file.
Don't forget to set the version of the dependence to your current compose version.

After a rebuild and reload of the preview everything works fine for me.
The Preview of the example looks like this:
package com.example.compose.basics.ui

import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import de.db.dbs.travio.compose.basics.themeing.ComposeBasicsTheme

@Preview
@Composable
fun ScreenContent() {
    ComposeBasicsTheme {
        Card(modifier = Modifier
                .padding(8.dp)
                .shadow(8.dp, RoundedCornerShape(32.dp))
        ) {
            Text(
                    text = "Hello World!",
                    modifier = Modifier.padding(16.dp)
            )
        }
    }
}

A: I am using Compose 1.0, Kotlin 1.5.10 and Android Studio 2020.3.1, and I run into the same problem on most of my previews (not on others).
On the top bar menu, clicking on "Edit configurations" and manually creating a new configuration with the same parameters as those in the invalid configuration with warning (" androidx.compose.ui.tooling.PreviewActivity is not an Activity subclass or alias") did the trick for me.

A: The thing that worked for me was downgrading the ui-tooling version to beta09, i.e using this dependency for ui-tooling:
implementation "androidx.compose.ui:ui-tooling:1.0.0-beta09"

A: Updating the compose_version to 1.0.1 , and kotlin-gradle-plugin to 1.5.21 fixes the issue if the versions used are lower than mentioned here.


text:
Q: Firebase Cloud Function - Create Triggers after delete I am using Firebase Database in my app and have a cloud function trigger for on update and create.
I have a scenario in app where data created and than deleted in app
when internet offline and later when connected to internet somehow the create event in cloud function is triggered and i am updating some common fields but while it gets updated / before it gets updated the delete action in queue from app occurs and later that ref child remains only with the updated keys.
I want to terminate create event ongoing async code in Cloud Function if delete is occurred.
Hope i explained my scenario clearly. if any confusion please ask in comments.
Thank You in advance.


text:
Q: HTML5 Video (mp3) disappears if not hovering over IE I have a  object with an mp3 source.  In Internet Explorer 11, the video player is shown for a few seconds on page load, but then disappears. It reappears when hovering over it.  How do I get it to stay visible all the time?
It is always visible in Firefox.
The html page is auto created and I am stuck with using video instead of audio but I do have control over JS on the page.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>

</head>
<body>
<VIDEO SRC="../media/439.mp3" CONTROLS="controls" WIDTH="400"></VIDEO>

</body>
</html>

A: In your case it is more correct and semantic to use the <audio> tag (it works the same way and has pretty much the same properties as the <video> tag). You should set the width: 400px and the display: inline-block via css, doing this should work normally, here is an example:
HTML:
<audio src="../media/439.mp3" controls="controls"></audio>

CSS:
audio{
    width: 400px;
    display: inline-block;
}

Edit: You can use the video tag too, but it's not the right one

A: This is my quick fix... not perfect, but it does the job.
$('video').each(function() {
    if ($(this).attr('src').toLowerCase().indexOf('.mp3') >=0)
    {
        var attrStr = $(this)[0].outerHTML;
        $(this).replaceWith($('<audio '+attrStr + '>' + this.innerHTML + '</audio>'));

    }
});


text:
Q: Flutter Checkbox not changing/updating/working I am trying to learn checkboxes in Flutter.
The problem is, when I want to use checkboxes in Scaffold(body:) it is working. But I want to use it in different places like an item in ListView.
return Center(
    child: Checkbox(
  value: testValue,
  onChanged: (bool value) {
    setState() {
      testValue = value;
    }
  },
));

But it is not working, updating and changing anything.
Edit: I solved my problem with putting checkbox in a StatefulBuilder. Thanks to @cristianbregant
 return StatefulBuilder(
    builder: (BuildContext context, StateSetter setState) {
  return Center(
    child: CheckboxListTile(
      title: const Text('Animate Slowly'),
      value: _valueCheck,
      onChanged: (bool value) {
        setState(() {
          _valueCheck = value;
        });
      },
      secondary: const Icon(Icons.hourglass_empty),
    ),
  );
});

A: Try these maybe:
return Center(
  child: CheckboxListTile(
    title: const Text('Animate Slowly'),
    value: _valueCheck,
    onChanged: (bool value) {
      setState(() {
       _valueCheck = value;
      });
    },
    secondary: const Icon(Icons.hourglass_empty),
  ),
);

and remember that if you are using it in a dialog or bottomsheet you need to wrap the Checkbox Widget in a Stateful builder because the state does not update.

A: Checkboxes require you have a Scaffold or Material as their parent. Without either of these, you get this helpful error message:
The following assertion was thrown building Checkbox(dirty, state: _CheckboxState#1163b):
No Material widget found.

Checkbox widgets require a Material widget ancestor.
In material design, most widgets are conceptually "printed" on a sheet of material.
In Flutter's material library, that material is represented by the Material widget. It is the Material widget that renders ink splashes, for instance. Because of this, many material library widgets require that there be a Material widget in the tree above them.

Once you have a material ancestor, you can place the ListView as it's child and it should show fine:
class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  var _foo = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Toggle Foo'),
              Checkbox(
                value: _foo,
                onChanged: (bool value) {
                  setState(() => _foo = value);
                },
              ),
            ],
          ),
        ],
      ),
    );
  }
}

A: Seems like you will have to use both initState and dispose.
See my code example below:
class SettingsOrder extends StatefulWidget {
  @override
  _SettingsOrderState createState() => _SettingsOrderState();
}

class _SettingsOrderState extends State<SettingsOrder> {

  List options = [];
  List<bool> newoptions = [];
  int selectedoption;
  bool checkedstatus;
  bool initialcall;

Future getproductlist(selectedoption, checkedstatus, initialcall) async{

    List updatedlist = [];

    final arguments = ModalRoute.of(context).settings.arguments as Map;
    int itempos = 0;
    options.clear();

    if(initialcall == false){
      for(var item in arguments['options']){
        updatedlist.add({
          'checkbox' : newoptions[itempos]
        });
        itempos++;
      }
    } else {
      for(var item in arguments['options']){
        updatedlist.add({
          'checkbox' : checkedstatus
        });
        newoptions.add(false);
        itempos++;
      }
    }

    setState(() {
      options = updatedlist;
    });

  }

  @override
  void initState(){
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    getproductlist(0, false, true);

    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
           width: double.infinity,
           child: ListView.builder(
             primary: false,
             shrinkWrap: true,
             itemCount: options.length,
             itemBuilder: (BuildContext context, int index){
              return Container(
                child: Theme(
                  data: ThemeData(
                    unselectedWidgetColor: Colors.grey
                  ),
                  child: CheckboxListTile(
                    controlAffinity: ListTileControlAffinity.trailing,
                    title: Text(options[index]['name']),
                    value: options[index]['checkbox'],
                    onChanged: (newvalue){
                      int indexposition = index;
                      newoptions.removeAt(indexposition);
                      newoptions.insert(indexposition, newvalue);
                      getproductlist(indexposition, newvalue, false);
                    },
                    activeColor: Color.fromRGBO(0, 130, 214, 1),
                    checkColor: Colors.white,
                  ),
                ),
               );
              }
            ),
           ),
          ),
       );
}


text:
Q: BufferedImage setRGB: Image gets squished down to quarter size I have a one dimensional integer array of rgb values that I need to feed BufferedImage and then use that to generate a jpeg. I have 128*128 pixels, which I'm stepping over using setrgb (I tried passing buffered image the array in one go, ran into trouble and well, that's a separate question)
       int numRows = 128;
       int numCols = 128;
       int inputIndex = 0;
       BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
       for(int row = 0; row < numRows; row++){
           for(int col = 0; col < numCols; col ++){
               int rgb = rgbvals[inputIndex++];
               rgb = (rgb << 8) + rgbvals[inputIndex++];
               rgb = (rgb << 8) + rgbvals[inputIndex++];
               image.setRGB(col,row, rgb);
           }
       }
       File outputFile = new File("output.jpg");
       ImageIO.write(image, "JPEG", outputFile);

This looks rather straightforward, but my image looks like this:
128*128 picture of an eye, except it takes up 1/4 the space it needs and the rest of the image is black
I feel like I might have overlooked a small detail. I'd appreciate any insight, thanks!

A: This was actually a silly mistake, I only needed to call the BufferedImage constructor with numRows and numCols correctly, instead of the other variables I used(width, height referred to something else).
This fixed it.


text:
Q: How to handle amount of data in Web API? I am new to web api and I have some problem with my web api. I have created an web api with sql server, but i did not used entity framwork, it is kind of old way to connect sql server database to web api.
The problem for now is my sql server database have more than ten thousand records and when i run my web api in google chrome and it showed out of memory in google chrome. I do not know why it will out of memory, those records are less than 200mb, it should not out of memory. I have though about my codes are wrong in somewhere, does anyone know how to solve it?
web api codes with data table:
public SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString);

        [HttpGet]
        public IHttpActionResult GetAll()
        {
            List<webapi> web = new List<webapi>();
            SqlCommand cmd = new SqlCommand("SELECT UserID, Name, Address, Mobile, Birthday From tbluser", connection);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            sda.Fill(table);
            foreach(DataRow read in table.Rows)
            {
                web.Add(new webapi
                {
                    UserId = Convert.ToString(read[0]),
                    Name = Convert.ToString(read[1]),
                    Address = Convert.ToString(read[2]),
                    Mobile = (read[3] != DBNull.Value) ? Convert.ToInt32(read[3]) : 0,
                    Birthday = (read[4] != DBNull.Value) ? Convert.ToDateTime(read[4]) : (DateTime?)null
                });
            }
            return Ok(web);
        }

web api codes with data reader:
public SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString);

[HttpGet]
        public IHttpActionResult GetAll()
        {
            List<webapi> web = new List<webapi>();
            SqlCommand cmd = new SqlCommand("SELECT UserID, Name, Address, Mobile, Birthday From tbluser", connection);
            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                web.Add(new webapi()
                {
                    UserId = sdr.GetString(0),
                    Name = sdr.GetString(1),
                    Address = sdr.GetString(2),
                    Mobile = (sdr.GetValue(3) != DBNull.Value) ? Convert.ToInt32(sdr.GetValue(3)) : 0,
                    birthday = (sdr.GetValue(4) != DBNull.Value) ? Convert.ToDateTime(sdr.GetValue(4)) : (DateTime?)null
                });
            }
            return Ok(web);
        }

I also made two version of get method which used data table and data reader to get data.
Class:
public class webapi
    {

        public string UserId { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }

        public int Mobile { get; set; }

        public DateTime? Birthday { get; set; }
    }

A:
I do not know why it will out of memory, those records are less than 200mb, it should not out of memory.

You don't pay this price only once. Especially locally. Here's what is happening:
Your database loads the data from disk to memory. This likely is streamed to the C# server. Either way the data needs to be serialized, send via sockets, read on the C# server side and deserialized into data. Since C# memory is managed, the data stays in memory until the garbage collector clears it. And we don't know when and how it will happen. It is likely that at least each separate webapi object will stay in memory for some unspecified time. Also the C# runtime rarely releases the memory back to OS. Another thing is that the database typically keep objects in a compact way, while C# class layout is less compact to allow better performance. It is likely that on C# side they weight a lot more than 200mb.
Next you send all those objects to the browser. This means data serialization, which by default is Json. So you take all those 200mb+ and now you turn that into Json string. The json serialization is really inefficient compared to binary database serialization formats. This can be many, many times more, depending on the data patterns. For example every Json object comes with field names.
You then send that data over the wire and read it on the browser side. Since Json is not streamable format, it has to be read entirely before it can be deserialized. It means that the browser has to keep buffering the data in memory, meaning you pay the full price at least on the browser side (possibly on the server's side as well, not sure). And then you pay for deserialization in js, and then you pay for generating and reneding html.
By rough calculations, if everything run locally, we get:

*

*say 250mb after loading in C#

*say 750mb after serializing into json

*250mb after deserialization in browser

*at least 250mb after rendering (probably many times more if fancy html + styling)

All in all you get 1.5 Gb (1.25 Gb on the client side), probably much more.

does anyone know how to solve it?

You could fix your serialization and deserialization to minimize all the prices you pay.
But the proper solution is to send data in small chunks. You really don't want a user to go through thousands of records, that is not user friendly. And risky (e.g. denial of service attack).
You really should implement pagination. Meaning your endpoint should accept "page" parameter and then you should send chunks of data in [page*page_size, (page+1)*page_size] range.

A: In your case, I think It is better to use OFFSET to fetch a huge amount of data into chunks from the database.
So try to use LIMIT OFFSET instead of selecting all rows, that could solve your issue.


text:
Q: Evolution - imported signatures not used Evolution 3.28.0-4 on Debian Testing.
I did a restore of my evolution-config, copied ~/.config/evolution from backup to my machine. The email-accounts and all the emails are fine.
For each account there is a signature assigned - I can see this in settings. But the signatures are not attached to the emails I write.
In ~/.config/evolution/signatures I see four files (hashes as names) with html-code of signatures inside.
Any ideas how to "activate" those signatures, to be attached to my emails?
Best regards
Johannes

A: Solved!
The signature-files had wrong file-permissions. They had 755 instead of 644!
Just did a chmod 644 056xxxxxxxxxxxxxxxxxxx and the signature worked immedently.
Best regards


text:
Q: memsql_platform.network.state.primary_state.primary_poll: Failed to lookup local agent I am trying to install MemSQL 4.1.7 on a RHEL 6 machine in offline mode following the instructions:
http://docs.memsql.com/latest/setup/offline/
In step 3, memsql-ops start command completes with the following error message
    memsql-ops-4.1.7 > memsql-ops/memsql-ops start
    Starting MemSQL Ops...
    Exception in thread Thread-7:
    Traceback (most recent call last):
    File "/usr/local/updated-openssl/lib/python3.4/threading.py", line 921, in _bootstrap_inner
    File "/usr/local/updated-openssl/lib/python3.4/threading.py", line 869, in run
    File "/memsql_platform/memsql_platform/agent/daemon/manage.py", line 198, in startup_watcher
    File "/memsql_platform/memsql_platform/network/api_client.py", line 32, in call
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/simplejson/__init__.py", line 501, in loads
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/simplejson/decoder.py", line 370, in decode
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/simplejson/decoder.py", line 400, in raw_decode
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

After that I can access the MemSQL Ops web interface and it complains "MemSQL Ops is unable to connect to the MemSQL download servers" and prompts me to add the binaries. Hence I followed step 5 of the instruction guide and got this error
    memsql-ops > memsql-ops file-add -t memsql memsqlbin_amd64.tar.gz
    Traceback (most recent call last):
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/cx_Freeze/initscripts/Console.py", line 27, in <module>
    File "/memsql_platform/bin/memsql-ops", line 18, in <module>
    File "/memsql_platform/memsql_platform/agent/cli/client.py", line 197, in parse
    File "/memsql_platform/memsql_platform/agent/cli/command_file_add.py", line 27, in run
    File "/memsql_platform/memsql_platform/agent/cli/file_add_mixin.py", line 58, in add_file
    File "/memsql_platform/memsql_platform/network/api_client.py", line 32, in call
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/simplejson/__init__.py", line 501, in loads
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/simplejson/decoder.py", line 370, in decode
    File "/usr/local/updated-openssl/lib/python3.4/site-packages/simplejson/decoder.py", line 400, in raw_decode
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

=====================================
This is the memsql-ops.log
2015-10-19 17:05:37,667 [INFO] memsql_platform.agent.daemon.daemon: Binding to xx.xx.xx.xx:9000
2015-10-19 17:05:38,458 [INFO] memsql_platform.network.engine: Ready.
2015-10-19 17:05:38,462 [ERROR] memsql_platform.network.state.primary_state.primary_poll: Failed to lookup local agent
2015-10-19 17:05:38,483 [INFO] memsql_platform.analytics.engine: Ready.
2015-10-19 17:05:38,505 [INFO] memsql_platform.topology.engine: Ready.
2015-10-19 17:05:38,509 [INFO] memsql_platform.spark.engine: Ready.
2015-10-19 17:05:38,518 [INFO] memsql_platform.user_intent.intention_manager: Ready.
2015-10-19 17:05:38,521 [INFO] memsql_platform.user_intent.intention_manager: Checking 1 active intentions
2015-10-19 17:05:38,533 [INFO] memsql_platform.usage_statistics.engine: Ready.
2015-10-19 17:05:38,537 [INFO] memsql_platform.benchmark.engine: Ready.
2015-10-19 17:05:38,551 [INFO] memsql_platform.cluster.engine: Ready.
2015-10-19 17:05:38,580 [INFO] memsql_platform.files.engine: Ready.
2015-10-19 17:05:38,632 [INFO] memsql_platform.jobs.engine: Ready.
2015-10-19 17:05:38,636 [INFO] memsql_platform.jobs.job_requeuer: Ready.
2015-10-19 17:05:42,974 [INFO] memsql_platform.network.web_socket_handler: Received websocket connection from xx.xx.xx.xx
2015-10-19 17:13:03,553 [INFO] memsql_platform.network.web_socket_handler: Closed websocket connection with xx.xx.xx.xx due to [1001] None
2015-10-19 17:13:03,573 [INFO] memsql_platform.network.web_server: 304 GET / (xx.xx.xx.xx) 1.19ms
2015-10-19 17:13:03,895 [INFO] memsql_platform.network.web_socket_handler: Received websocket connection from xx.xx.xx.xx
2015-10-19 17:13:18,714 [INFO] memsql_platform.network.web_socket_handler: Closed websocket connection with xx.xx.xx.xx due to [1001] None

Can anyone confirm if MemSQL 4.1.7 works with RHEL 6 or does it require some other dependencies?

A: As pointed out by @Wayne Song in the comments. The MemSQL Ops command line works by sending API requests to 127.0.0.1:9000
So if your server is inside a corporate firewall there is a possibility that the request to 127.0.0.1 may not pass. So adding 127.0.0.1 to no_proxy solved this problem.
you can set this in command line as:
export no_proxy=127.0.0.1


text:
Q: Python - urllib - Server is not getting everything after '?' in URL I am writing a Python3 script to trigger an Axis camera via their HTTP API. The string they need in the url to trigger the Digital Input (with authorization) is:
"http://{ip}/axis-cgi/param.cgi?action=update&IOPort.I0.Input.Trig={open/closed}"

If I put this in a browser it works AKA response 200 - OK. When I run this on my Linux machine using the urllib request.
#encode user,pass
values = { 'username': username,'password': password }
data = urllib.urlencode(values)

#Axis param.cgi action
action = "update"
trig = "closed"

cgi_args = {"action": action, "IOPort.I0.Input.Trig": trig}
cgi_data = urllib.urlencode(cgi_args)
url = "http://{ip}/axis-cgi/param.cgi?{data}".format(ip=ip, data=cgi_data)

req = urllib2.Request(url, data, headers={'Content-type': 'text/html'})
print(req.get_full_url())

response = urllib2.urlopen(req)
result = response.read()
print (result)

The output is:
http://192.168.50.191/axis-cgi/param.cgi?action=update&IOPort.I0.Input.Trig=closed
action must be specified

I know that I am authenticated otherwise I get Unauthorized response from server.
As you can see for debugging I print the req.get_full_url() to make sure I've built the url string correctly, however the server responds with action must be specified which is what I get in the browser when I just have http://192.168.50.191/axis-cgi/param.cgi? in the address bar. So the action portion of the URL appears to not be making it to the server.
I've tried:

*

*Using %3F as the ? character, but I get 404 error

*Embedding the data in the data parameter does not work either

Anything I am missing here?

A: used pycurl with digest authorization for a GET request with auth:
def configCurl():
username = "user"
password = "pass"
auth_mode = pycurl.HTTPAUTH_DIGEST
curl = pycurl.Curl()
curl.setopt(pycurl.HTTPAUTH, auth_mode)
curl.setopt(pycurl.USERPWD, "{}:{}".format(username, password))
curl.setopt(pycurl.WRITEFUNCTION, lambda x: None)
return curl

curl = configCurl()
curl.setopt(curl.URL, url)
curl.perform()
curl.close()


text:
Q: Loss of information with generics' parameters The declaration of generic parameters is not exhaustive enough to give type relationships (subtypes) and this information is simply lost... For example :
-- generic_p.ads
generic
   type Index_Range_Type is range <>;
   type Count_Range_Type is range <>;
procedure Generic_P (I : Index_Range_Type, C : Count_Range_Type);

-- generic_p.adb
procedure Generic_P (I : Index_Range_Type, C : Count_Range_Type) is
begin
   if I = C then -- oops : cannot compare different types...
     -- ...
   end if;
end Generic_P;

-- main.adb
procedure Main is
   type Index_Range_Type is 0 .. 512;
   subtype Count_Range_Type is Index_Range_Type range 1 .. Index_Range_Type'Last;

   procedure P is new Generic_P (Index_Range_Type, Count_Range_Type);

   I : Index_Range_Type := 33;
   C : Count_Range_Type := 42;
begin
   if I = C then -- Ok : Count_Range is a subset of Index_Range, they can be compared
      -- ...
   end if;
   P (I, C);
end Main;

Which gives the following error for the comparison in generic_p.adb : invalid operand types [...] left operand has type "Index_Range_Type" [...] right operand has "type Count_Range_Type". The subtyping is not visible in the generic procedure.
Is there any way to specify the relationship between generic parameters ?
Further Informations
I really need Count_Range_Type as a parameter of the procedure to be able to add another parameter which needs Count_Range_Type.
-- generic_p.ads
generic
   type Index_Range_Type is range <>;
   type Count_Range_Type is range <>;
   with procedure F (C : Count_Range_Type);
procedure Generic_P (I : Index_Range_Type, C : Count_Range_Type);

I can't directly use the type, I need P to be absolutely generic and independent.

A: Off the top of my head, perhaps inverting who declares what might meet your need. Consider having the generic define the subtype:
generic
   type Index_Range_Type is range <>;
package Generic_Provider is

   pragma Assert(Index_Range_Type'First = 0);
   subtype Count_Range_Type is Index_Range_Type range 1 .. Index_Range_Type'last;

   procedure P (I : Index_Range_Type; C : Count_Range_Type);

end Generic_Provider;

In the body:
package body Generic_Provider is

   procedure P (I : Index_Range_Type; C : Count_Range_Type) is
   begin
      if I = C then -- No problem comparing now...
            -- ...
         null;
      end if;
   end P;
end Generic_Provider;

Then in your instantiating unit:
with Generic_Provider;

procedure Main is
   type Index_Range_Type is range 0 .. 512;
   package P_Provider is new Generic_Provider (Index_Range_Type);

   subtype Count_Range_Type is P_provider.Count_Range_Type;

   I : Index_Range_Type := 33;
   C : Count_Range_Type := 42;
begin
   if I = C then -- Ok : Count_Range is a subset of Index_Range, and all is good.
         -- ...
      null;
   end if;
   P_Provider.P (I, C);
end Main;

This is akin to the approach System.Address_To_Access_Conversions takes, whereby the generic is instantiated with a "foundational" type, and the generic then provides the "enhancements"--in that package it's an access type, in this it would be the subtype.

A: You could also put a with function "=" (Left : Index_Range_Type; Right : Count_Range_Type) Return boolean into the generic's header... that forces the user to provide an appropriate equals function.
That route is needed because as the generic header now stands, the compiler may NOT make the assumption he two types are related; that is not given from the information is the signature.

A: This addresses the "Further Informations" portion of the original question, whereby a generic needs to be instantiated with a procedure containing a parameter that's a subtype of the instantiating type.
Essentially, a generic package is employed to set up the subtype, and then a generic child package provides the desired procedure (which is instantiated with the generic formal procedure). Admittedly, this is a rather involved solution to the problem. So here we go:
The "parent" generic that creates the subtype:
generic
   type Index_Range_Type is range <>;
package Generic_Provider is
   pragma Assert(Index_Range_Type'First = 0);
   subtype Count_Range_Type is Index_Range_Type range 1 .. Index_Range_Type'last;

end Generic_Provider;

All this does is declare the subtype, it needs no body (and in fact a body would be illegal).
Here's the spec of our procedure provider, which utilizes a client-supplied formal procedure.
generic
   with procedure F(I : Index_Range_Type;
                    C : Count_Range_Type);

package Generic_Provider.Services is

   procedure P (I : Index_Range_Type; C : Count_Range_Type);

end Generic_Provider.Services;

Just for grins, its body, which verifies that the formal procedure can be invoked and that the subtype comparison is valid:
package body Generic_Provider.Services is

   procedure P (I : Index_Range_Type; C : Count_Range_Type) is
   begin
      if I = C then
         F(I, C);
      end if;
   end P;

end Generic_Provider.Services;

Finally, the instantiating main program:
with Generic_Provider.Services;

procedure Main is
   type Index_Range_Type is range 0 .. 512;
   package Type_Provider is new Generic_Provider (Index_Range_Type);
   subtype Count_Range_Type is Type_Provider.Count_Range_Type;

   procedure My_F (I : Index_Range_Type;
                   C : Count_Range_Type) is
   begin
      null;
   end My_F;

   package P_Provider is new Type_Provider.Services(My_F);

   I : Index_Range_Type := 33;
   C : Count_Range_Type := 42;
begin
   if I = C then
      null;
   end if;
   P_Provider.P (I, C);
end Main;

A: You can use a full type instead of a subtype:
-- generic_p.ads
generic
   type Index_Range_Type is range <>;
   type Count_Range_Type is new Index_Range_Type;
procedure Generic_P (I : Index_Range_Type; C : Count_Range_Type);

-- generic_p.adb
procedure Generic_P (I : Index_Range_Type; C : Count_Range_Type) is
begin
   -- Neccessary conversion
   if I = Index_Range_Type (C) then
     -- ...
   end if;
end Generic_P;

-- main.adb
procedure Main is
   type Index_Range_Type is 0 .. 512;
   type Count_Range_Type is new Index_Range_Type range 1 .. Index_Range_Type'Last;

   procedure P is new Generic_P (Index_Range_Type, Count_Range_Type);

   I : Index_Range_Type := 33;
   C : Count_Range_Type := 42;
begin
   if I = Index_Range_Type (C) then
      -- ...
   end if;
   P (I, C);
end Main;

It is also possible to just cast C to Index_Range_Type without specifying the relation between the types in the generic section. That way, you can still use your subtype, but any instance of the generic procedure where Count_Range_Type is not castable to Index_Range_Type will raise an exception.
I suggest reading Ada 95 Quality and Style Guide, 8.2.4 for more information about using subtypes with generics.


text:
Q: Is there a programmatic way to swap attributes on a feature? I am still pretty new to python (and programming for that matter) but I believe there must be an easier way to do a certain task. My task is to flip road centerline directions. The centerlines have address ranges in the attributes, and I need to flip them, from left to right. Basically I am swapping the value of some attributes.
Is that something I could accomplish with some scripting? I have a Python book on my desk that I've been reading through. I'm eager to tackle new problems with code.

A: To do attributes, you can use either arcpy.da.UpdateCursor (requires 10.1 or later)  or  arcpy.UpdateCursor
To use arcpy.da.UpdateCursor  (see arcpy.da.UpdateCursor)
# using arcpy.da.UpdateCursor  (requires 10.1 or later...)
import arcpy

fc = 'C:/Temporary Files/Centerlines.shp'
fields = ['L_ADD_FROM', 'L_ADD_TO']

with arcpy.da.UpdateCursor(fc, fields, "\"L_ADD_TO\" < \"L_ADD_FROM\"") as cursor:
    for row in cursor:
        # Get the values - row[0] refers to the first field in your fields list
        value0 = row[0]
        value1 = row[1]

        # Switch the values
        row[0] = value1
        row[1] = value0

        cursor.updateRow(row)

To use arcpy.UpdateCursor   (See arcpy.UpdateCursor)
# using arcpy.UpdateCursor
import arcpy

fc = 'C:/Temporary Files/Centerlines.shp'

cursor = arcpy.UpdateCursor(fc, "\"R_ADD_TO\" < \"R_ADD_FROM\"")
row = cursor.next()
while row:
    value0 = row.getValue('R_ADD_FROM')
    value1 = row.getValue('R_ADD_TO')

    row.setValue('R_ADD_FROM', value1)
    row.setValue('R_ADD_TO', value0)

    cursor.updateRow(row)
    row = cursor.next()


text:
Q: How to lock an existing key? I am writing some c# code to write to a redis server. The code is multithreading so whenever I want to make changes to a certain key:value pair, I need to lock the "key"
I am using the StackExchange.Redis library. In this library, an interface IDatabase stands for the redis db and provides methods to read from/write to redis. It has 2 lock-related methods: bool LockTake(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None); & bool LockRelease(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None);
However, the LockTake() can only lock non-existing keys, according to this post: https://github.com/StackExchange/StackExchange.Redis/issues/144
But I want to lock a key even if it has been created since multiple threads may try to update it concurrently. How can I do that in c#?

A: You can use a key-based locking library, such as the one I made called AsyncKeyedLock. It's available on GitHub and packaged over at NuGet.
Usage example:
var locker = new AsyncKeyedLocker<string>(o =>
{
   o.PoolSize = 20;
   o.PoolInitialFill = 1;
});

// asynchronous code
using (await locker.LockAsync(key, cancellationToken))
{
   ...
}

// synchronous code
using (locker.Lock(key))
{
   ...
}


text:
Q: Flask gives "error 32 broken pipe" when being requested too often I write a very simple flask server. This server response to GET and give back my home.html.
I visit the site on 127.0.0.1:5000
everything is good till now.
However, if I keep pressing "fresh" (Command+R on my computer) a lot of times for a few second, as fast as I can, then, my flask give this error and breaks down.

Exception in thread Thread-1:
  Traceback (most recent call last):
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 801, in bootstrap_inner
      self.run()
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 754, in run
      self.__target(*self.__args, **self.__kwargs)
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 659, in inner
      srv.serve_forever()
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 499, in serve_forever
      HTTPServer.serve_forever(self)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 238, in serve_forever
      self._handle_request_noblock()
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 297, in _handle_request_noblock
      self.handle_error(request, client_address)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
      self.process_request(request, client_address)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 321, in process_request
      self.finish_request(request, client_address)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 334, in finish_request
      self.RequestHandlerClass(request, client_address, self)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 655, in __init
      self.handle()
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 216, in handle
      rv = BaseHTTPRequestHandler.handle(self)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.py", line 340, in handle
      self.handle_one_request()
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 251, in handle_one_request
      return self.run_wsgi()
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 193, in run_wsgi
      execute(self.server.app)
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 184, in execute
      write(data)
    File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 152, in write
      self.send_header(key, value)
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.py", line 401, in send_header
      self.wfile.write("%s: %s\r\n" % (keyword, value))
  IOError: [Errno 32] Broken pipe

I believe this is what happened: When my server was trying to transmit html to my browser, I pressed the refresh and broke the pipe. So my server got confused and then give error.
How to solve this problem? Or this site is not usable as all since anyone who ask constantly for my page can break my webpage down.
Thanks!

A: you can try using app.run(threaded=True) as suggested in this SO answer.

A: This error appear because your server is overloaded! Stop and start it!

A: I saw this error too in an Ubuntu Docker container on Kubernetes on Ubuntu VM:
Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 270, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 261, in execute
    write(data)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 227, in write
    self.send_header(key, value)
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 412, in send_header
    self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe

I created a brand new Ubuntu xenial VM and ran the same code in Ubuntu Docker container on Kubernetes, and this error was not seen and Python Flask worked as expected. I think it was issue with my host (Ubuntu VM).

A: built-in werkzeug is not capable of handle concurrent requests the connection while the server is still churning its content out.
rather than using
 app.run(debug=True,port=5000)

you should try this
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()

A: Which version of Flask are you using, version 0.12/0.13, or an older one?
You're seeing this error because your server doesn't handle concurrent requests. You need a proper WSGI server that is capable of handling concurrent requests ( use  gunicorn or uWSGI in multithreaded environment) and it should work fine.
Check: http://twistedmatrix.com/trac/wiki/TwistedWeb
What happens is that you are making a second request through reload to your flask app while it is still busy processing the first request. It won't respond to this second request until it is done with that first request. The requests.post() function is waiting for Flask to respond, but Flask itself is waiting for post()
Also enable threads in the Flask-supplied server using:
app.run(threaded=True)

Also note that Python 3 the socketserver implementation handles the disconnect more gracefully and continues to serve rather than crash.