text:
Q: Extracting values from python dictionaries with array of dicts I this data structure, but seem to be having a bit of a mental block. I can't work out how to get the values for the size keys in the dicts.
dups = {'2222': [{'Book': 'Lord of the Rings', 'size': '100'},
                 {'Book': 'Woman in Black', 'size': '800'}],
        '3333': [{'Book': 'The Hobbit', 'size': '500'},
                 {'Book': '100 Dalmations', 'size': '600'}]}

I've tried this:
for i in dups:
    book = i[1]
        for size in book
        print size'['size']

But that does not work!

A: I think you want:
for i in dups:
    book_list = dups[i]
    for book in book_list:
        print book['size']

dups[i] gives you the list, which you can iterate over.

A: You can use .iteritems() to retrieve the value and keys while you are iterating:
>>> for key, value in dups.iteritems():
...     print key, value
...
3333 [{'Book': 'The Hobbit', 'size': '500'}, {'Book': '100 Dalmations', 'size': '600'}]
2222 [{'Book': 'Lord of the Rings', 'size': '100'}, {'Book': 'Woman in Black', 'size': '800'}]
>>>

And then you can nest a second loop in the loop to iterate over all keys and values again.


text:
Q: Approximate solution to MILP with PuLP Is it possible to get an approximate solution to a mixed integer linear programming problem with PuLP? My problem is complex and the exact resolution takes too long.

A: You probably do not mean Linear Programming but rather Mixed Integer Programming. (The original question asked about LPs).
LPs usually solve quite fast and I don't know a good way to find an approximate solution for them. You may want to try an interior point or barrier method and set an iteration or time limit. For Simplex methods this typically does not work very well.
MIP models can take a lot of time to solve. Solvers allow to terminate earlier by setting a gap (gap = 0 means solving to optimality). E.g.
model.solve(GLPK(options=['--mipgap', '0.01']))

redpajama_set_name: RedPajamaStackExchange


text:
Q: copying classes linked together I have few different types of classes which are cross linked (they contain pointers to each other - some of them vectors of pointers) and I am pretty happy with this design. But now it come a point where I would like to make a copy of all my structure and its very hard to correct all the links of every instance of the new classes. I already have a container class for all the structure but still the attempts I made to write a clone() method ended up in very dirty code and I am not satisfied with them.
I would like to know if there is a kind of design pattern that could help to solve this problem.

A: One solution that might help you (if I understood correctly from your rather vague description):

*

*create a clone of all your objects (by now, just copy all pointers to the new objects still pointing to the original objects)

*while doing so, keep track of which object is the clone of which object in some sort of dictionary (something like std::map<void*,void*> should do the job, but maybe you can come up with something better than the ugly void*)

*go through all the new objects and redirect all pointers by the values stored in the dictionary

A: The usual approach is to keep some sort of a mapping form old to new pointers - before making a copy, consult the map to see if the object was already copied and if it is, return the existing copy, otherwise, call clone().
Something like this:
#include <unordered_map>
#include <vector>

typedef std::unordered_map<void *, void *> map_type;

template<typename T>
T *clone (T *ptr, map_type &m)
{
  auto p = m.find (ptr);
  if (p != m.end ())
    return static_cast<T *> (p->second);
  else
    return ptr->clone (m);
}

struct S
{
  int x;
  std::vector<S *> v;

  S *clone (map_type &m)
  {
    S *p = new S;

    // this is important to happen before calling clone() on subobjects
    m [this] = p;

    p->x = x;
    for (auto q: v)
      p->v.push_back (::clone (q, m));

    return p;
  }
};

int
main ()
{
  S *p = new S ();
  p->x = 1;

  S *q = new S ();
  q->x = 2;

  S *r = new S ();
  r->x = 3;

  p->v.push_back (p);
  p->v.push_back (p);
  p->v.push_back (q);

  q->v.push_back (p);
  q->v.push_back (r);

  r->v.push_back (p);

  map_type m;

  S *x;
  x = clone (p, m);
}

A: It might be a bit cleaner if you can impose hierarchy (child-parent relationship) together with the links. Then you may approach cloning process recursively - let each of the parents clone all of all its children while being cloned and updating references.
In case you have relationship on the same level (say, objects being peers and cross-referencing each other in circle), you can artificially add parent that would clone all children, update its own references, and then update children with new references.
This would allow scaling/adding new components without modifying much of the code.


text:
Q: Is it possible for a DFA to have one state with an empty alphabet? I am confused if this is a valid DFA or not.

A: Yes. That one state must be the initial state. If it is also an acceptor state, the DFA accepts the language $\{\epsilon\}$; if not, the DFA accepts the language $\varnothing$. Both of these are languages over any alphabet, including the empty alphabet.


text:
Q: PhantomJS Cookies I'm trying to run some QUnit test cases with phantomJS and chutzpah console. I'm having difficulties communicate with the phantomJS cookies. My test case runs perfectly with the browser communicating with the but not with phantomJS as it gives an error with the cookie.
Does the phantomJS deals with Cookies in a different pattern than the other browsers? any suggestions?

A: Have you got at least version 1.7 of PhantomJS? In the release notes it states:

PhantomJS 1.7 "Blazing Star", was released on September 22, 2012. It
  added module system support (modelled after CommonJS), better
  cookies handling, and other small improvements.

http://phantomjs.org/release-1.7.html


text:
Q: Displaying searched record for a query using 'like' at the top in mysql I am writing a search query which makes a search based on first name and last name.
The query is like this:
select fname,lname
from users
where fname like fname like '%$name%' or lname like '%$name%';

if the user enters first name and last name in the search box,I have exploded it with a 'space' and the query goes like this
select fname,lname
from users
where fname like fname like '%$f_name%' or lname like '%$l_name%';

In the second query if I enter John Thomas,it shows me all the records with John or Thomas in first or last name,but the actual search result i.e John Thomas(exact match) is somewhere below in the results.(If I have 100 results its on the 60th position).
How can I modify the query to achive this or do I have to handle it programatically? i.e Check the result array and match the check box value for its presence and display it fist.

A: ADD in query
ORDER BY `fname`

You can testing mysql sorting
More information here ==> http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

A: Try:
SELECT fname, lname FROM users
WHERE (fname = '$f_name' AND lname = '$l_name')
OR (fname LIKE '%$f_name%') OR (lname LIKE '%$l_name%');

And if you need to order then ORDER BY lname, fname in the end of the query, depending on what you need to order by of course.


text:
Q: Magento Forbidden Error On Backend When I Logged in Magento error not display but as I refresh or nevigate to other pages it shows error on every page till three or four navigations then error hide automatically. I access all pages but I wants to know why this error come and how t o solve this.
I have tried below commands but it not works for me
    find ./ -type f | xargs chmod 644
    find ./ -type d | xargs chmod 755
    chmod -Rf 777 var
    chmod -Rf 777 media

A: Since you've mentioned that Bulk SMS extension is installed, and after that issue occurred, can you try to edit the following file:
app/etc/modules/Topefekt_Magesms.xml
and change <active>true</active> to <active>false</active>.
After that, clear Magento cache, and let us know if it still occurs.


text:
Q: run @Component after @Repository in Spring Framework I'm using Redis in a spring project and I define a @Component class that uses Redis repository with @Autowire, but when debugging the application, @Component class constructor runs before bean to connect to Redis, therefore the application exits with this error :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataManager' defined in file [/mnt/D/ms/projects/EventDetection/out/production/classes/ir/rahati/data/datamanager/DataManager.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ir.rahati.data.messagegraph.redis.RedisMessageGraphRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

DataManager class
@Component
public class DataManager {
        private final RedisMessageGraph messageGraph;
    @Autowired
    public DataManager( RedisMessageGraphRepository redisMessageGraphRepository) {
        this.messageGraph=new RedisMessageGraph(redisMessageGraphRepository);
    }
}

Redis repository interface
@Repository
public interface RedisMessageGraphRepository extends CrudRepository<MessageGraphModel, String> {
}

Configuration Class
@Configuration
@EnableRedisRepositories("ir.rahati.data.messagegraph")
public class RedisMessageGraphConfig {
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
        redisStandaloneConfiguration.setDatabase(3);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    @Bean(name = "redis15")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());

        return template;
    }
}


text: Q: Stop Files From Being Given the 'nodump' Flag When Accessed Over SMB      Is there any way to stop files from being given the 'nodump' flag when accessed over the network via SMB?  This happens all the time when I'm using files on the external boot drive I use with my iMac from my Windows 10 laptop, and it's started to annoy me.  I have to switch over to that iMac, either physically or via an SSH session, and run 'chflags dump' on the affected files every time after this problem occurs.


text:
Q: Is there a way to format multiple worksheets using the googlesheets api and gspread I'm currently writing a python program which scrapes data from a website and then writes that info into a google spreadsheet. Based on the data contained in each row the data is separated into different worksheets inside of the main spreadsheet. I've been sending multiple requests using gspread's batch_update() function but it only formats sheet1 and doesn't format the subsequent pages. What can I do to make all of my sheets be formatted the same.
batch_update() calls the spreadsheets.batchUpdate() method through the googlesheets api which should affect the whole spreadsheet instead of the first worksheet which I don't understand
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
vt = client.open(sheetName)

formatRequests = []
formatRequests.append({
        "repeatCell" : {
            "range" : {
                "startColumnIndex" : 0,
                "endColumnIndex" : 1
            },
            "cell" : {
                "userEnteredFormat" : {
                    "numberFormat" : {
                        "type": "DATE",
                        "pattern" : "mmm dd, yyyy, hh:mm am/pm"
                    }
                }
            },
            "fields" : "userEnteredFormat.numberFormat"
        }
    })

#... A bunch of other formatting appends

body = {
        'requests' : formatRequests
    }
vt.batch_update(body)

This only formats the first page in the spreadsheet

A: *

*You want to set the format for all sheets in the Spreadsheet.

*You want to achieve this using Sheets API with gspread.

*You have already been able to get and put values using Sheets API.

If my understanding is correct, how about this modification?
Modification point:

*

*In this modification, at first, all sheets are retrieved from the Spreadsheet. Then the request body is created using the retrieved sheet IDs.

Modified script:
Please modify your script as follows.

From:

formatRequests = []
formatRequests.append({
        "repeatCell" : {
            "range" : {
                "startColumnIndex" : 0,
                "endColumnIndex" : 1
            },
            "cell" : {
                "userEnteredFormat" : {
                    "numberFormat" : {
                        "type": "DATE",
                        "pattern" : "mmm dd, yyyy, hh:mm am/pm"
                    }
                }
            },
            "fields" : "userEnteredFormat.numberFormat"
        }
    })

To:

formatRequests = []
worksheet_list = vt.worksheets()  # Added
for sheet in worksheet_list:  # Added
    formatRequests.append({
        "repeatCell": {
            "range": {
                "startColumnIndex": 0,
                "endColumnIndex": 1,
                "sheetId": sheet.id  # Added
            },
            "cell": {
                "userEnteredFormat": {
                    "numberFormat": {
                        "type": "DATE",
                        "pattern": "mmm dd, yyyy, hh:mm am/pm"
                    }
                }
            },
            "fields": "userEnteredFormat.numberFormat"
        }
    })

Reference:

*

*Selecting a Worksheet
If I misunderstood your question and this was not the direction you want, I apologize.


text:
Q: Subseting data frame by another data frame The data is as follows:
> x
  a b
1 1 a
2 2 a
3 3 a
4 1 b
5 2 b
6 3 b

> y
  a b
1 2 a
2 3 a
3 3 b

My goal is to compare both data frames, and for each row in x indicate whether equivalent row exists in y. All of the y rows are actually contained in x, so I would like to end up with something like this:
> x
  a b intersect.x.y
1 1 a             F
2 2 a             T
3 3 a             T
4 1 b             F
5 2 b             F
6 3 b             T

How about that?

A: How about this?
x$rn          <- 1:nrow(x)
xyrows        <- merge(x,y)$rn # maybe you just want to look at the merge ...?
x$iny         <- FALSE
x$iny[xyrows] <- TRUE

I suspect there is a more standard approach, but this way is easy to understand.


text:
Q: "sys-package-mgr*: can't create package cache dir" when run python script with Jython I want to run Python script with Jython.
the result show correctly, but at the same time there is an warning message, "sys-package-mgr*: can't create package cache dir"
How could I solve this problem?
thanks in advance~~~

A: You can change the location of the cache directory to a place that you have read & write access to by setting the "python.cachedir" option when starting jython, e.g.:
jython -Dpython.cachedir=*your cachedir directory here*

or:
java -jar my_standalone_jython.jar -Dpython.cachedir=*your cachedir directory here*

You can read about the python.cachedir option here:
http://www.jython.org/archive/21/docs/registry.html

A: 1) By changing permissions to allow writing to the directory in the error message.
2) By setting python.cachedir.skip = true
You can read this:
http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#module-search-path-compilation-and-loading
for further insights.

A: Making directories world writable admittedly makes the problem "go away", however, it introduces a huge security hole. Anyone could introduce code to the now world writable directory that would be executed in the users' jpython environment.
Setting the cachedir to skip would presumably result in a performance drop (why implement a caching scheme other than to improve performace).
Instead I did the following:
I created a new group (in my case eclipse, but it could have been jpython). I added the users of jpython to that group.
$ sudo groupadd eclipse

I then changed the group of my eclipse plugins folder and its children to 'eclipse'.
/opt/eclipse/plugins $ sudo chgrp -R eclipse *

Then I changed the group permissions as follows
/opt/eclipse/plugins $ sudo chmod -R g+w *
/opt/eclipse/plugins $ find * -type d -print | sudo xargs chmod g+s

This added group writable, and set the S_GID bit on all directories recursively. This last bit causes new directories created to have the same group id as their parent.
The final touch was change the umask for the eclipse users set to 007.
$ sudo vi /etc/login.def

change UMASK to 007 (from 022).
UMASK=007

A: The easiest fix I found so far was to do:
$ sudo chmod -R 777 /opt/jython/cachedir


text:
Q: Java | what is the difference between peek() and lastElement() method in Stack Java |
what is the difference between peek() and lastElement() method in Stack.
They both can return the element of top of stack, is there have performance difference or something else?

A: The only difference between these two methods is the class of the exception that gets thrown in the case where the stack is empty.  Use whichever one you prefer.  The standard implementations in JDK 8 are more-or-less identical, so there will be no measurable performance difference.
Possibly the reason why Stack provides a second version of the same method is that the words peek, pop and push are traditionally associated with programming a stack.
From java/util/Stack.java
 public synchronized E peek() {
    int len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);
}

and from java/util/Vector.java
 public synchronized E lastElement() {
    if (elementCount == 0) {
        throw new NoSuchElementException();
    }
    return elementData(elementCount - 1);
}


text:
Q: switching image on timed event in swift I am trying to switch the displayed image in an UIImageView to different images based on an timed event by defining the what image should be displayed by I and the app works but when the timer gets to 5 the app crashes. if anyone can help me out then that would be great (also the Ad is the beginning of the image name so AD_1 - AD_4)
import UIKit

 class ViewController: UIViewController {

//this is for declaring all the profile buttons
@IBOutlet weak var Icon_1: UIButton!
@IBOutlet weak var Icon_2: UIButton!
@IBOutlet weak var Icon_3: UIButton!
@IBOutlet weak var Icon_4: UIButton!
@IBOutlet weak var Icon_5: UIButton!
@IBOutlet weak var Icon_6: UIButton!
@IBOutlet weak var Icon_7: UIButton!
@IBOutlet weak var Icon_8: UIButton!

//this is used to swich the images
var i = Int(1)

let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fire), userInfo: nil, repeats: false)

//this is for the view
@IBOutlet weak var ad_view: UIView!

//this is for when the user swipes left
@IBAction func Icon_Swipe_Left(_ sender: Any) {
    Icon_1.isHidden = true
    Icon_2.isHidden = true
    Icon_3.isHidden = true
    Icon_4.isHidden = true

    Icon_5.isHidden = false
    Icon_6.isHidden = false
    Icon_7.isHidden = false
    Icon_8.isHidden = false
}

//this is when the user swipes right
@IBAction func Icon_Swipe_Right(_ sender: Any) {
    Icon_1.isHidden = false
    Icon_2.isHidden = false
    Icon_3.isHidden = false
    Icon_4.isHidden = false

    Icon_5.isHidden = true
    Icon_6.isHidden = true
    Icon_7.isHidden = true
    Icon_8.isHidden = true
}

// this is for decareing the image frame for the adds
@IBOutlet weak var Ad_Frame: UIImageView!

override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view.

    //this is for showing the fist set of icons
    Icon_1.isHidden = false
    Icon_2.isHidden = false
    Icon_3.isHidden = false
    Icon_4.isHidden = false
    //this is for hideing the second set of icons
    Icon_5.isHidden = true
    Icon_6.isHidden = true
    Icon_7.isHidden = true
    Icon_8.isHidden = true

    self.Ad_Frame.image = UIImage(named: "AD_\(i)")
}

@objc func fire()
{
    i += 1
    self.Ad_Frame.image = UIImage(named: "AD_\(i)")
}

}

A: Two things:
1:  you say you have images AD_1 - AD_4 - that's only four images, so it won't cope with the fifth!  I'm assuming you mean AD_1 - AD_5
2:  More importantly, you start with i = 1, and then add 1 before trying to display the image, so you're actually trying to display images 2...6.
Increment i after displaying the image, not before

A: Change fire so that it starts over once 5 is reached
@objc func fire() {
    self.Ad_Frame.image = UIImage(named: "AD_\(i)")
    i += 1
    if i > 4 { i = 1 }
}

Off-topic but I would recommend renaming i to something more readable like counter for instance. Single letter variables are not recommended apart from in for loops. Also when declaring it you don't need to call Int(...) but assign the value directly instead, var counter = 1


text:
Q: Changing value of $_SESSION variable using submit button I am trying to make code changing news pages and I am having difficulties.
$_SESSION['page'] doesn't change value and always stays as 1.
Thank you.
<?php
   session_start();
   if (!isset($_POST['set_page'])) {
      $_SESSION['page'] = 1;
   }
   else {
      eval("return '".$_POST['change_page']."';");
   }
   echo "Page ".$_SESSION['page'];
   echo '<form action="test.php" method="post">';
   echo '<input type="hidden" name="change_page" value="$_SESSION["page"]++"/>';
   echo '<input type="submit" name="set_page" value="Next Page"></form></p>';
?>

A: Your statement here is wrong ++ operator will work like that change that line like this
echo '<input type="hidden" name="change_page" value="'.$_SESSION["page"]++.'"/>';

and your single quotes, When you embed some variable inside string use double quotes or use concatenation.


text:
Q: Hibernate, error org.hibernate.util.JDBCExceptionReporter Field 'Variable_ID' doesn't have a default value I have problem with insert data from one side relationships to other tables and to other side of relationships at the same time
I have:
Table User with User Entity
@Entity
@Column(name="USER")
public class User{

private int id;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

@ManyToMany
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@JoinTable(name="USER_CARS_JOINTABLE",
                joinColumns=@JoinColumn(name="USER_ID"),
                inverseJoinColumns=@JoinColumn(name="CARS_ID"))
public Cars userCars;

//set and get methods omitted

}

Table CARS with Cars Entity
@Entity
   @Column(name="CARS")
   public class Cars{

    private int dateId;

    @Id
    @GeneratedValue(strategy=IDENTITY)
    @Column(name="DATE_ID")
    public int getDateId() {
        return dateId;
    }

    public void setDateId(int dateId) {
        this.dateId = dateId;
    }

   @ManyToMany
   @Cascade(org.hibernate.annotations.CascadeType.ALL)
   @JoinTable(name="USER_CARS_JOINTABLE",
               joinColumns=@JoinColumn(name="CARS_ID"),
               inverseJoinColumns=@JoinColumn(name="USER_ID"))

   public User username;

   //set and get methods omitted

   }

As you can see I have a JoinTable "USER_CARS_JOINTABLE" between USER and CARS which contain FK on User and Cars tables.
I also will have the table DESCRIPTION and Entity class the name Description:
@Entity
  @Column(name="DESCRIPTION")
  public class Description{

  private int id;

    @Id
    @GeneratedValue(strategy=IDENTITY)
    @Column(name="ID")
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

  private String color;
  private String size;
  private String speed;
  private String type;

  //set and get methods omitted

  }

My JoinTable USER_CARS_JOINTABLE is:

USER_ID INT NOT NULL, CARS_ID INT NOT NULL, DESCRIPTION_ID INT NOT
  NULL, PRIMARY KEY(INSTITUTION_ID, DATE_ID, SRC_ID), CONSTRAINT
  FK_USER_ID_IN_USER_CARS FOREIGN KEY(USER_ID) REFERENCES USER(ID),
  CONSTRAINT FK_CARS_ID_IN_USER_CARS FOREIGN KEY(CARS_ID) REFERENCES
  CARS(ID), CONSTRAINT FK_DESCRIPTION_ID_IN_USER_CARS FOREIGN
  KEY(DESCRIPTION_ID) REFERENCES DESCRIPTION(ID)

In my case User can have alot's of Cars and one type of Car can belong to number of Users. Also the same Car can  have different Description.
Between class Description and User Entity and Cars Entity I will have an Undirectional, JoinTable, OneToMany relationships.That's mean that Classes User and Cars will know about Description class, but Description will not know about User and Cars. When I will try to enset data to my database from User side to class Cars and class Description I will have an exception like this:

Hibernate: insert into USER_CARS_JOINTABLE (User_ID, Description)
  values (?, ?) ERROR: org.hibernate.util.JDBCExceptionReporter - Field
  'Cars_ID' doesn't have a default value ERROR:
  org.hibernate.event.def.AbstractFlushingEventListe ner - Could not
  synchronize database state with session

If I will do this from Cars side I will have an error like this:

Hibernate: insert into USER_CARS_JOINTABLE (Cars_ID, Description)
  values (?, ?) ERROR: org.hibernate.util.JDBCExceptionReporter - Field
  'User_ID' doesn't have a default value ERROR:
  org.hibernate.event.def.AbstractFlushingEventListe ner - Could not
  synchronize database state with session

That's meant that some of my foreign keys an JoinTable USER_CARS_JOINTABLE did not get an ID because I'm inserting it from side which is can not to generate or insert data to this jointable USER_CARS_JOINTABLE, I don't know why?
If I will add to my JoinTable database schema for some of my foreign key like User_ID or Cars_ID the DEFAULT "number" than it is works, it's inser data, but it will always insert the same Number by DEFAULT which I put in "number".
But What I want, is to give for one of my problem foreign key's in joinTable USER_CARS_JOINTABLE the same value as in parient table User or Cars!!! Maybe I can use some of the @Generator annotation from Hibernate for my JoinTable in my Entity class.
Thank you.

A: Your mapping is wrong. A bidirectional association always has an owner side and an inverse side. You made both sides the owner side. The inverse side must not contain mapping information (join table, join column), and must be marked as the inverse side using the mappedBy attribute:
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "userCars")
private User username;

Note that you have several other problems with the code:

*

*the naming is bad. Cars should be named Car. username should be named user. userCars should be named cars.

*the username field shouldn't be public but private

*the annotations should always be on the fields, or always be on the getters. You can't mix both placement types. If you do, half of them will be ignored by Hibernate

A: First, you are using ManyToMany over a single field. It's better to have something like this:
In your User Class:
@ManyToMany
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@JoinTable(name="USER_CARS_JOINTABLE",
            joinColumns=@JoinColumn(name="USER_ID"),
            inverseJoinColumns=@JoinColumn(name="CARS_ID"))
public List<Cars> userCars;

And in your Car class it is better to user mappedBy
@ManyToMany(mappedBy = "userCars")
public List<User> usernames;

In this case, you are making this relation bidirectional, and avoiding an unnecessary table (for this ManyToMany relation, one table is sufficient)

A: I believe your problem is because you are using the strategy IDENTITY to generate your IDs. Try setting this to AUTO instead.
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")


text:
Q: run a php function from js end goal: HTML element is click i want to run PHP functions
so i want to do something like this
  function byeBye(page) {
    if (page == 'teacher.php') {
      <?php $_SESSION['AccType'] = 1; ?>
    } else if (page == 'admin.php') {
      <?php $_SESSION['AccType'] = 2; ?>
    }
    console.log('Redirecting to ' + page);
    window.location.href = './' + page;
  }
</script>

and it called with something like this
<li id='admin' class="list-group-item" onclick="byeBye('admin.php')">
but you can see what is wrong with that. what is the right way to do this?


text:
Q: What are the trade offs of limiting relay ports for a TURN server? By default coturn uses the range 49152-65535    UDP as relay ports. Is there any reason to use the full range? Can't one udp handle infinite connections? What's the point of having all of these open? Are there any security risks? Are there any trade offs to using less udp ports?

A: Coturn uses the 49152-65535 range by default because this is what is specified in RFC 5766, Section 6.2, which describes how the TURN server should react when it receives an allocation request. This paragraph is of particular interest for your question:

In all cases, the server SHOULD only allocate ports from the range 49152 - 65535 (the Dynamic and/or Private Port range [Port-Numbers]), unless the TURN server application knows, through some means not specified here, that other applications running on the same host as the TURN server application will not be impacted by allocating ports outside this range.  This condition can often be satisfied by running the TURN server application on a dedicated machine and/or by arranging that any other applications on the machine allocate ports before the TURN server application starts.  In any case, the TURN server SHOULD NOT allocate ports in the range 0 - 1023 (the Well-Known Port range) to discourage clients from using TURN to run standard services.

The Dynamic and/or Private Port range is described in RFC 6335, Section 6:

*

*the Dynamic Ports, also known as the Private or Ephemeral Ports, from 49152-65535 (never assigned)

So, to try and answer your questions:

*

*Is there any reason to use the full range?
Yes, if the default range works for you and your application.

*Can't one udp handle infinite connections?
Yes, you could configure coturn to only use one port, as system resources allow, of course.

*What's the point of having all of these open?
It is the default range for dynamically assigned port numbers as defined by the IANA.

*Are there any security risks?
Not beyond any other normal security risk involved with running a service like coturn.

*Are there any trade offs to using less udp ports?
As far as I know, there are not any technical trade offs. I have run coturn with a much smaller range outside of the dynamic range, and it works just fine.
When faced with firewalls or port number restrictions on networks trying to reach a TURN server, a smaller range may be seen as a benefit to some network administrators, but at the same time other administrators may question the use of a port range outside of the IANA-assigned dynamic range. I have encountered both mindsets, and it is not possible to declare one approach as clearly better than the other (when chosing between the default port range or a smaller range). You just have to find what works for you application and usage.

A: @bradley-t-hughes provides a good answer; to add a point of view on that:

*

*Defining a default range is a strategy to ensure that applications that are run without customised configuration (hence using default settings) don't clash with each other.

*As for other applications that dynamically allocate UDP ports for real time communications, the configured port range represents an upper limit for concurrent sessions. The smaller the range, the fewer concurrent sessions can be established.

*There are cases where hosts are dedicated to applications like TURN servers, and using wide ranges ensures that the maximum capacity is limited by other factors, like bandwidth or CPU usage.

*If you know in advance that the number of concurrent sessions will be small, e.g. because it's just being used for testing functionality and not to provide a Live service, then you can restrict that range, and leave the other ports available for other applications.


text:
Q: AWS API Gateway with EC2 I have a Django Project deployed in AWS EC2 and have created all the REST APIs with DRF. Everything is working great. When I point public.ip.of.ec2:8000/myapi, I get the correct response and these APIs are used in Android application.
Now, day by day the API hits will be increased. So in order to maintain API requests I want to integrate my APIs with APIGateway. After a lot of reading and searching I still could not find any definitive tutorial or steps as of how to integrate APIGateway with EC2.
I've followed this but still could not integrate APIGateway with AWS Service i.e., EC2.
Please suggest a way to do this.

A:
I have a Django Project deployed in AWS EC2 and have created all the
  REST APIs with DRF. Everything is working great. When I point
  public.ip.of.ec2:8000/myapi, I get the correct response

Integration type you are looking for is HTTP integration

Now, day by day the API hits will be increased. So in order to
  maintain API requests I want to integrate my APIs with APIGateway

Although you can configure API caching, throttling, logging and monitoring, AWS API Gateway won't scale your backend integration. You will need to configure autoscaling on backend service as well.


text:
Q: Formula to find like dates in one column and then calculate difference between the min/max Does anyone know the best way to have Excel:

*

*Look in one column to find all like dates

*Calculate total time between min datetime and max datetime

*Place total in separate column

C                                     D
8/27/2018 14:02       insert total time for each date here, ie:  8/27 00:05:03
8/27/2018 14:01
8/27/2018 14:01
8/27/2018 13:57
8/27/2018 8:56
8/24/2018 10:01
8/24/2018 9:36
8/23/2018 6:01
8/21/2018 12:32
8/21/2018 11:23
8/20/2018 14:03
8/20/2018 10:54
8/17/2018 14:47

I used =TEXT(C7-C8, "h:mm:ss"), but this is not working for me at all. Would I add a vlookup to it?

A: This solution will require that you create a UDF (User-Defined Function) in VBA.
Essentially, you will loop to find all matching dates in your column. On all the dates that match, you will modify the minDt and maxDt variables as necessary - which if the new time is lower or higher than what you currently have stored.
This is probably not the best solution, as creating a UDF that contains a loop is going to be somewhat of a bottleneck, but this is what I am able to come up with at the moment.
Option Explicit

Function getTimeDiff(col As String, inputDt As Date)

    Dim colRng As Range, compDt As Date
    Set colRng = Columns(col)

    compDt = Int(inputDt)   '<-- Converts date/time to date only

    Dim cel As Range, maxDt As Date, minDt As Date, tmpDt As Date
    maxDt = inputDt
    minDt = inputDt
    For Each cel In colRng.Cells
        If cel = "" Then Exit For
        tmpDt = CDate(cel)
        If Int(tmpDt) = compDt Then
            If tmpDt > maxDt Then
                maxDt = tmpDt
            ElseIf tmpDt < minDt Then
                minDt = tmpDt
            End If
        End If
    Next cel

    getTimeDiff = Format(maxDt - minDt, "h:mm")

End Function

Read here on creating UDFs
If you are familiar with UDFs, you may skip this section

*

*Press  Alt  +  F11  to open up VBA.

*In the VBE, click Insert > Module

*Paste the above code into the module

*Save as a Macro-Enabled Workbook

Once you have saved the UDF, you may now use your newly create formula.
It appears that your dates are in column C. So, if your first date was in C2, your formula for D2 would be:
=getTimeDiff("C", C2)


text:
Q: how to show agendaday with rowspan dynamically i cant get any css that change the specific column header with title when event loader ....
its mine.....
function initCalendar(myresources) {
$('#day-calendar').fullCalendar({
defaultView: 'agendaDay',
// defaultDate: '2017-12-28',
defaultDate: $scope.setDate,
aspectRatio: 1.8,
editable: true,
selectable: true,
eventLimit: true,
slotEventOverlap: true,
minTime: $scope.lessonStartTime,
maxTime: $scope.lessonEndTime,
contentHeight: 'auto',
slotLabelInterval: $scope.lessonTimeInterval,
slotLabelFormat: "HH:mm:A",
header: {
left: '',
center: 'Time',
right: ''
},
views: {
agendaDay: {
groupByDateAndResource: true,
}
},
selectable: true,
selectHelper: true,
resourceLabelText: "Venue",
allDaySlot: false,
resources: myresources,
events: eventsData,
eventAfterRender: function(event, element, view) {
$(element).css('width', '200px');
},

this what i want
i want with resource header and event width both are same
is it done by dynamicaly ?
help me ....


text:
Q: Pygame rendering surface to screen without clearing the screen When you click on a specific card it should appear above, when clicked again it should drop down below. Momentarily when you click on a card, it doesn't just move the card up, it basically duplicates the card.
This is the script:
from utilities import *
import pygame
import sys

def main():
    pygame.init()
    size = width, height = 1920, 1020
    screen = pygame.display.set_mode(size)
    screen.fill((10, 200, 100))

    def display_card(card):
        screen.blit(pygame.image.load(card.img), card.coordonates)

    game = MackaoGame("Test1", "Test2")
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                game.change_card_status(pygame.mouse.get_pos())

        card_count = 0
        for player, deck in game.player_decks.items():
            new_cards = []
            for card in deck:
                card_image = pygame.image.load(card.img)
                card.make_coordonates((50 * card_count + 500, 500))
                if card.status == "selected":
                    card.coordonates[1] -= 100
                new_cards.append(card)
                card_count += 1
            game.player_decks[player] = new_cards

        for player, deck in game.player_decks.items():
            for card in deck:
                display_card(card)
        pygame.display.update()

if __name__ == "__main__":
   main()

This is the utilities file:
from random import sample
from PIL import Image

class Card:

    def __init__(self, num, symbol, img, status):
        self.num = num
        self.symbol = symbol
        self.img = img
        self.status = status
        with Image.open(img) as image:
            self.img_width, self.img_height = image.size
        self.coordonates = [0, 0]
        self.velocity = 0

    def __repr__(self):
        return "This card is a {num} of {symbol}.".format(num = self.num, symbol = self.symbol)

    def __eq__(self, other):
        if self.num == other.num and self.symbol == other.symbol:
            return True
        return False

    def make_coordonates(self, center):
        self.coordonates = [center[0] - self.img_width / 2, center[1] - self.img_height / 2]

class MackaoGame:
    def __init__(self, *players):
        self.players = players
        self.player_wait_times = {player: 0 for player in players}
        self.give_cards()
        self.card_debt = 0
        self.round = 0

    def make_deck(self):
        deck = []
        width_total = 543
        height_total = 278
        signs = ["clubs", "hearts", "spades", "diamonds"]
        row = -1
        with Image.open("playing_cards.png") as card_img:
            for i in range(4):
                row += 1
                for j in range(13):
                    box = (width_total / 13 * j, height_total / 4 * i, width_total / 13 * (j + 1), height_total / 4 * (i + 1))
                    card_img.crop(box).save("{j}_{i}.png".format(j = j, i = i))
                    deck.append(Card(j, signs[i], "{j}_{i}.png".format(j = j, i= i), "ready"))
        return deck

    def mix_deck(self, deck):
        return sample(deck, len(deck))

    def give_cards(self):
        remaining_deck = self.mix_deck(self.make_deck())
        main_deck = []
        player_decks = {}
        for name in self.players:
            if player_decks.get(name) is None:
                cards = []
                for i in range(5):
                    cards.append(remaining_deck.pop())
                player_decks[name] = cards
        main_deck.append(remaining_deck.pop())
        self.main_deck, self.remaining_deck, self.player_decks = main_deck, remaining_deck, player_decks

    def get_curent_player(self):
        self.round += 1
        self.curent_player = self.players[(round - 1) % len(self.players)]

    def put_cards(self):
        for player, deck in self.player_decks.items():
            for card in deck:
                if card.status == "selected":
                    self.main_deck.append(card)
                    self.player_decks[player].remove(card)

                if card.num == 2:
                    self.card_debt += 2
                if card.num == 3:
                    self.card_debt += 3
                if card.num == 4:
                    self.player_wait_times[player] = 0
                if card.num == 7:
                    self.card_debt = 0
                    self.player_wait_times[player] = 0

    def can_change_status(self, card):
        return True

    def change_card_status(self, coordonates):
        for player, deck in self.player_decks.items():
            new_cards = []
            for card in deck:
                if coordonates[0] > card.coordonates[0] and coordonates[0] < card.coordonates[0] + card.img_width and coordonates[1] > card.coordonates[1] and coordonates[1] < card.coordonates[1] + card.img_height:
                    if card.status == "ready":
                        if self.can_change_status(card):
                            card.status = "selected"
                            print(card.status)
                    elif card.status == "selected":
                        card.status = "ready"
                        print(card.status)
                new_cards.append(card)
            self.player_decks[player] = new_cards

"playing_cards.png":
!
"playing_cards.png"
This is how it looks now:

This is how I would want it to look, no card down below after clicking on it:

A: The card gets duplicated because you aren't clearing the screen within each frame, so the previous frames still appear. In pygame, we can clear the screen by using the fill function. We use the fill function like this: screen.fill((0, 0, 0)) (this fills the screen with the color black and also hides the previous frames). If you add that to your game loop, the card won't get duplicated.
Change your game loop to this:
while True:
    screen.fill((0, 0, 0)) # You can change this to the color of your choice
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            game.change_card_status(pygame.mouse.get_pos())

    card_count = 0
    for player, deck in game.player_decks.items():
        new_cards = []
        for card in deck:
            card_image = pygame.image.load(card.img)
            card.make_coordonates((50 * card_count + 500, 500))
            if card.status == "selected":
                card.coordonates[1] -= 100
            new_cards.append(card)
            card_count += 1
        game.player_decks[player] = new_cards

    for player, deck in game.player_decks.items():
        for card in deck:
            display_card(card)
    pygame.display.update()


text:
Q: Merging PDFs with Apache PDFBox & inserting after section I need to merge multiple files together to create a single PDF somehow. Ideally, I could take PDFs as input and then mash them together without having to worry about formatting, so I'm thinking do that for the time being. Eventually, it would be nice if I could scan through the PDF for some specific metadata about a section in a PDF, and insert content after that section.
Essentially, something like the id attribute in html for PDFs is what I need (short of scanning the PDF text as that may change). Worst case scenario, I could use JSON as an interim format and create a PDF from the JSON, but I'd prefer not to format the PDF on the fly if I don't have to. JSON->LaTeX->PDF (or maybe just LaTeX->PDF) seems like what I might be looking at there, which seems like more pre-processing than is strictly needed.
Basically, is there any way to do this just via some hidden PDF metadata, or am I looking at scanning the document text for keywords?
Footnote:
I'm assuming I'm going to be given either a text file (converted to JSON) or a PDF as the initial input, but I definitely do want PDF output. Basically, just creating a PDF is simpler than requiring this be written in JSON.


text:
Q: ARKit add 2D Video flipped by X So I have following code to create custom wall
    let wall = SCNPlane(width: CGFloat(distance),
                        height: CGFloat(height))
    wall.firstMaterial = wallMaterial()
    let node = SCNNode(geometry: wall)

    // always render before the beachballs
    node.renderingOrder = -10

    // get center point
    node.position = SCNVector3(from.x + (to.x - from.x) * 0.5,
                               from.y + height * 0.5,
                               from.z + (to.z - from.z) * 0.5)
    node.eulerAngles = SCNVector3(0,
                                  -atan2(to.x - node.position.x, from.z - node.position.z) - Float.pi * 0.5,
                                  0)

And Now I am adding simple SCNPlane on hit test and add video (skscene to it)
          // first.node is hittest result

            let node = SCNNode(geometry: SCNPlane(width: CGFloat(width) , height:  CGFloat(height))
            node.geometry?.firstMaterial?.isDoubleSided = true
            node.geometry?.firstMaterial?.diffuse.contents = self.create2DVideoScene(xScale: first.node.eulerAngles.y < 0 ? -1 : nil)
                         node.position = nodesWithDistance.previous.node.mainNode.position

            node.eulerAngles = first.node.eulerAngles

Here How I created 2d  node
 /// Creates 2D video scene
    private func create2DVideoScene (xScale:CGFloat?) -> SKScene {
        var videoPlayer = AVPlayer()

        if let validURL = Bundle.main.url(forResource: "video", withExtension: "mp4", subdirectory: "/art.scnassets") {
            let item = AVPlayerItem(url: validURL)
            videoPlayer = AVPlayer(playerItem: item)
        }
        let videoNode = SKVideoNode(avPlayer: videoPlayer)
        videoNode.yScale *= -1

        // While debug I observe that if first.node.rotation.y in  - , then we need to change xScale to -1 (when wall draw from right -> left )

        if let xScale = xScale {
            videoNode.xScale *= xScale

        }

        videoNode.play()

        let skScene = SKScene(size: self.sceneView.frame.size)
        skScene.scaleMode = .aspectFill
        skScene.backgroundColor = .green
        skScene.addChild(videoNode)
        videoNode.position = CGPoint(x: skScene.size.width/2, y: skScene.size.height/2)
        videoNode.size = skScene.size
        return skScene
    }

Issue  :: If I draw wall node from left to right means first point is on left side and other point on right side and draw wall between them. Then Video is flipped.
If I draw from right to left means first point is on right side and second point is on left side and draw line between them then video is perfectly fine.
To fix this I checked wall eulerAngles check the line self.create2DVideoScene but this is not working in every area of real world
I want video should not be start flipped in front of user
EDIT
video is flipped because of eulerAngles is different in both case while create a wall

Angle point1 to point2 --> (0.000000 -1.000000 0.000000 3.735537)
Angle point2 to point1 -- > (0.000000 -1.000000 0.000000 0.478615)

Issue video Click here to play video
Please please provide the suggestion or solution of this issue .

Video flipped

A: I have fixed issue with temporary solution still looking for a better one
Issue is of wall. wall is flipped other side of camera when draw from right to left direction. I have figure it out by setting isDoubleSided = false and by applying a image as diffuse contents   which has text and I can see that image is flipped itself.
I have tried many things but this one helps me

*

*Normalize vector

*Find the cross between to SCNVectors

*If y > 0 I just swapped from and to Value

Code
    let normalizedTO = to.normalized()
    let normalizedFrom = from.normalized()
    let angleBetweenTwoVectors = normalizedTO.cross(normalizedFrom)

    var from = from
    var to = to
    if angleBetweenTwoVectors.y > 0 {
        let temp = from
        from = to
        to = temp
    }

// Inside extension of SCNVector3
func normalized() -> SCNVector3 {
    if self.length() == 0 {
        return self
    }

    return self / self.length()
}

func cross(_ vec: SCNVector3) -> SCNVector3 {
        return SCNVector3(self.y * vec.z - self.z * vec.y, self.z * vec.x - self.x * vec.z, self.x * vec.y - self.y * vec.x)
    }

Hope it is helpful. If anyone know better solution please answer it.


text:
Q: How do you change a setting in TYPO3 Setup based on a Constant? In my constants I have a select dropdown with two options.
In my setup can I change the page.shortcutIcon setting depending on what that constant is set to?
Also, can I use the same constant to determine a setting in PageTSConfig or the rte .yaml config?

A: Its not possible to use Typoscript Template Constants (frontend).
In PageTS (Backend configuration)
Thr backend does not need and does not evaluate the configuration there.

A: Why don't you add an additional field to the pages record for your new value?
This value can be evaluated in the PageTS for backend conditions.
And it could be evaluated in the frontend. either in the regular typoscript setup (use data instead of constants) or in FLUID as field of your pagesdata.


text:
Q: FlaskForm cannot submit data I'm using Flask-WTF to submit data to a form, but I can't get any data when the form is submitted. This is my LoginForm class:
class LoginForm(FlaskForm):
    username=StringField('Username')
    password=PasswordField('Password')

    def validate(self):

        check_validate = super(LoginForm, self).validate()

        if not check_validate:
            return False
        logging.error('username is %s'%(self.username)
        user=User.query.filter_by(username=self.username.data).first()
        if not user:
            logging.error('username %s: Invalid username or password'%self.username.data)
            self.username.errors.append(
                'Invalid username or password'
            )

            return False

        if not user.checkPassword(self.password.data):
            logging.error('password %s:Invalid username or password'%self.password.data)
            self.username.errors.append(
                'Invalid username or password'
            )

            return False

        return True

And here is my form:
{% extends 'base.html' %}
{% from 'base.html' import input %}
{% block title %}Login{% endblock %}
{% block body %}
    <form method='POST' action="{{ url_for('main.login')}}">
        {{ form.hidden_tag() }}
        {{ input(form.username, 'Username') }}
        {{ input(form.password, 'Password') }}
        <input class='btn-primary' type='submit' value='Login'>
    </form>
{% endblock %}

the input file is a jinaja macro containing
{% macro input(name, label, value='', type='text') %}

        {{ label }}
        <input type='{{ type }}' name='{{ name }}' value='{{ value | escape }}' class='form-control'>

{% endmacro %}

so when I input some data in this form and submit, I always saw

ERROR:root:username is
  <input id="username" name="username" type="text" value="">

It seems like no data has been pass to LoginForm
What should I do?
@main_blueprint.route('/login', methods=('GET','POST'))
def login():
    form = LoginForm()

    if form.validate_on_submit():
        flash("Your have been logged in.", category="success")
        user = User.query.filter_by(username=form.username.data).first()
        return render_template(
            'user.html',
            user=user
        )
    return render_template('login.html', form = form)

main_blueprint = Blueprint(
    'main',
    __name__,
    template_folder='../templates/main'
)

new:
I tried to submit my form by 'GET' method, and I found my username and password was passed, but I still can't get them in my LoginForm

127.0.0.1 - - [02/Dec/2018 01:05:18] "GET /login?csrf_token=...input+
id%3D%22username%22+
name%3D%22username%22+
type%3D%22text%22+
value%3D%22%22%3E=mer&%3C
input+
id%3D%22password%22+
name%3D%22password%22+
type%3D%22password%22+
value%3D%22%22%3E=dly1234&
submit=Login+In HTTP/1.1" 200 -

'mer' and 'dly1234' is username and pwd I inputted.

A: The question was resolved, I read the login page's HTML code and found in my latest version the input in form is:

    <label for='<input id="username" name="username" type="text" value="">'>Username
    <input type='text' name='<input id="username" name="username" type="text" value="">' value='' class='form-control'>

I noticed the name in this is strange, So I back to change my jinja:
before:
{{ input(form.username, 'Username') }}

now:
 {{ input('username', 'Username') }}

End of the question.
And thanks @kosist, the Mega's tutorial gives me so many helpful, his implement method inspired me to compare the difference between our final HTML code.


text:
Q: How to avoid locks during DELETE in sqlite? The DELETE query is simple:
DELETE FROM pages WHERE status = 0

It takes around 15 minutes to complete (for removing ~20K rows). It's a ~500 MB database that maps a local files system, and contains around 3 million records.
The structure:

*

*pages - just a few records

*files - around 230K records, contains a foreign key constraint with ON DELETE CASCADE that references a column from pages

*meta - around 3 million records, contains foreign key constraints with ON DELETE CASCADE that reference columns from files and pages

*search - a FTS4 table, almost exact duplicate of meta. The integrity of this table is maintained with triggers.

CREATE TABLE pages(
  id       INTEGER PRIMARY KEY AUTOINCREMENT,
  slug     TEXT,
  name     TEXT NOT NULL,
  type     INTEGER NOT NULL DEFAULT 1,
  data     TEXT,
  parent   INTEGER,
  status   INTEGER DEFAULT 1,
  comments INTEGER DEFAULT 1,
  priority INTEGER DEFAULT 0,
  UNIQUE(slug),
  FOREIGN KEY(parent) REFERENCES pages(id) ON DELETE CASCADE
);

CREATE INDEX "pageParent" ON "pages"("parent");

CREATE TABLE files(
  id        INTEGER PRIMARY KEY AUTOINCREMENT,
  gallery   INTEGER NOT NULL,
  type      INTEGER NOT NULL DEFAULT 1,
  sPath     TEXT,
  rPath     TEXT,
  parent    INTEGER,
  hero      INTEGER,
  hidden    INTEGER DEFAULT 0,
  createdAt DATETIME,
  mTime     TEXT,
  UNIQUE(sPath),
  FOREIGN KEY(gallery) REFERENCES pages(id) ON DELETE CASCADE,
  FOREIGN KEY(parent)  REFERENCES files(id) ON DELETE CASCADE,
  FOREIGN KEY(hero)    REFERENCES files(id) ON DELETE SET NULL
);

CREATE INDEX "fileGallery" ON "files"("gallery");
CREATE INDEX "fileType"    ON "files"("type");
CREATE INDEX "fileParent"  ON "files"("parent");
CREATE INDEX "fileRPathNS" ON "files"("rPath" COLLATE NATSORT);

CREATE TABLE thumbs(
  hash    TEXT,
  image   INTEGER,
  width   INTEGER,
  height  INTEGER,
  FOREIGN KEY(image) REFERENCES files(id) ON DELETE CASCADE,
  PRIMARY KEY(hash, image) ON CONFLICT REPLACE
);

CREATE INDEX "thumbImage" ON "thumbs"("image");

CREATE TABLE meta(
  id      INTEGER PRIMARY KEY AUTOINCREMENT,
  file    INTEGER NOT NULL,
  key     TEXT NOT NULL,
  value   TEXT,
  extra   TEXT,
  gallery INTEGER,
  FOREIGN KEY(gallery) REFERENCES pages(id) ON DELETE CASCADE,
  FOREIGN KEY(file) REFERENCES files(id) ON DELETE CASCADE
);

CREATE INDEX "metaFileId" ON "meta"("file");
CREATE INDEX "metaKey"    ON "meta"("key");
CREATE INDEX "metaExtra"  ON "meta"("extra");

CREATE VIRTUAL TABLE search USING fts4(file, key, value, gallery);

CREATE TRIGGER metaBeforeUpd BEFORE UPDATE ON meta BEGIN
  DELETE FROM search WHERE docid = OLD.rowid;
END;

CREATE TRIGGER metaBeforeDel BEFORE DELETE ON meta BEGIN
  DELETE FROM search WHERE docid = OLD.rowid;
END;

CREATE TRIGGER metaAfterUpd AFTER UPDATE ON meta BEGIN
  INSERT INTO search(docid, file, key, value, gallery) VALUES(NEW.rowid, NEW.file, NEW.key, NEW.value, NEW.gallery);
END;

CREATE TRIGGER metaAfterIns AFTER INSERT ON meta BEGIN
  INSERT INTO search(docid, file, key, value, gallery) VALUES(NEW.rowid, NEW.file, NEW.key, NEW.value, NEW.gallery);
END;

The problem is that not only it's slow, but it also locks these tables so I cannot do any changes to them during this time.
I tried every suggestion from this question and answers but without significant improvements. Setting journaling mode to MEMORY and turning off sync made it run a little faster, but it's too risky.
To avoid long write locks, I tried deleting records step by step, 40 at time with a 0.5s delay between. But this slows down the entire process even by 10x
Is there any other way I can improve the speed and/or avoid locks?

PS: What baffles me is that INSERTs are much faster. It takes 2 minutes to insert the amount of records I was deleting, and that time includes some heavy file processing (Exif reading from lots of images). Why is removing records slower than inserting?

A: Deleting from pages is slow because there is no index on the gallery column in the meta table.
Whenever a pages record is actually deleted, the database has to search for any meta records that match the ON DELETE CASCADE constraint; this results in a full table scan for every deleted record.
(The INSERTs are faster because no such check must be made.)
SQLite is not designed for concurrency; it is never possible to have multiple writers at the same time.
However, to allow multiple readers at the same time as a writer, consider enabling write-ahead logging.


text:
Q: PS Azure automation runbook ; How to Mount Azure File Share? Trying to mount Azure FS from Powershell runbook in Azure Automation.
Via username and key
$UserName = "localhost\trex4xfs"
$Key = "Zav---mykey-----1Tdw=="
$RemotePath = "\\myshare.file.core.windows.net\mainfs"
$MapDrive = "z:"

Get-Command -Name *SmbMapping* | ft

[securestring]$pass = ConvertTo-SecureString $key -AsPlainText -Force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $pass

new-psdrive -name T -PsProvider FileSystem -root $RemotePath -credential $credential
Get-PSDrive | ft

echo "--------now import smb"
Import-Module smbshare
echo "--------now smb"
New-SmbMapping -LocalPath $MapDrive -RemotePath $RemotePath -UserName $UserName -Password $Key

Above works great on "plain Powershell on Windows"
Tried

*

*Runbook with 5.1 and 7.1 PS version

*new-psdrive (error: This function is not supported on this system )

*New-SmbMapping (error 7.1:  The 'New-SmbMapping' command was found in the module 'SmbShare', but the module could not be loaded. For more information, run 'Import-Module SmbShare'

*New-SmbMapping (error 5.1: Cannot connect to CIM server. The specified service does not exist as an installed service. )

*Import-Module smbshare (error  Failed to generate proxies for remote module 'smbshare'. Cannot overwrite the item C:\Users\Client\Temp\tmp_5t22mi1k.oh0\remoteIpMoProxy_smbshare_2.0.0.0_localhost_f29e4e95-e8cf-4256-a4db-fc9381c6563c.format.ps1xml with itself.)

*New-CimSession (error: The specified service does not exist as an installed service.)

Seem to be related to New-CimSession not available on Azure Automation runbook
other questions related to this:

*

*Azure Runbook - Get a file from Azure File System Storage

*Not able to access Azure FileShare Storage container from Azure Automation Runbook

*Map a Azure Fileshare to Azure Runbook local drive to use as temporary storage

A: One of the related question which you have shared already provides the answer (i.e., this one) which basically says to use hybrid runbook worker in your use case scenario.


text:
Q: Get width of svg element from uploaded file I selected a svg file and read it via readDataUrl(<file>), I can set it to an html image element by setting the src to be the value read from the file. However the width and height attributes will be 0. How can I set the value read from a file to an svg element in order to be able to do a getBBox().width to obtain its width?

A: You can use XMLHttpRequest (or your favourite AJAX library) to read and parse the SVG file.  I imagine you can even just pass the dataurl to it if you want.

A: Edit, because I misread the question :

*

*If you can append the svg to your document, and need to use a FileReader, use its readAsText() method, then insert it in an html element.

function previewFile() {
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    var parent = document.getElementById('container');
    parent.innerHTML= reader.result;
  }

  if (file && file.type=="image/svg+xml") {
    reader.readAsText(file);
  } else {
    alert("wrong file type or no file provided");
  }
}

<input type="file" onchange="previewFile()">

*

*If you don't need to use a FileReader (e.g if the file is saved on the server), Paul's answer is better.

*If you don't want to actually append the svg file but only know its width/height, you can refer to my
original answer :
I don't think you can get the height from the data url.
As a workaround, you can use the readAsText()method of the fileReader API, combined with the DOMParser() method, in order to read the viewBox property of the svg.

function xlog(msg){
 document.getElementById('log').textContent = msg;
 }
function previewFile() {
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
  var doc = new DOMParser().parseFromString(reader.result, 'application/xml');
 var viewBox = doc.documentElement.viewBox.baseVal;
 xlog('height:'+viewBox.height+' width:'+viewBox.width);
  }

  if (file && file.type=="image/svg+xml") {
    reader.readAsText(file);
  } else {
    xlog("wrong file type or no file provided");
  }
}

<input type="file" onchange="previewFile()">

Note that you can append the doc.documentElement into your document and then get the element's BBox.


text:
Q: When will anonymous array/hash be garbage collected in perl? I know that perl can't detect the recursive reference as :
$a = \$a;

$a will never be GCed in this case.
What about :
@a = ({1,2,3}, [1,2,3]);

Will the anonymous {1,2,3} and [1,2,3] be collected when @a goes out of scope?
How to prove it's yes or no?

A: When @a = ({1,2,3}, [1,2,3]); goes out of scope, its reference count will be reduced by one*.
When the reference count of @a reaches zero, the reference count of its values will be reduced by one, and it will be freed.
When the reference count of $a[0] (a reference to a hash) reaches zero, the reference count of the referenced hash will be reduced by one, and it will be freed.
When the reference count of the anonymous hash reaches zero, the reference count of the its values will be reduced by one, and it will be freed.
When the reference count of one of the anonymous's hash's values reaches zero, the reference count of the its values will be reduced by one, and it will be freed.
Same goes for $a[1], the array it references and the values of that array.
You can "prove" this by using objects with destructors.
$ perl -E'
   package X {
      sub new { my ($c,$n) = @_; bless(\$n, $c) }
      DESTROY { say ${$_[0]}; }
   }
   {
      my @a = (
         { a => X->new(1), b => X->new(2) },
         [ X->new(3), X->new(4) ],
      );
      say "Before end of scope";
   }
   say "After end of scope";
'
Before end of scope
4
3
2
1
After end of scope

* — Actual implementation differs as an optimisation.

A: Perl can garbage-collect circular references if you "weaken" them using Scalar::Util's weaken function:
weaken REF
    REF will be turned into a weak reference. This means that it will
    not hold a reference count on the object it references. Also when
    the reference count on that object reaches zero, REF will be set to
    undef.

As far as garbage-collecting things that have gone out of scope, there's no one answer. It depends on your operating system and how perl was compiled. It's not something you should generally be worried about. perlfaq3 has a couple of relevant entries:

*

*How can I make my Perl program take less memory?

*How can I free an array or hash so my program shrinks?

A: If there is nothing more referring the anonymous hash it will be collected.
This will give you a complete answer!

A: Another way to prove that the inner elements will be GCed when out of scope:
use Scalar::Util 'weaken';

my $x;

{
    my @a = ({foo => 'bar'}, ['foo', 'bar']);

    $x = $a[1]; # ref to the inner array
    weaken $x; # weaken the ref, so it doesn't interfere with GC
    print "'$x->[1]'\n"; # show us what we got
}

print "'$x->[1]'\n"; # and now it's gone

Outputs:
'bar'
''

weaken REF
REF will be turned into a weak reference. This means that it
  will not hold a reference count on the
  object it references. Also when the
  reference count on that object reaches
  zero, REF will be set to undef.
This is useful for keeping copies of
  references , but you don't want to
  prevent the object being DESTROY-ed at
  its usual time.

A: Actually when an array/hash goes out of scope,its values(the reference in keys are just taken as string so won't impact the refcount) will decrease their refcount,and if reaches 0,the operation will performe recursively.


text:
Q: JSON.stringify won't work on JSON Object where properties are created with Object.defineproperty I'm currently writing a web scraping discord bot and want to implement the logic. I create the final Object it also has all properties that i set but when i try to console.log(totalData) it returns {}
same result when i do console.log(JSON.stringify(totalData)) => {}
i have also tried it with console.dir(), console.table()
The code:
const puppeteer = require('puppeteer')

let url = "https://www.worldometers.info/coronavirus/";

async function scrapeAllByCountry(page, country){
   const totalData = {}
   let endPosition;

   // XPath to the data
   allData = ["/html/body/div[3]/div[3]/div/div[6]/div[1]/div/table/tbody[1]"]
   headerData = ["Country", "Total Cases", "New Cases", "Total Deaths", "New Deaths", "Total Recovered", "New recovered", "Active Cases", "Serious, Critical", "Total Cases/1M pop", "Deaths/1M pop", "Total Tests", "Tests/1M pop", "Population"]

   // scraping the data
   var element = await page.waitForXPath(allData[0])
   let allTableData = await page.evaluate(element => element.textContent, element)

   allTableData = allTableData.toLowerCase()
   // replacing comma with nothing so numbers return false when i call isNaN()
   allTableData = allTableData.replaceAll(",", "")

   // searches for the country in the string and saves it into positionCountry
   let positionCountry = allTableData.search(country.toLowerCase())
   // Adds 150 more chars so the full Data is in it
   let data = allTableData.substring(positionCountry, positionCountry + 150)
   // creates array for each row
   tempDataArray = data.split("\n");

   // searches for the next NAN in the array and sets the end position
   for(let i = 0; i < tempDataArray.length; i++){
      // if the current element is a number do nothing if it is a NaN set endPosition and exit
      if(isNaN(tempDataArray[i]) & i != 0){
         endPosition = i
         break;
      }
   }

   // create new Array with endposition
   let filteredArray = [];
   for(let i = 0; i < endPosition; i++){
      filteredArray.push(tempDataArray[i])
   }

   // Merge both Arrays into Object
   for(let i = 0; i < filteredArray.length; i++){
      // sets the header with a value on the totalDataObject
      Object.defineProperty(totalData, headerData[i], {
         value: filteredArray[i],
         writable: false
      })
      // here it confirms that it has all Properties
      console.log(totalData.hasOwnProperty(headerData[i]))
   }

   console.log(JSON.stringify(totalData)) // outputs {}

   return totalData
}

async function main(){
   const browser = await puppeteer.launch({})
   const page = await browser.newPage()

   await page.goto(url)

   let result = await scrapeAllByCountry(page, "Germany")
   console.log(JSON.stringify(result)) // also returns {}
   console.log(result.hasOwnProperty("Country"))

   browser.close()

}

main();


text:
Q: Citation with Harvard as an argument throws error I'm trying to include the source citation everytime I use an image in my thesis. I have a self-written command to ease that process (code at the end of the post):
\bild[citation]{label for refs}{file}{name of the image}{size in cm}

When I try to include citation as a \cite-command (using the harvard-package), latex throws following error:
<argument> \cite
                 {ferstl_grundlagen_2008}
\equal #1#2#3->\TE@throw \def \@tempa {#1
                                         }\def \@tempb {#2}\noexpand \ifx \@...

\NROrg@ifthenelse ...eval \the \toks@ \TE@endeval
                                                  }\endgroup \@gtempa \expan...

\\bild ...-0.3cm\ifthenelse {\equal {#1}{\empty }}
                                                   {\caption [{#4}]{#4}} {\c...
l.12 ...en/aufgabenstruktur}{Aufgabenstruktur}{12}

?

The command I used was following:
\bild[\cite{ferstl_grundlagen_2008}]{aufgabenstruktur}{FeSi-Aufgaben/aufgabenstruktur}{Aufgabenstruktur}{12}

I think this is a problem of the harvard implementation of \cite, as I recently used this piece of code with the bibgerm-package, where it worked like a charm. What am I doing wrong here? Is there any easy way to fix this problem?
Thanks in advance,
Uli
EDIT: Code of the \bild-macro:
\newcommand{\bild}[5][\empty]{%
  \begin{figure}[htb]%
    \begin{center}%
      \includegraphics[width=#5cm]{images/#3}%
      \vskip -0.3cm%
    \ifthenelse{\equal{#1}{\empty}}
        {\caption[{#4}]{#4}}
            {\caption[{#4} \newline \small{\textit{Quelle: #1}}]{#4}}%
      \vskip -0,2cm%
      \label{#2}%
    \end{center}%
  \end{figure}%
}

Used packages & document class:
\documentclass[a4paper, 12pt]{article}
\usepackage{german}
\usepackage[latin1]{inputenc}
\usepackage{fancyhdr}
\usepackage[T1]{fontenc}
\usepackage{ae}
\usepackage{listings}
\usepackage{color}
\usepackage{listings}
\usepackage{harvard}
\usepackage{wrapfig}
\usepackage{helvet}
\usepackage{txfonts}
\usepackage{geometry}
\usepackage{setspace}
\usepackage{hyperref}
\usepackage{sectsty}
\usepackage{acronym}
\usepackage{eurosym}

A: (Answer updated with full MWE)
Not having access to your image files or the bib file that sets up the entry with key ferstl_grundlagen_2008, I can't be entirely sure what's going on. Here's a suggested solution:
\documentclass{article}
\usepackage{german,harvard,ifthen}
\usepackage[demo]{graphicx} % get rid of 'demo' option in real document
\usepackage{hyperref}
\newcommand{\bild}[5][\empty]{%
  \begin{figure}[htbp]%
     \centering
     \includegraphics[width=#5cm]{images/#3}%
     \caption{#4}
     \label{#2}%
     \ifthenelse{\equal{#1}{\empty}}
        {}
        {\small\emph{Quelle: #1}}
  \end{figure}%
}

\begin{document}
\bild[Ferstl (2008)]{fig:1}{FeSi-Aufgaben/aufgabenstruktur}%
   {Aufgabenstruktur}{12}
\bild{fig:2}{FeSi-Aufgaben/aufgabenstruktur}{Neue Aufgabenstruktur}{10}
\end{document}

Incidentally, given that you use the harvard citation management package, you should probably be using the command \citeasnoun rather than \cite in the first, optional argument of \bild.
In addition, since it appears that you use the hyperref package as well, you may want to load the natbib and har2nat packages instead of the harvard package. The reason for this recommendation is that while hyperref works sort of OK with several citation management packages, it really does work best with the natbib package. As you can probably tell from its name, the har2nat package "translates" harvard-style citation commands (such as \citeasnoun) to equivalent natbib-style citation commands. That way, you can keep using the harvard-style citation commands while getting all the benefits of the good interplay between the natbib and hyperref packages


text:
Q: Can somebody explain me the following LINQ code? I am having trouble interpreting code from someone else.
I know the behavior, but I don't understand how.
Behavior:

*

*driverRemark has a sequence number and can be linked to a group.
The group that contains the remark with the lowest seq nr should be printed out first. and so on.
If 2 remarks have the lowest seq nr, the lowest group should be printed first. except when its null, null should be printed last.

Can somebody explain me what is happening here?
 var groupedDriverRemarks = driverRemarks
                .GroupBy(dr => dr.RemarkGroup)
                .OrderBy(g => g.Key == null)
                .ThenBy(g => g.Key)
                .OrderBy(gr => gr.Min(dr => dr.SeqNr))
                .SelectMany(g => g.OrderBy(dr => dr.SeqNr))
                .ToList();

 return groupedDriverRemarks;

I have no clue how this function operates. It does work, but no clue why.
I tried searching all the different LINQ methods and try to translate it. But without any result.

A: Here is a commented version of the code:
var groupedDriverRemarks = driverRemarks
                .GroupBy(dr => dr.RemarkGroup) // group driver remarks by RemarkGroup
                .OrderBy(g => g.Key == null) // order groups so null RemarkGroup is last
                .ThenBy(g => g.Key) // order non-null remark groups by RemarkGroup
                .OrderBy(gr => gr.Min(dr => dr.SeqNr))
                // re-order remark groups by minimum of SeqNr;
                // since previous ordering is preserved, any duplicate minimum SeqNr will be ordered by RemarkGroup with null last still
                .SelectMany(
                    g => g.OrderBy(dr => dr.SeqNr) // sort contents of each group in SeqNr order
                ) // flatten SeqNr sorted groups into single stream
                .ToList(); // convert ordered driver remarks to a List<T>

The use of multiple sorts is not an efficient way to handle sub-sorts, the ThenBy method is intended for this, so you have one sort that works correctly. Here is an improved version; it uses one sort before grouping to pre-order all the driver remarks so the final result is properly sorted after grouping.
var orderedDriverRemarks =
    driverRemarks
        .OrderBy(dr => dr.SeqNr) // order the driver remarks by SeqNr
        .OrderBy(dr => dr.RemarkGroup == null) // then order duplicate SeqNr so the null RemarkGroup remarks are last
        .ThenBy(dr => dr.RemarkGroup) // then order by RemarkGroup for the non-null remarks with duplicate SeqNr
        .GroupBy(dr => dr.RemarkGroup) // group driver remarks by RemarkGroup
        // since GroupBy is order preserving, the groups will be ordered by their first SeqNr
        // which is the minimum SeqNr in each group, then duplicate min SeqNrs will be ordered
        // by RemarkGroup with null last
        // in addition, the contents of each group will be ordered by SeqNr
        .SelectMany(g => g) // flatten groups into single stream
        .ToList(); // convert ordered driver remarks to a List<T>


text:
Q: How to remove a line from quick book invoice by using php quickbooks api we are using php quickbooks api.
we want to delete a line from quickbooks invoice.
we are using below code to delete a line from invoice, but it did not worked and it did not shows any error.
$Qbinvoice = $InvoiceService->query($Context, $realm, "SELECT * FROM Invoice WHERE Id = '$quickBookInvoiceId' ");
$QBSubInvoices = $Qbinvoice[0];
$lines = $QBSubInvoices->getLine();
$count = $QBSubInvoices->countLine();

for ($i = 0; $i < $count; $i++) {
    $QBSubInvoices->unsetLine($lines->$i);
}

Please help me any one, thanks in advance.


text:
Q: How to change svg color on Hover every one , i am using angular and i have a svg , html like :
  <button
    type="button"
    class="filter-icon-wrapper padding-0 border-0 outline-0 bg-transparent pointer"
  >
    <mat-icon class="filter-icon" *ngIf="!isDateType" svgIcon="filter_default">filter_alt</mat-icon>
  </button>

this is the svg source code filter_default:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11.9 11.91"><defs><style>.cls-2{fill:#707070;}</style></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><g id="Path_7587" data-name="Path 7587"><path class="cls-2" d="M6.8,11.91a1,1,0,0,1-.58-.19l-1.7-1.19a1,1,0,0,1-.43-.83V5.52L.3,1.73A1,1,0,0,1,0,1,1,1,0,0,1,.29.3,1,1,0,0,1,1,0h9.88a1,1,0,0,1,.72.29,1,1,0,0,1,0,1.44L7.82,5.52v5.37a1,1,0,0,1-.19.59A1,1,0,0,1,6.8,11.91ZM1,1,5.09,5.11V9.7L6.8,10.9l0-5.79L10.9,1V1Z"/></g></g></g></svg>

I want to know how can i change the svg color when mouse hover , thanks all of your help!

A:

#Path_7587 .cls-2 {
  fill:#707070;
}
#Path_7587 .cls-2:hover {
  fill: red;
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11.9 11.91"><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><g id="Path_7587" data-name="Path 7587"><path class="cls-2" d="M6.8,11.91a1,1,0,0,1-.58-.19l-1.7-1.19a1,1,0,0,1-.43-.83V5.52L.3,1.73A1,1,0,0,1,0,1,1,1,0,0,1,.29.3,1,1,0,0,1,1,0h9.88a1,1,0,0,1,.72.29,1,1,0,0,1,0,1.44L7.82,5.52v5.37a1,1,0,0,1-.19.59A1,1,0,0,1,6.8,11.91ZM1,1,5.09,5.11V9.7L6.8,10.9l0-5.79L10.9,1V1Z"/></g></g></g></svg>

A: Similar to the first answer, with one correction. The right class to modify is cls-2:
.cls-2:hover {
  fill:red;
}

A: thanks all of your help , i try ng-deep and now work fine

*

*rename the class name in svg from cls-2 to floatTextIcon

*in the scss file add such code
:host ::ng-deep .floatTextIcon:hover {
fill: #3a464d;
}

A: Changing the icon color when hovering a button:
button .cls-2 {
  fill: #888;
}

button:hover .cls-2 {
  fill: blue;
}

button {
  width: 50px;
  height: 50px;
}

button .cls-2 {
  fill: #888;
}

button:hover .cls-2 {
  fill: blue;
}
<button>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11.9 11.91"><g id="Layer_2" data-name="Layer 2" width="32" height="32"><g id="Layer_1-2" data-name="Layer 1"><g id="Path_7587" data-name="Path 7587"><path class="cls-2" d="M6.8,11.91a1,1,0,0,1-.58-.19l-1.7-1.19a1,1,0,0,1-.43-.83V5.52L.3,1.73A1,1,0,0,1,0,1,1,1,0,0,1,.29.3,1,1,0,0,1,1,0h9.88a1,1,0,0,1,.72.29,1,1,0,0,1,0,1.44L7.82,5.52v5.37a1,1,0,0,1-.19.59A1,1,0,0,1,6.8,11.91ZM1,1,5.09,5.11V9.7L6.8,10.9l0-5.79L10.9,1V1Z"/></g></g></g></svg>
</button>


text:
Q: Trouble with log stash @timestamp I have set up ELK on my laptop and I am having trouble with the timestamp field.
My input file looks like this ... (one line so far)
Chckpoint 502 10.189.7.138 Allow 18 Mar 2015 15:00:01

My code looks like this ..
input {
  file {
    path => "/usr/local/bin/firewall_log"
  }
}

filter {
  grok {
    match => {"message", "%{WORD:type} %{NUMBER:nums} %{IP:sourceip} %{WORD:Action}"}
   add_tag => "checkpoint"
  }

date {
  match => {"DATETIME" => "%{dd mmm yyyy hh:mm:ss}"}
  target => "@timestamp"
}
}

output {
  elasticsearch { host => localhost }

When I run it, I get the following result
"message" => "Chckpoint 502 10.189.7.138 Allow 18 Mar 2015 15:00:01   ",
      "@version" => "1",
    "@timestamp" => "2015-04-30T19:02:21.663Z",
          "host" => "UOD-220076",
          "path" => "/usr/local/bin/firewall_log",
          "type" => "Chckpoint",
          "nums" => "502",
      "sourceip" => "10.189.7.138",
        "Action" => "Allow",
          "tags" => [
        [0] "checkpoint"

This is fine EXCEPT for the timestamp - it shows todays date but what I want it to do is set the timestamp to what is in the log file, in this case, 18 Mar 2015 15:00:01.
Help please.

A: That's what the date{} filter will do for you, if you give it the right info.
First, define a custom pattern for your timestamp:
MYTIMESTAMP %{MONTHDAY} %{MONTH} %{YEAR} %{TIME}

Then add it to your grok pattern so you get a new field:
%{WORD:type} %{NUMBER:nums} %{IP:sourceip} %{WORD:Action} %{MYTIMESTAMP:mytime}

Then you can pass the mytime variable to the date filter:
date {
  match => {"mytime" => "dd MM YYYY HH:mm:ss"}
}


text:
Q: Using pytest-cov plugin from inside PyCharm I want to use pytest and pytest-cov plugin from inside PyCharm, so I added --cov=package to "Additional arguments" entry field when I edited my configuration. However, I get both the output and the error, not sure why:
Testing started at 4:50 PM ...
/home/alex/.repos/codelib/github/dsa/env/bin/python /home/alex/Downloads/pycharm-2019.3.4/plugins/python/helpers/pycharm/_jb_pytest_runner.py --path /home/alex/.repos/codelib/github/dsa/ -- --cov=bag
Launching pytest with arguments --cov=bag /home/alex/.repos/codelib/github/dsa/ in /home/alex/.repos/codelib/github/dsa/bag/tests

============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 -- /home/alex/.repos/codelib/github/dsa/env/bin/python
cachedir: .pytest_cache
rootdir: /home/alex/.repos/codelib/github/dsa
plugins: cov-2.8.1
collecting ... collected 1 item

test_simple_bag.py::test_len PASSED                                      [100%]

Coverage statistics reporting failed
Traceback (most recent call last):
  File "/home/alex/Downloads/pycharm-2019.3.4/plugins/python/helpers/pycharm/teamcity/pytest_plugin.py", line 371, in pytest_terminal_summary
    self._report_coverage()
  File "/home/alex/Downloads/pycharm-2019.3.4/plugins/python/helpers/pycharm/teamcity/pytest_plugin.py", line 378, in _report_coverage
    from coverage.report import Reporter
ImportError: cannot import name 'Reporter'

----------- coverage: platform linux, python 3.6.9-final-0 -----------
Name                                                     Stmts   Miss  Cover
----------------------------------------------------------------------------
/home/alex/.repos/codelib/github/dsa/bag/__init__.py         0      0   100%
/home/alex/.repos/codelib/github/dsa/bag/simple_bag.py      17      5    71%
__init__.py                                                  0      0   100%
test_simple_bag.py                                           6      0   100%
----------------------------------------------------------------------------
TOTAL                                                       23      5    78%

============================== 1 passed in 0.03s ===============================

Process finished with exit code 0

When I run tests from the terminal, everything goes fine:
(env) alex@smartalex-pc:~/.repos/codelib/github/dsa$ pytest --cov=bag
============================================== test session starts ===============================================
platform linux -- Python 3.6.9, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /home/alex/.repos/codelib/github/dsa
plugins: cov-2.8.1
collected 1 item

bag/tests/test_simple_bag.py .                                                                             [100%]

----------- coverage: platform linux, python 3.6.9-final-0 -----------
Name                           Stmts   Miss  Cover
--------------------------------------------------
bag/__init__.py                    0      0   100%
bag/simple_bag.py                 17      5    71%
bag/tests/__init__.py              0      0   100%
bag/tests/test_simple_bag.py       6      0   100%
--------------------------------------------------
TOTAL                             23      5    78%

=============================================== 1 passed in 0.03s ================================================
(env) alex@smartalex-pc:~/.repos/codelib/github/dsa$

A: That's because PyCharm's test plugin didn't adapt to breaking changes in coverage>=5.0 yet. Here's a related issue in JetBrain's tracker: PY-40980. Until the issue is fixed, pin coverage to previous major:
$ pip install 'coverage<5'


text:
Q: Need clarification on flow of android debugger connect protocol over network We have Android 7.1 booted on qemu kind of virtual platform. We are trying to connect ADB debugger over network. The platform uses slirp for communication between virtual platform and the host. We have bound port 5585 on android running on virtual platform to port 15585 on host.
Once Android is booted, using terminal on Android device, we are setting adb port to 5585 as below,
$ stop adbd
$ setprop service.adb.tcp.port 5585
$ start adbd
We are using one more machine on which Android SDK is running. We are issuing following command on Android machine,
adb tcpip 15585
adb connect :15585
When we analyzed packet captured on virtual platform hosting Android, we observe that we are getting request for ADB connect on port 5585 but stack on Android is not able to communicate back to the connect request.
From Android platform, we are seeing ARP requests are going out to resolve IP address of machine which initiated connect request, but it is not getting any response.
My question is, whether Android daemon will not respond till ARP request response is not got? or daemon can still respond to the connect request without ARP request not getting response?


text:
Q: Define an Objectkey dynamic with angular i have this object:
$scope.objecttest = [{
        "Datum": "2015-1-31",
        "y-title": "Testname",
        "test1": 920,
        "test2": 280
        }];

It works fine. But now i want to fill the Keys dynamicly. for example:
var testvariable = "HelloWorld";
$scope.objecttest = [{
        "Datum": "2015-1-31",
        "y-title": "Testname",
        testvariable: 920,
        "test2": 280
        }];

But when i want access to the key i only get the variablename "testvariable" as key and not the "HelloWorld".
For extracting the key, i use:
var data = $scope.objecttest;
var valuesnumber = Object.keys(data[0]).length;
var values = [];
for (i = 0; i <= valuesnumber; i++) {
    values[i] = Object.keys(data[0])[i];
}
alert(values[2]);

I hope somebody can help me. :)
Greetings


text:
Q: Can I detect if my custom made kernel was built with module support? I have been provided with a vendor supplied minimal linux installation. From an answer to a previous question I discovered that it is possible to build a kernel with or without module support. I have a CANBUS device that I need to attach which comes with drivers in the form of .ko files. I would like to be able to install these with the provided install scripts, but firstly I need to know if my kernel was built with module support - is it possible for me to detect this from the command line??
When I run lsmod it returns nothing so I know that there are no .ko files there at the moment - but doest this mean that the kernel won't allow me to install a .ko file ?

A: Most distributions store a text file with the kernel configuration somewhere. On a Debian system you'll find it in /boot/config-<kernel_version>.
Then you can simply run grep on that file:
grep CONFIG_MODULES /boot/config-<kernel_version>

A: If you have a /proc filesystem, the file /proc/modules exists if and only if the kernel if compiled with module support. If the file exists but is empty, your kernel supports modules but none are loaded at the moment. If the file doesn't exist, your kernel cannot load any module.
It's technically possible to have loadable module support without /proc. You can check for the presence of the init_module and delete_module system calls in the kernel binary. This may not be easy if you only have a compressed binary (e.g. vmlinuz or uImage). See How do I uncompress vmlinuz to vmlinux? for vmlinuz. Once you've managed to decompress the bulk of the kernel, search for the string sys_init_module.
Note that if modules are supported, you'll need additional files to compile your own modules anyway: kernel headers. These are C header files (*.h), some of which are generated when the kernel is compiled (so you can't just take them from the kernel source). See What does a kernel source tree contain? Is this related to Linux kernel headers?


text:
Q: Async test with jest returning empty div So i have this axios test and Im getting an empty div, not sure why.
test
import React from 'react';
import ReactDOM from 'react-dom';
import TestAxios from '../test_axios.js';
import {act, render, fireEvent, cleanup, waitForElement} from '@testing-library/react';
import axiosMock from "axios";

afterEach(cleanup)

it('Async axios request works', async () => {
  const url = 'https://jsonplaceholder.typicode.com/posts/1'
  const { getByText, getByTestId } = render(<TestAxios url={url} />);

  act(() => {
    axiosMock.get.mockImplementation(() => Promise.resolve({ data: {title: 'some title'} })
         .then(console.log('ggg')) )
  })

  expect(getByText(/...Loading/i).textContent).toBe("...Loading")

  const resolvedSpan = await waitForElement(() => getByTestId("title"));

  expect((resolvedSpan).textContent).toBe("some title");

  expect(axiosMock.get).toHaveBeenCalledTimes(1);
  expect(axiosMock.get).toHaveBeenCalledWith(url);

 })

the component
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const TestAxios = (props) => {
  const [state, setState] = useState()

  useEffect(() => {
    axios.get(props.url)
      .then(res => setState(res.data))
  }, [])

  return (

 Test Axios Request

      {state
        ?
{state.title}

        :
...Loading
}

  )
}

export default TestAxios;

the mock function
export default {
  get: jest.fn().mockImplementation(() => Promise.resolve({ data: {} }) )
};

so Im supposed to get a p element with some text but I get nothing. I have tried many different things bt cant seem to get it work not sure why its not working

A: So I figured it out it turns out you have to call axios.mockresolved value before the rendering of the component, otherwise it will just use the value you provided as the default in your mock axios module.
import React from 'react';
import ReactDOM from 'react-dom';
import TestAxios from '../test_axios.js';
import {act, render, fireEvent, cleanup, waitForElement} from '@testing-library/react';
import axiosMock from "axios";

afterEach(cleanup)

it('Async axios request works', async () => {
  axiosMock.get.mockResolvedValue({data: { title: 'some title' } })

  const url = 'https://jsonplaceholder.typicode.com/posts/1'
  const { getByText, getByTestId, rerender } = render(<TestAxios url={url} />);

  expect(getByText(/...Loading/i).textContent).toBe("...Loading")

  const resolvedEl = await waitForElement(() => getByTestId("title"));

  expect((resolvedEl).textContent).toBe("some title")

  expect(axiosMock.get).toHaveBeenCalledTimes(1);
  expect(axiosMock.get).toHaveBeenCalledWith(url);
 })


text:
Q: How to wrap child elements in a parent tag using xmlstarlet I want to wrap "table" elements with a new parent anywhere in the xml file. Am new using xmlstarlet.
Input:

<oldTable>

</oldTable>

Desired output:
<newparent id="tab">

</newparent>

<oldTable>
    <newparent id="tab">

    </newparent>
<oldTable>

A: Assuming a POSIX shell:
xmlstarlet edit \
  --var T '//table[not(parent::newparent)]' \
  -i '$T' -t 'elem' -n 'newparent' \
  -a '$prev' -t 'attr' -n 'typ' -v 'wtab' \
  -u '//newparent[following-sibling::*[1][self::table]]' \
  -x 'following-sibling::*[1]' \
  -d '$T' \
file.xml > newfile.xml

where:

*

*--var T … collect candidate table elements in variable T

*-i insert a newparent element before each table

*-a append a typ attribute to the element just created

*-u update all newparent elements having an immediately
following table sibling element
with (-x XPath expression) a deep copy of that sibling

*-d delete the copied siblings

xmlstarlet edit code can use the convenience $prev (aka
$xstar:prev) node to refer to the node created by the most recent
-i (--insert), -a (--append), or -s (--subnode) option.
Examples of $prev are given in
doc/xmlstarlet.txt.


text:
Q: Xamarin.Mac: Closed window is not reopened to click app icon in the dock I would like to be able to close all the windows once and then click on the icon in the Dock to make the window reopen again.

I was able to find the following code.
AppDelegate.cs
public override bool ApplicationShouldHandleReopen(NSApplication sender, bool hasVisibleWindows)
{
    if (hasVisibleWindows == false)
    {
      var mainWindow = new MainWindowController();
      mainWindow.ShowWindow(this);
    }
    return true;
}

However, I can't find any file in the default project that defines MainWindowController as shown in the code above.

I thought I was supposed to use ViewController, and I've tried something, but it doesn't work as intended. What should I do?
The development environment is Visual Studio for Mac ver. 8.9.6.

A: You can try this code, it works:
 public override bool ApplicationShouldHandleReopen(NSApplication sender, bool hasVisibleWindows)
 {
     if (!hasVisibleWindows)
     {
         foreach (var window in sender.Windows)
             window.MakeKeyAndOrderFront(this);
     }
     return true;
 }

A: You should maybe try (idk if this works in xamarin on mac but i had the same problem in winforms) creating new window, after what you can see in that hierarchy or solution explorer or whatever new window. Then create new instance and show it.
if (hasvisiblewindows == false)
        {
            NewWindow newWindow == new NewWindow();
            NewWindow.ShowWindow(this);
        }

I think this should help you.


text:
Q: simulate a data based on lme in r I am trying to simulate data  based on two models of linear mixed model.
The first model is included random intercept and for fixed there are intercept and slope
library(nlme)
library(mixAK)

 fm1 <- lme(distance ~ age , data = Orthodont, random = ~ 1)
set.seed(2425)
    simfun <- function(n) {
        # n is the number of subjects, total rows will be 4*n
        # sig.b0 is the st. dev. of the random intercepts
        # it might be easier to just copy from the output
        sig.b0 <- exp(unlist(fm1$modelStruct$reStruct))*fm1$sigma
        b0 <- rnorm(n, 0, sig.b0)

    fe <- fixef(fm1)
    my.df <- data.frame( Subject=rep(1:n, each=4),
        int = fe[1] + rep(b0, each=4),
        age=rep( c(8,10,12,14), n ) )
    my.df$distance <- my.df$int + fe[2] * my.df$age +
       rnorm(n*4, 0, fm1$sigma)

    my.df$int <- NULL
       my.df
}

Orthodont1 <- simfun(100)

the summary for real data:
summary(Orthodont) # original data
 distance          age          Subject       Sex
 Min.   :16.50   Min.   : 8.0   M16    : 4   Male  :64
 1st Qu.:22.00   1st Qu.: 9.5   M05    : 4   Female:44
 Median :23.75   Median :11.0   M02    : 4
 Mean   :24.02   Mean   :11.0   M11    : 4
 3rd Qu.:26.00   3rd Qu.:12.5   M07    : 4
 Max.   :31.50   Max.   :14.0   M08    : 4
                                (Other):84

the summary for first simulated
 summary(Orthodont1)
      Subject            age          distance
     Min.   :  1.00   Min.   : 8.0   Min.   :15.26
     1st Qu.: 25.75   1st Qu.: 9.5   1st Qu.:22.28
     Median : 50.50   Median :11.0   Median :24.22
     Mean   : 50.50   Mean   :11.0   Mean   :24.09
     3rd Qu.: 75.25   3rd Qu.:12.5   3rd Qu.:26.09
     Max.   :100.00   Max.   :14.0   Max.   :33.22

I run the first model successfully, but when I run the second model the simulated data is not similar to real data.
Here the second model that I simulated:
fm2 <- lme(distance ~ age , data = Orthodont, random = ~ 1+ age|Subject)
set.seed(2425)
simfun <- function(n) {
    # n is the number of subjects, total rows will be 4*n

    # sig.b0 is the st. dev. of the random intercepts
    # it might be easier to just copy from the output
    sig.b0 <- getVarCov(fm2)[1:2,1:2]
    b0 <- rMVN(n,c(0, 0), sig.b0)$x

    fe <- fixef(fm2)
    my.df <- data.frame( Subject=rep(1:n, each=4),
        int = fe[1] + rep(b0[,1], each=4),
        age=rep( c(8,10,12,14), n ) )
    my.df$distance <- my.df$int +
                   ( fe[2] + rep(b0[,2], each=4)) * my.df$age +
       rnorm(n*4, 0, fm2$sigma)

    my.df$int <- NULL
       my.df
}

Orthodont2 <- simfun(100)
> summary(Orthodont)
    distance          age          Subject       Sex
 Min.   :16.50   Min.   : 8.0   M16    : 4   Male  :64
 1st Qu.:22.00   1st Qu.: 9.5   M05    : 4   Female:44
 Median :23.75   Median :11.0   M02    : 4
 Mean   :24.02   Mean   :11.0   M11    : 4
 3rd Qu.:26.00   3rd Qu.:12.5   M07    : 4
 Max.   :31.50   Max.   :14.0   M08    : 4
                                (Other):84
> summary(Orthodont2)
    Subject            age          distance
 Min.   :  1.00   Min.   : 8.0   Min.   :-178.660
 1st Qu.: 25.75   1st Qu.: 9.5   1st Qu.:  -7.904
 Median : 50.50   Median :11.0   Median :  20.634
 Mean   : 50.50   Mean   :11.0   Mean   :  27.006
 3rd Qu.: 75.25   3rd Qu.:12.5   3rd Qu.:  61.831
 Max.   :100.00   Max.   :14.0   Max.   : 213.611

I do not know when the model included intercept and slope for random effects(model 2) the range of simulated data is different from real data.
May give me any suggestion ?