Programs & Examples On #Libevent

libevent is an API for writing event driven systems. libevent is written in C and should compile on Linux, *BSD, Mac OS X, Solaris and Windows.

configure: error: C compiler cannot create executables

I had already installed the command line tools in xcode but I mine still errored out on:

line 3619: /usr/bin/gcc-4.2: No such file or directory

When I entered which gcc it returned

/usr/bin/gcc

When I entered gcc -v I got a bunch of stuff then

..  
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)

So I created a symlink:

cd /usr/bin
sudo ln -s gcc gcc-4.2

And it worked!

(the config.log file is located in the directory that make is trying to build something in)

Hide password with "•••••••" in a textField

For SwiftUI, try

TextField ("Email", text: $email)
    .textFieldStyle(RoundedBorderTextFieldStyle()).padding()
SecureField ("Password", text: $password)
    .textFieldStyle(RoundedBorderTextFieldStyle()).padding()

How to layout multiple panels on a jFrame? (java)

The JPanel is actually only a container where you can put different elements in it (even other JPanels). So in your case I would suggest one big JPanel as some sort of main container for your window. That main panel you assign a Layout that suits your needs ( here is an introduction to the layouts).

After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).

  JPanel mainPanel = new JPanel();
  mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

  JPanel paintPanel = new JPanel();
  JPanel textPanel = new JPanel();

  mainPanel.add(paintPanel);
  mainPanel.add(textPanel);

This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS).

As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)

Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)

EDIT

Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.

The class is called MyFrame and extends swings JFrame

public class MyFrame extends javax.swing.JFrame{

    // these are the components we need.
    private final JSplitPane splitPane;  // split the window in top and bottom
    private final JPanel topPanel;       // container panel for the top
    private final JPanel bottomPanel;    // container panel for the bottom
    private final JScrollPane scrollPane; // makes the text scrollable
    private final JTextArea textArea;     // the text
    private final JPanel inputPanel;      // under the text a container for all the input elements
    private final JTextField textField;   // a textField for the text the user inputs
    private final JButton button;         // and a "send" button

    public MyFrame(){

        // first, lets create the containers:
        // the splitPane devides the window in two components (here: top and bottom)
        // users can then move the devider and decide how much of the top component
        // and how much of the bottom component they want to see.
        splitPane = new JSplitPane();

        topPanel = new JPanel();         // our top component
        bottomPanel = new JPanel();      // our bottom component

        // in our bottom panel we want the text area and the input components
        scrollPane = new JScrollPane();  // this scrollPane is used to make the text area scrollable
        textArea = new JTextArea();      // this text area will be put inside the scrollPane

        // the input components will be put in a separate panel
        inputPanel = new JPanel();
        textField = new JTextField();    // first the input field where the user can type his text
        button = new JButton("send");    // and a button at the right, to send the text

        // now lets define the default size of our window and its layout:
        setPreferredSize(new Dimension(400, 400));     // let's open the window with a default size of 400x400 pixels
        // the contentPane is the container that holds all our components
        getContentPane().setLayout(new GridLayout());  // the default GridLayout is like a grid with 1 column and 1 row,
        // we only add one element to the window itself
        getContentPane().add(splitPane);               // due to the GridLayout, our splitPane will now fill the whole window

        // let's configure our splitPane:
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);  // we want it to split the window verticaly
        splitPane.setDividerLocation(200);                    // the initial position of the divider is 200 (our window is 400 pixels high)
        splitPane.setTopComponent(topPanel);                  // at the top we want our "topPanel"
        splitPane.setBottomComponent(bottomPanel);            // and at the bottom we want our "bottomPanel"

        // our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically

        bottomPanel.add(scrollPane);                // first we add the scrollPane to the bottomPanel, so it is at the top
        scrollPane.setViewportView(textArea);       // the scrollPane should make the textArea scrollable, so we define the viewport
        bottomPanel.add(inputPanel);                // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea

        // let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
        inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75));     // we set the max height to 75 and the max width to (almost) unlimited
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));   // X_Axis will arrange the content horizontally

        inputPanel.add(textField);        // left will be the textField
        inputPanel.add(button);           // and right the "send" button

        pack();   // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
    }

    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MyFrame().setVisible(true);
            }
        });
    }
}

Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.

Remove scrollbar from iframe

Try adding scrolling="no" attribute like below:

_x000D_
_x000D_
<iframe frameborder="0" scrolling="no" style="height:380px;width:6000px;border:none;" src='https://yoururl'></iframe>
_x000D_
_x000D_
_x000D_

Hash Map in Python

Hash maps are built-in in Python, they're called dictionaries:

streetno = {}                        #create a dictionary called streetno
streetno["1"] = "Sachin Tendulkar"   #assign value to key "1"

Usage:

"1" in streetno                      #check if key "1" is in streetno
streetno["1"]                        #get the value from key "1"

See the documentation for more information, e.g. built-in methods and so on. They're great, and very common in Python programs (unsurprisingly).

All com.android.support libraries must use the exact same version specification

I had this:

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:27.1.1'
   implementation 'com.android.support:design:27.1.1'
   implementation 'com.android.support:support-v4:27.1.1'
   implementation 'com.google.firebase:firebase-auth:12.0.1'
   implementation 'com.google.firebase:firebase-firestore:12.0.1'
   implementation 'com.google.firebase:firebase-messaging:12.0.1'
   implementation 'com.google.android.gms:play-services-auth:12.0.1'
   implementation'com.facebook.android:facebook-login:[4,5)'
   implementation 'com.twitter.sdk.android:twitter:3.1.1'
   implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
   implementation 'org.jetbrains:annotations-java5:15.0'
   implementation project(':vehiclesapi')
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.1'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

and got this error: enter image description here

The solutions was easy - the primary dependencies were all correct so the leaves however - any third party dependencies. Removed one by one until found the culprit, and turns out to be facebook! its using version 27.0.2 of the android support libraries. I tried to add the cardview version 27.1.1 but that didn't work eithern the solution was still simple enough.

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:27.1.1'
   implementation 'com.android.support:design:27.1.1'
   implementation 'com.android.support:support-v4:27.1.1'
   implementation 'com.google.firebase:firebase-auth:12.0.1'
   implementation 'com.google.firebase:firebase-firestore:12.0.1'
   implementation 'com.google.firebase:firebase-messaging:12.0.1'
   implementation 'com.google.android.gms:play-services-auth:12.0.1'
   implementation('com.facebook.android:facebook-login:[4,5)'){
       // contains com.android.support:v7:27.0.2, included required com.android.support.*:27.1.1 modules
    exclude group: 'com.android.support'
   }
   implementation 'com.android.support:cardview-v7:27.1.1' // to replace facebook sdk's cardview-v7:27.0.2.
   implementation 'com.twitter.sdk.android:twitter:3.1.1'
   implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
   implementation 'org.jetbrains:annotations-java5:15.0'
   implementation project(':vehiclesapi')
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.1'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

How to import Maven dependency in Android Studio/IntelliJ?

  1. Uncheck "Offline work" in File>Settings>Gradle>Global Gradle Settings
  2. Resync the project, for example by restarting the Android Studio
  3. Once synced, you can check the option again to work offline.

CSS :: child set to change color on parent hover, but changes also when hovered itself

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

.parent:hover span {
  border: 10px solid red;
}

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

Can HTML checkboxes be set to readonly?

If you want ALL your checkboxes to be "locked" so user can't change the "checked" state if "readonly" attibute is present, then you can use jQuery:

$(':checkbox').click(function () {
    if (typeof ($(this).attr('readonly')) != "undefined") {
        return false;
    }
});

Cool thing about this code is that it allows you to change the "readonly" attribute all over your code without having to rebind every checkbox.

It works for radio buttons as well.

Determine the data types of a data frame's columns

Your best bet to start is to use ?str(). To explore some examples, let's make some data:

set.seed(3221)  # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5), 
                      x1=c(1:5), 
                      x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
                      X3=letters[1:5])

@Wilmer E Henao H's solution is very streamlined:

sapply(my.data, class)
        y        x1        x2        X3 
"numeric" "integer" "logical"  "factor" 

Using str() gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable):

str(my.data)
'data.frame':  5 obs. of  4 variables:
$ y : num  1.03 1.599 -0.818 0.872 -2.682
$ x1: int  1 2 3 4 5
$ x2: logi  TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5

@Gavin Simpson's approach is also streamlined, but provides slightly different information than class():

sapply(my.data, typeof)
       y        x1        x2        X3 
"double" "integer" "logical" "integer"

For more information about class, typeof, and the middle child, mode, see this excellent SO thread: A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient.

What is the difference between a candidate key and a primary key?

Think of a table of vehicles with an integer Primary Key.

The registration number would be a candidate key.

In the real world registration numbers are subject change so it depends somewhat on the circumstances what might qualify as a candidate key.

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

Another solution is to add a hidden input field to the php page:

<input type="hidden" id="myHiddenLocationHash" name="myHiddenLocationHash" value="">

Using javascript/jQuery you can set the value of this field on the page load or responding to an event :

$('#myHiddenLocationHash').val(document.location.hash.replace('#',''));

In php on the server side you can read this value using the $_POST collection:

$server_location_hash = $_POST['myHiddenLocationHash'];

How to clear a chart from a canvas so that hover events cannot be triggered?

Complementing Adam's Answer

With Vanilla JS:

_x000D_
_x000D_
document.getElementById("results-graph").remove(); //canvas_x000D_
div = document.querySelector("#graph-container"); //canvas parent element_x000D_
div.insertAdjacentHTML("afterbegin", "<canvas id='results-graph'></canvas>"); //adding the canvas again
_x000D_
_x000D_
_x000D_

Best way to resolve file path too long exception

The best answer I can find, is in one of the comments here. Adding it to the answer so that someone won't miss the comment and should definitely try this out. It fixed the issue for me.

We need to map the solution folder to a drive using the "subst" command in command prompt- e.g., subst z:

And then open the solution from this drive (z in this case). This would shorten the path as much as possible and could solve the lengthy filename issue.

Test file upload using HTTP PUT method

In my opinion the best tool for such testing is curl. Its --upload-file option uploads a file by PUT, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):

curl http://myservice --upload-file file.txt

How to convert int to NSString?

If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:

NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];

In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.

Create PostgreSQL ROLE (user) if it doesn't exist

Or if the role is not the owner of any db objects one can use:

DROP ROLE IF EXISTS my_user;
CREATE ROLE my_user LOGIN PASSWORD 'my_password';

But only if dropping this user will not make any harm.

How to merge many PDF files into a single one?

You can use http://www.mergepdf.net/ for example

Or:

PDFTK http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

If you are NOT on Ubuntu and you have the same problem (and you wanted to start a new topic on SO and SO suggested to have a look at this question) you can also do it like this:

Things You'll Need:

* Full Version of Adobe Acrobat
  1. Open all the .pdf files you wish to merge. These can be minimized on your desktop as individual tabs.

  2. Pull up what you wish to be the first page of your merged document.

  3. Click the 'Combine Files' icon on the top left portion of the screen.

  4. The 'Combine Files' window that pops up is divided into three sections. The first section is titled, 'Choose the files you wish to combine'. Select the 'Add Open Files' option.

  5. Select the other open .pdf documents on your desktop when prompted.

  6. Rearrange the documents as you wish in the second window, titled, 'Arrange the files in the order you want them to appear in the new PDF'

  7. The final window, titled, 'Choose a file size and conversion setting' allows you to control the size of your merged PDF document. Consider the purpose of your new document. If its to be sent as an e-mail attachment, use a low size setting. If the PDF contains images or is to be used for presentation, choose a high setting. When finished, select 'Next'.

  8. A final choice: choose between either a single PDF document, or a PDF package, which comes with the option of creating a specialized cover sheet. When finished, hit 'Create', and save to your preferred location.

    • Tips & Warnings

Double check the PDF documents prior to merging to make sure all pertinent information is included. Its much easier to re-create a single PDF page than a multi-page document.

Convert java.util.Date to java.time.LocalDate

Short answer

Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Explanation

Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion:

Date input = new Date();
Instant instant = input.toInstant();

A java.util.Date instance has no concept of time-zone. This might seem strange if you call toString() on a java.util.Date, because the toString is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date.

An Instant also does not contain any information about the time-zone. Thus, to convert from an Instant to a local date it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault() - or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone() method to apply the time-zone:

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());

A ZonedDateTime contains state consisting of the local date and time, time-zone and the offset from GMT/UTC. As such the date - LocalDate - can be easily extracted using toLocalDate():

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();

Java 9 answer

In Java SE 9, a new method has been added that slightly simplifies this task:

Date input = new Date();
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());

This new alternative is more direct, creating less garbage, and thus should perform better.

How to add column to numpy array

I think that your problem is that you are expecting np.append to add the column in-place, but what it does, because of how numpy data is stored, is create a copy of the joined arrays

Returns
-------
append : ndarray
    A copy of `arr` with `values` appended to `axis`.  Note that `append`
    does not occur in-place: a new array is allocated and filled.  If
    `axis` is None, `out` is a flattened array.

so you need to save the output all_data = np.append(...):

my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)

Alternative ways:

all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)

I believe that the only difference between these three functions (as well as np.vstack) are their default behaviors for when axis is unspecified:

  • concatenate assumes axis = 0
  • hstack assumes axis = 1 unless inputs are 1d, then axis = 0
  • vstack assumes axis = 0 after adding an axis if inputs are 1d
  • append flattens array

Based on your comment, and looking more closely at your example code, I now believe that what you are probably looking to do is add a field to a record array. You imported both genfromtxt which returns a structured array and recfromcsv which returns the subtly different record array (recarray). You used the recfromcsv so right now my_data is actually a recarray, which means that most likely my_data.shape = (210,) since recarrays are 1d arrays of records, where each record is a tuple with the given dtype.

So you could try this:

import numpy as np
from numpy.lib.recfunctions import append_fields
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
data = np.array( list(zip(x,y,z)), dtype=[('x',float),('y',float),('z',float)])
data = np.recarray(data.shape, data.dtype, buf=data)
data.shape
#(10,)
tot = data['x'] + data['y'] + data['z'] # sum(axis=1) won't work on recarray
tot.shape
#(10,)
all_data = append_fields(data, 'total', tot, usemask=False)
all_data
#array([(0.4374783740738456 , 0.04307289878861764, 0.021176067323686598, 0.5017273401861498),
#       (0.07622262416466963, 0.3962146058689695 , 0.27912715826653534 , 0.7515643883001745),
#       (0.30878532523061153, 0.8553768789387086 , 0.9577415585116588  , 2.121903762680979 ),
#       (0.5288343561208022 , 0.17048864443625933, 0.07915689716226904 , 0.7784798977193306),
#       (0.8804269791375121 , 0.45517504750917714, 0.1601389248542675  , 1.4957409515009568),
#       (0.9556552723429782 , 0.8884504475901043 , 0.6412854758843308  , 2.4853911958174133),
#       (0.0227638618687922 , 0.9295332854783015 , 0.3234597575660103  , 1.275756904913104 ),
#       (0.684075052174589  , 0.6654774682866273 , 0.5246593820025259  , 1.8742119024637423),
#       (0.9841793718333871 , 0.5813955915551511 , 0.39577520705133684 , 1.961350170439875 ),
#       (0.9889343795296571 , 0.22830104497714432, 0.20011292764078448 , 1.4173483521475858)], 
#      dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'), ('total', '<f8')])
all_data.shape
#(10,)
all_data.dtype.names
#('x', 'y', 'z', 'total')

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

Letsencrypt add domain to existing certificate

this worked for me

 sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
 domain.com -d www.domain.com

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

I was getting this error for some network calls and not others. I was connected to a public wifi. That free wifi seemed to bee tampering with certain URLs and hence the error.

When I connected to LTE that error went away!

Spring Rest POST Json RequestBody Content type not supported

I had the same issue. Root cause was using custom deserializer without default constructor.

pointer to array c++

The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int

  int g[] = {9,8};
  int (*j) = g;

could also be rewritten as

  int g[] = {9,8};
  int *j = g;

which could also be rewritten as

  int g[] = {9,8};
  int *j = &g[0];

a pointer-to-an-array would look like

  int g[] = {9,8};
  int (*j)[2] = &g;

  //Dereference 'j' and access array element zero
  int n = (*j)[0];

There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations

Find mouse position relative to element

I came across this question, but in order to make it work for my case (using dragover on a DOM-element (not being canvas in my case)), I found that you only have have to use offsetX and offsetY on the dragover-mouse event.

onDragOver(event){
 var x = event.offsetX;
 var y = event.offsetY;
}

How to export all collections in MongoDB?

  1. Open the Connection
  2. Start the server
  3. open new Command prompt

Export:

mongo/bin> mongoexport -d webmitta -c domain -o domain-k.json

Import:

mongoimport -d dbname -c newCollecionname --file domain-k.json

Where

webmitta(db name)
domain(Collection Name)
domain-k.json(output file name)

Symfony2 Setting a default choice field selection

I'm not sure what you are doing wrong here, when I build a form using form classes Symfony takes care of selecting the correct option in the list. Here's an example of one of my forms that works.

In the controller for the edit action:

$entity = $em->getRepository('FooBarBundle:CampaignEntity')->find($id);

if (!$entity) {
throw $this->createNotFoundException('Unable to find CampaignEntity entity.');
}


$editForm = $this->createForm(new CampaignEntityType(), $entity);
$deleteForm = $this->createDeleteForm($id);

return $this->render('FooBarBundle:CampaignEntity:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));

The campaign entity type class (src: Foo\BarBundle\Form\CampaignEntityType.php):

namespace Foo\BarBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;

class CampaignEntityType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
        ->add('store', 'entity', array('class'=>'FooBarBundle:Store', 'property'=>'name', 'em'=>'my_non_default_em','required'  => true, 'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');}))
        ->add('reward');
    }
    public function getName()
    {
        return 'foo_barbundle_campaignentitytype';
    }
}

jQuery Date Picker - disable past dates

By setting startDate: new Date()

$('.date-picker').datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 1,
    ...
    startDate: new Date(),
});

How to bind a List to a ComboBox?

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList)

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}



List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource implements IBindingList; one such structure is BindingList<T>.


Tip: make sure that you are binding the DisplayMember to a Property on the class and not a public field. If you class uses public string Name { get; set; } it will work but if it uses public string Name; it will not be able to access the value and instead will display the object type for each line in the combo box.

Comparing two input values in a form validation with AngularJS

Thanks for the great example @Jacek Ciolek. For angular 1.3.x this solution breaks when updates are made to the reference input value. Building on this example for angular 1.3.x, this solution works just as well with Angular 1.3.x. It binds and watches for changes to the reference value.

angular.module('app', []).directive('sameAs', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      sameAs: '='
    },
    link: function(scope, elm, attr, ngModel) {
      if (!ngModel) return;

      attr.$observe('ngModel', function(value) {
        // observes changes to this ngModel
        ngModel.$validate();
      });

      scope.$watch('sameAs', function(sameAs) {
        // watches for changes from sameAs binding
        ngModel.$validate();
      });

      ngModel.$validators.sameAs = function(value) {
        return scope.sameAs == value;
      };
    }
  };
});

Here is my pen: http://codepen.io/kvangrae/pen/BjxMWR

How can I get the SQL of a PreparedStatement?

Using prepared statements, there is no "SQL query" :

  • You have a statement, containing placeholders
    • it is sent to the DB server
    • and prepared there
    • which means the SQL statement is "analysed", parsed, some data-structure representing it is prepared in memory
  • And, then, you have bound variables
    • which are sent to the server
    • and the prepared statement is executed -- working on those data

But there is no re-construction of an actual real SQL query -- neither on the Java side, nor on the database side.

So, there is no way to get the prepared statement's SQL -- as there is no such SQL.


For debugging purpose, the solutions are either to :

  • Ouput the code of the statement, with the placeholders and the list of data
  • Or to "build" some SQL query "by hand".

Select a random sample of results from a query result

I know this has already been answered, but seeing so many visits here I'd like to add one version that uses the SAMPLE clause but still allows to filter the rows first:

with cte1 as (
    select *
    from t_your_table
    where your_column = 'ABC'
)
select * from cte1 sample (5)

Note however that the base select needs a ROWID column, which means it may not work for some views for example.

Scroll Element into View with Selenium

Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.

For scrolling down:

WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");

Or, also

js.executeScript("scroll(0, 250);");

For scrolling up:

js.executeScript("window.scrollBy(0,-250)", "");

Or,

js.executeScript("scroll(0, -250);");

Python 3 turn range to a list

Use Range in Python 3.

Here is a example function that return in between numbers from two numbers

def get_between_numbers(a, b):
    """
    This function will return in between numbers from two numbers.
    :param a:
    :param b:
    :return:
    """
    x = []
    if b < a:
        x.extend(range(b, a))
        x.append(a)
    else:
        x.extend(range(a, b))
        x.append(b)

    return x

Result

print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))

[5, 6, 7, 8, 9]  
[5, 6, 7, 8, 9]

angular.js ng-repeat li items with html content

ng-bind-html-unsafe is deprecated from 1.2. The correct answer should be currently:

HTML-side: (the same as the accepted answer stated):

<div ng-app ng-controller="MyCtrl">
   <ul>
      <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
      </li>
   </ul>

   <p>{{opt}}</p>
</div>

But in the controller-side:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
   $scope.opts.map(function(opt) { 
      opt = $sce.trustAsHtml(opt);
   });
}

What is the proper way to check and uncheck a checkbox in HTML5?

<form name="myForm" method="post">
  <p>Activity</p> 
  skiing:  <input type="checkbox" name="activity" value="skiing"  checked="yes" /><br /> 
  skating: <input type="checkbox" name="activity" value="skating" /><br /> 
  running: <input type="checkbox" name="activity" value="running" /><br /> 
  hiking:  <input type="checkbox" name="activity" value="hiking"  checked="yes" />
</form>

How to position two elements side by side using CSS

Like this

.block {
    display: inline-block;
    vertical-align:top;
}

JSFiddle Demo

remove all special characters in java

Your problem is that the indices returned by match.start() correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c every time, these indices become incorrect.

The best approach to solve this is to use replaceAll, for example:

        System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

How do I set default terminal to terminator?

In xfce (e.g. on Arch Linux) you can change the parameter TerminalEmulator:

 TerminalEmulator=xfce4-terminal

to

TerminalEmulator=custom-TerminalEmulator

The next time you want to open a terminal window, xfce will ask you to choose an emulator. You can just pick /usr/bin/terminator.

System Defaults

/etc/xdg/xfce4/helpers.rc

User Defaults

/home/USER/.config/xfce4

What is a postback?

Postback is essentially when a form is submitted to the same page or script (.php .asp etc) as you are currently on to proccesses the data rather than sending you to a new page.

An example could be a page on a forum (viewpage.php), where you submit a comment and it is submitted to the same page (viewpage.php) and you would then see it with the new content added.

See: http://en.wikipedia.org/wiki/Postback

How do I force a favicon refresh?

Here's how I managed it with a simply animated favicon and FireFox 3.6.13 (beta version) It will probably work for other versions of FireFox as well, let me know if it doesn't. It's basically artlung's solution, but addressing the .gif file as well:

  1. I opened by FTP program, downloaded my favicon.ico AND favicon.gif files,
  2. then DELETED them from my server's files.
  3. Then I opened them in my browser as artlung suggested: http://mysite.com/favicon.ico AND http://mysite.com/favicon.gif Once those addresses loaded and displayed 404 error pages ("page not found")
  4. I THEN uploaded both files back onto my server, and PRESTO - the correct icons were instantly displayed.

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

Unable to find a @SpringBootConfiguration when doing a JpaTest

In my case
Make sure your (test package name) of YourApplicationTests is equivalent to the (main package name).

Difference between "while" loop and "do while" loop

While:

  1. entry control loop

  2. condition is checked before loop execution

  3. never execute loop if condition is false

  4. there is no semicolon at the end of while statement

Do-while:

  1. exit control loop

  2. condition is checked at the end of loop

  3. executes false condition at least once since condition is checked later

  4. there is semicolon at the end of while statement.

How to define global variable in Google Apps Script

You might be better off using the Properties Service as you can use these as a kind of persistent global variable.

click 'file > project properties > project properties' to set a key value, or you can use

PropertiesService.getScriptProperties().setProperty('mykey', 'myvalue');

The data can be retrieved with

var myvalue = PropertiesService.getScriptProperties().getProperty('mykey');

How to include route handlers in multiple files in Express?

I wrote a small plugin for doing this! got sick of writing the same code over and over.

https://www.npmjs.com/package/js-file-req

Hope it helps.

How to get just the date part of getdate()?

SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)

or

SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))

How do I check that a Java String is not all whitespaces?

The trim method should work great for you.

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#trim()

Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

This method may be used to trim whitespace from the beginning and end of a string; in fact, it trims all ASCII control characters as well.

Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.leading or trailing white space.

You could trim and then compare to an empty string or possibly check the length for 0.

How to find and return a duplicate value in array

Simply find the first instance where the index of the object (counting from the left) does not equal the index of the object (counting from the right).

arr.detect {|e| arr.rindex(e) != arr.index(e) }

If there are no duplicates, the return value will be nil.

I believe this is the fastest solution posted in the thread so far, as well, since it doesn't rely on the creation of additional objects, and #index and #rindex are implemented in C. The big-O runtime is N^2 and thus slower than Sergio's, but the wall time could be much faster due to the the fact that the "slow" parts run in C.

load iframe in bootstrap modal

Bootstrap event for modal load was changed in Bootstrap 3

just use shown.bs.modal event:

$('.modal').on('shown.bs.modal', function() {
    $(this).find('iframe').attr('src','http://www.google.com')
})  

More can found on the event at the below link:

http://getbootstrap.com/javascript/

Spaces in URLs?

Spaces are simply replaced by "%20" like :

http://www.example.com/my%20beautiful%20page

How to include files outside of Docker's build context?

On Linux you can mount other directories instead of symlinking them

mount --bind olddir newdir

See https://superuser.com/questions/842642 for more details.

I don't know if something similar is available for other OSes. I also tried using Samba to share a folder and remount it into the Docker context which worked as well.

How to interactively (visually) resolve conflicts in SourceTree / git

I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.

If you'd like to use it as well, then:

  1. Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.

  2. Unzip TortoiseIDiff.exe and TortoiseMerge.exe to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\ in my case).

  3. In SourceTree open Tools > Options > Diff > External Diff / Merge. Select TortoiseMerge in both dropdown lists.

  4. Hit OK and point SourceTree to your location of TortoiseIDiff.exe and TortoiseMerge.exe.

After that, you can select Resolve Conflicts > Launch External Merge Tool from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.

The only problem is, that it automatically creates backup copy, even though proper option is unchecked.

HttpServletRequest - Get query string parameters, no form data

Java 8

return Collections.list(httpServletRequest.getParameterNames())
                  .stream()
                  .collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));

Best approach to remove time part of datetime in SQL Server

select CONVERT(char(10), GetDate(),126)

Java enum - why use toString instead of name

It really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}

Is a DIV inside a TD a bad idea?

As everyone mentioned, it might not be a good idea for layout purposes. I arrived to this question because I was wondering the same and I only wanted to know if it would be valid code.

Since it's valid, you can use it for other purposes. For example, what I'm going to use it for is to put some fancy "CSSed" divs inside table rows and then use a quick jQuery function to allow the user to sort the information by price, name, etc. This way, the only layout table will give me is the "vertical order", but I'll control width, height, background, etc of the divs by CSS.

How can I get the ID of an element using jQuery?

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

$("#test").get(0).id

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")

Python Web Crawlers and "getting" html source code

Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

import urllib2

response = urllib2.urlopen("http://google.de")
page_source = response.read()

For parsing the code, have a look at BeautifulSoup.

BTW: what exactly do you want to do:

Just for background, I need to download a page and replace any img with ones I have

Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

How to print variables without spaces between values

Don't use print ..., if you don't want spaces. Use string concatenation or formatting.

Concatenation:

print 'Value is "' + str(value) + '"'

Formatting:

print 'Value is "{}"'.format(value)

The latter is far more flexible, see the str.format() method documentation and the Formatting String Syntax section.

You'll also come across the older % formatting style:

print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)

but this isn't as flexible as the newer str.format() method.

Is it possible to program Android to act as physical USB keyboard?

I am bit late to comment in this question but it might be useful for some other people.

You can make your android phone to work like keyboard, mouse, camera, sound streaming system, tethering device. In short what ever usb gadget you see in the market and until and unless hardware doesn't limit you. Such as speed, or gadget interface not available.

USB device is of two type, host and gadget. So gadget device acts like client and usually has usb otg interface in most of the phones. So in gadget end, you can make your phone to behave like different device at all by switching between different configuration(you are already doing it when you go into usb settings and make your device as mass storage or anything else).

But for doing all these you have to modify android kernel. If you are a android device developer you can for sure do it.

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

T-SQL split string

There is a correct version on here but I thought it would be nice to add a little fault tolerance in case they have a trailing comma as well as make it so you could use it not as a function but as part of a larger piece of code. Just in case you're only using it once time and don't need a function. This is also for integers (which is what I needed it for) so you might have to change your data types.

DECLARE @StringToSeperate VARCHAR(10)
SET @StringToSeperate = '1,2,5'

--SELECT @StringToSeperate IDs INTO #Test

DROP TABLE #IDs
CREATE TABLE #IDs (ID int) 

DECLARE @CommaSeperatedValue NVARCHAR(255) = ''
DECLARE @Position INT = LEN(@StringToSeperate)

--Add Each Value
WHILE CHARINDEX(',', @StringToSeperate) > 0
BEGIN
    SELECT @Position  = CHARINDEX(',', @StringToSeperate)  
    SELECT @CommaSeperatedValue = SUBSTRING(@StringToSeperate, 1, @Position-1)

    INSERT INTO #IDs 
    SELECT @CommaSeperatedValue

    SELECT @StringToSeperate = SUBSTRING(@StringToSeperate, @Position+1, LEN(@StringToSeperate)-@Position)

END

--Add Last Value
IF (LEN(LTRIM(RTRIM(@StringToSeperate)))>0)
BEGIN
    INSERT INTO #IDs
    SELECT SUBSTRING(@StringToSeperate, 1, @Position)
END

SELECT * FROM #IDs

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

First of all, beware of that method:

As Jesse Ezel says:

Brad Abrams

"The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.

Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.

The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are)."

And if you patch String class... be sure NilClass has not been patch either!

class NilClass
    def empty?; true; end
end

How to ignore deprecation warnings in Python

Python 3

Just write below lines that are easy to remember before writing your code:

import warnings

warnings.filterwarnings("ignore")

Creating a div element in jQuery

I've just made a small jQuery plugin for that.

It follows your syntax:

var myDiv = $.create("div");

DOM node ID can be specified as second parameter:

var secondItem = $.create("div","item2");

Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.

(Answer partially copied from: jQuery document.createElement equivalent?)

Using Linq select list inside list

list.Where(m => m.application == "applicationName" && 
           m.users.Any(u => u.surname=="surname"));

if you want to filter users as TimSchmelter commented, you can use

list.Where(m => m.application == "applicationName")
    .Select(m => new Model
    {
        application = m.application,
        users = m.users.Where(u => u.surname=="surname").ToList()
    });

What is SELF JOIN and when would you use it?

You'd use a self-join on a table that "refers" to itself - e.g. a table of employees where managerid is a foreign-key to employeeid on that same table.

Example:

SELECT E.name, ME.name AS manager
FROM dbo.Employees E
LEFT JOIN dbo.Employees ME
ON ME.employeeid = E.managerid

Generating a WSDL from an XSD file

You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.

These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types> tag.

(thanks to Cheeso for pointing out my inaccurate usage of terms)

Found shared references to a collection org.hibernate.HibernateException

I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.

Short version

Check that your @Embedded Id of container has no possible collisions.

Long version

When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.

For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.

So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.

Example

Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).

@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
    private Set<Loan> loans;

    @Embedded
    private AccountId accountId;

    ...
}

@Embeddable
public class AccountId {
    @Column(name = "X")
    private Long x;
    
    @Column(name = "BRANCH")
    private String branchId;
    
    @Column(name = "Z")
    private String z;

    ...
}

Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;

It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.

According to @NotFound(action = NotFoundAction.IGNORE) if value is not present in related table, Hibernate will load null value for the property.

If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.

So two CollectionKey objects will be equal and will have same hashCode for different Accounts.

result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
 role = "Account.loans"
 key = {Account@26451} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
 role = "Account.loans"
 key = {Account@35225} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

Because of this, Hibernate will load same PesistentSet for two entities.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I dont know what is the exact reason but I solved the problem running:

   app/console cache:clear --env=prod

How exactly does the python any() function work?

If you use any(lst) you see that lst is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None] (which all have boolean values of False) then any(lst) would be False. If lst also contained any of the following [-1, True, "X", 0.00001] (all of which evaluate to True) then any(lst) would be True.

In the code you posted, x > 0 for x in lst, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []'s: [x > 0 for x in lst]. From the lst containing [-1, -2, 10, -4, 20], you would get this comprehended list: [False, False, True, False, True]. This internal value would then get passed to the any function, which would return True, since there is at least one True value.

But with generator expressions, Python no longer has to create that internal list of True(s) and False(s), the values will be generated as the any function iterates through the values generated one at a time by the generator expression. And, since any short-circuits, it will stop iterating as soon as it sees the first True value. This would be especially handy if you created lst using something like lst = range(-1,int(1e9)) (or xrange if you are using Python2.x). Even though this expression will generate over a billion entries, any only has to go as far as the third entry when it gets to 1, which evaluates True for x>0, and so any can return True.

If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any. But by using a generator expression, you can have Python's builtin functions like any and all break out early, as soon as a True or False value is seen.

What is the difference between SAX and DOM?

Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation

SAX:

  1. Parses node by node

  2. Does not store the XML in memory

  3. We cant insert or delete a node

  4. Top to bottom traversing

DOM

  1. Stores the entire XML document into memory before processing

  2. Occupies more memory

  3. We can insert or delete nodes

  4. Traverse in any direction.

If we need to find a node and does not need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Angular - Use pipes in services and components

This answer is now outdated

recommend using DI approach from other answers instead of this approach

Original answer:

You should be able to use the class directly

new DatePipe().transform(myDate, 'yyyy-MM-dd');

For instance

var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');

Sending mail attachment using Java

Using Spring Framework , you can add many attachments :

package com.mkyong.common;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailMail
{
    private JavaMailSender mailSender;
    private SimpleMailMessage simpleMailMessage;

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String dear, String content) {

       MimeMessage message = mailSender.createMimeMessage();

       try{
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(simpleMailMessage.getTo());
        helper.setSubject(simpleMailMessage.getSubject());
        helper.setText(String.format(
            simpleMailMessage.getText(), dear, content));

        FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
        helper.addAttachment(file.getFilename(), file);

         }catch (MessagingException e) {
        throw new MailParseException(e);
         }
         mailSender.send(message);
         }
}

To know how to configure your project to deal with this code , complete reading this tutorial .

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

how to prevent "directory already exists error" in a makefile when using mkdir

ifeq "$(wildcard $(MY_DIRNAME) )" ""
  -mkdir $(MY_DIRNAME)
endif

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

How do I run two commands in one line in Windows CMD?

It's simple: just differentiate them with && signs. Example:

echo "Hello World" && echo "GoodBye World".

"Goodbye World" will be printed after "Hello World".

urlencoded Forward slash is breaking URL

Replace %2F with %252F after url encoding

PHP

function custom_http_build_query($query=array()){

    return str_replace('%2F','%252F', http_build_query($query));
}

Handle the request via htaccess

.htaccess

RewriteCond %{REQUEST_URI} ^(.*?)(%252F)(.*?)$ [NC]
RewriteRule . %1/%3 [R=301,L,NE]

Resources

http://www.leakon.com/archives/865

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

you could try

$('*').not('#div').bind('touchmove', false);

add this if necessary

$('#div').bind('touchmove');

note that everything is fixed except #div

Generate signed apk android studio

I had the same problem. I populated the field with /home/tim/android.jks file from tutorial thinking that file would be created. and when i would click enter it would say cant find the file. but when i would try to create the file, it would not let me create the jks file. I closed out of android studio and ran it again and it worked fine. I had to hit the ... to correctly add my file. generate signed apk wizard-->new key store-->hit ... choose key store file. enter filename I was thinking i was going to have to use openjdk and create my own keyfile, but it is built into android studio

How do implement a breadth first traversal?

Breadth first search

Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
    if (root == null)
        return;
    queue.clear();
    queue.add(root);
    while(!queue.isEmpty()){
        TreeNode node = queue.remove();
        System.out.print(node.element + " ");
        if(node.left != null) queue.add(node.left);
        if(node.right != null) queue.add(node.right);
    }

}

adding text to an existing text element in javascript via DOM

Instead of appending element you can just do.

 document.getElementById("p").textContent += " this has just been added";

_x000D_
_x000D_
document.getElementById("p").textContent += " this has just been added";
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

It's very old problem with cashed content. MS planning to remove diagrams from SSMS, so they don't care about this. Anyway, solution exists.

Just close Diagrams tab and open it again. Works with SSMS 18.2.

Adding attribute in jQuery

$('.some_selector').attr('disabled', true);

How to add font-awesome to Angular 2 + CLI project

Now there is few ways to install fontAwesome on Angular CLI:

ng add @fortawesome/angular-fontawesome

OR using yarn

yarn add @fortawesome/fontawesome-svg-core
yarn add @fortawesome/free-solid-svg-icons
yarn add @fortawesome/angular-fontawesome

OR Using NPM

npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/angular-fontawesome

Reference here: https://github.com/FortAwesome/angular-fontawesome

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

You have in your module

import {Routes, RouterModule} from '@angular/router';

you have to export the module RouteModule

example:

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

to be able to access the functionalities for all who import this module.

How do I install Python OpenCV through Conda?

Following command adds a different anaconda channel for opencv3, you should be able to pull from it.

conda install --channel  https://mirrors.ustc.edu.cn/anaconda/cloud/menpo opencv3

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

How to keep two folders automatically synchronized?

You can use inotifywait (with the modify,create,delete,move flags enabled) and rsync.

while inotifywait -r -e modify,create,delete,move /directory; do
    rsync -avz /directory /target
done

If you don't have inotifywait on your system, run sudo apt-get install inotify-tools

Can I escape a double quote in a verbatim string literal?

Use a duplicated double quote.

@"this ""word"" is escaped";

outputs:

this "word" is escaped

Is it possible to listen to a "style change" event?

Just adding and formalizing @David 's solution from above:

Note that jQuery functions are chainable and return 'this' so that multiple invocations can be called one after the other (e.g $container.css("overflow", "hidden").css("outline", 0);).

So the improved code should be:

(function() {
    var ev = new $.Event('style'),
        orig = $.fn.css;
    $.fn.css = function() {
        var ret = orig.apply(this, arguments);
        $(this).trigger(ev);
        return ret; // must include this
    }
})();

Google Spreadsheet, Count IF contains a string

Try just =COUNTIF(A2:A51,"iPad")

Wait until ActiveWorkbook.RefreshAll finishes - VBA

I had the same issue, however DoEvents didn't help me as my data connections had background-refresh enabled. Instead, using Wayne G. Dunn's answer as a jumping-off point, I created the following solution, which works just fine for me;

Sub Refresh_All_Data_Connections()

    For Each objConnection In ThisWorkbook.Connections
        'Get current background-refresh value
        bBackground = objConnection.OLEDBConnection.BackgroundQuery

        'Temporarily disable background-refresh
        objConnection.OLEDBConnection.BackgroundQuery = False

        'Refresh this connection
        objConnection.Refresh

        'Set background-refresh value back to original value
        objConnection.OLEDBConnection.BackgroundQuery = bBackground
    Next

    MsgBox "Finished refreshing all data connections"

End Sub

The MsgBox is for testing only and can be removed once you're happy the code waits.

Also, I prefer ThisWorkbook to ActiveWorkbook as I know it will target the workbook where the code resides, just in case focus changes. Nine times out of ten this won't matter, but I like to err on the side of caution.

EDIT: Just saw your edit about using an xlConnectionTypeXMLMAP connection which does not have a BackgroundQuery option, sorry. I'll leave the above for anyone (like me) looking for a way to refresh OLEDBConnection types.

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

Disable submit button when form invalid with AngularJS

_x000D_
_x000D_
<form name="myForm">_x000D_
        <input name="myText" type="text" ng-model="mytext" required/>_x000D_
        <button ng-disabled="myForm.$pristine|| myForm.$invalid">Save</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

If you want to be a bit more strict

Angular ng-if not true

you are not using the $scope you must use $ctrl.area or $scope.area instead of area

Ruby send JSON request

HTTParty makes this a bit easier I think (and works with nested json etc, which didn't seem to work in other examples I've seen.

require 'httparty'
HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: '[email protected]', password: 'secret'}}).body

Get free disk space

As this answer and @RichardOD suggested , you should do like this:

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
   out ulong lpFreeBytesAvailable,
   out ulong lpTotalNumberOfBytes,
   out ulong lpTotalNumberOfFreeBytes);

ulong FreeBytesAvailable;
ulong TotalNumberOfBytes;
ulong TotalNumberOfFreeBytes;

bool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder",
                                  out FreeBytesAvailable,
                                  out TotalNumberOfBytes,
                                  out TotalNumberOfFreeBytes);
if(!success)
    throw new System.ComponentModel.Win32Exception();

Console.WriteLine("Free Bytes Available:      {0,15:D}", FreeBytesAvailable);
Console.WriteLine("Total Number Of Bytes:     {0,15:D}", TotalNumberOfBytes);
Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);

Reading an integer from user input

You could create your own ReadInt function, that only allows numbers (this function is probably not the best way to go about this, but does the job)

public static int ReadInt()
    {
        string allowedChars = "0123456789";

        ConsoleKeyInfo read = new ConsoleKeyInfo();
        List<char> outInt = new List<char>();

        while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
        {
            read = Console.ReadKey(true);
            if (allowedChars.Contains(read.KeyChar.ToString()))
            {
                outInt.Add(read.KeyChar);
                Console.Write(read.KeyChar.ToString());
            }
            if(read.Key == ConsoleKey.Backspace)
            {
                if(outInt.Count > 0)
                {
                    outInt.RemoveAt(outInt.Count - 1);
                    Console.CursorLeft--;
                    Console.Write(" ");
                    Console.CursorLeft--;
                }
            }
        }
        Console.SetCursorPosition(0, Console.CursorTop + 1);
        return int.Parse(new string(outInt.ToArray()));
    }

What is the best Java email address validation method?

Apache Commons validator can be used as mentioned in the other answers.

pom.xml:

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.4.1</version>
</dependency>

build.gradle:

compile 'commons-validator:commons-validator:1.4.1'

The import:

import org.apache.commons.validator.routines.EmailValidator;

The code:

String email = "[email protected]";
boolean valid = EmailValidator.getInstance().isValid(email);

and to allow local addresses

boolean allowLocal = true;
boolean valid = EmailValidator.getInstance(allowLocal).isValid(email);

Background service with location listener in android

Very easy no need create class extends LocationListener 1- Variable

private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;

2- onStartService()

@Override public void onStartService() {
    addListenerLocation();
}

3- Method addListenerLocation()

 private void addListenerLocation() {
    mLocationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(lastKnownLocation!=null){
                currentLat = lastKnownLocation.getLatitude();
                currentLon = lastKnownLocation.getLongitude();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}

4- onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    mLocationManager.removeUpdates(mLocationListener);
}

Linux command to list all available commands and aliases

For Mac users (find doesn't have -executable and xargs doesn't have -d):

echo $PATH | tr ':' '\n' | xargs -I {} find {} -maxdepth 1 -type f -perm '++x'

Using sessions & session variables in a PHP Login Script

Firstly, the PHP documentation has some excellent information on sessions.

Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt() hashing function. This means that if any credentials are compromised, the passwords are not readily available.

Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.

You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.

To start a PHP session, you need to call session_start(). Similarly, to destroy a session and its data, you need to call session_destroy() (for example, when the user logs out):

// Begin the session
session_start();

// Use session variables
$_SESSION['userid'] = $userid;

// E.g. find if the user is logged in
if($_SESSION['userid']) {
    // Logged in
}
else {
    // Not logged in
}

// Destroy the session
if($log_out)
    session_destroy();

I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there.

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

I had some trouble similar to this,

<repository>
    <id>java.net</id>
    <url>https://maven-repository.dev.java.net/nonav/repository</url>
    <layout>legacy</layout>
</repository>
<repository>
    <id>java.net2</id>
    <url>https://maven2-repository.dev.java.net/nonav/repository</url>
</repository>

Setting the updatePolicy to "never" did not work. Removing these repo was the way I solved it. ps: I was following this tutorial about web services (btw, probably the best tutorial for ws for java)

Recursive mkdir() system call on Unix

The two other answers given are for mkdir(1) and not mkdir(2) like you ask for, but you can look at the source code for that program and see how it implements the -p options which calls mkdir(2) repeatedly as needed.

Checking Value of Radio Button Group via JavaScript?

Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}

How to execute a command prompt command from python

Try:

import os

os.popen("Your command here")

How to process each output line in a loop?

One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop.

Something like:

grep xyz abc.txt | while read -r line ; do
    echo "Processing $line"
    # your code goes here
done

There are variations on this scheme depending on exactly what you're after.

If you need to change variables inside the loop (and have that change be visible outside of it), you can use process substitution as stated in fedorqui's answer:

while read -r line ; do
    echo "Processing $line"
    # your code goes here
done < <(grep xyz abc.txt)

Select a row from html table and send values onclick of a button

In my case $(document).ready(function() was missing. Try this.

$(document).ready(function(){   
("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected');    
       var value=$(this).find('td:first').html();
       alert(value);    
    });
    $('.ok').on('click', function(e){
        alert($("#table tr.selected td:first").html());
    });
});

JSON and XML comparison

I found this article at digital bazaar really interesting. Quoting their quotations from Norm:

About JSON pros:

If all you want to pass around are atomic values or lists or hashes of atomic values, JSON has many of the advantages of XML: it’s straightforwardly usable over the Internet, supports a wide variety of applications, it’s easy to write programs to process JSON, it has few optional features, it’s human-legible and reasonably clear, its design is formal and concise, JSON documents are easy to create, and it uses Unicode. ...

About XML pros:

XML deals remarkably well with the full richness of unstructured data. I’m not worried about the future of XML at all even if its death is gleefully celebrated by a cadre of web API designers.

And I can’t resist tucking an "I told you so!" token away in my desk. I look forward to seeing what the JSON folks do when they are asked to develop richer APIs. When they want to exchange less well strucured data, will they shoehorn it into JSON? I see occasional mentions of a schema language for JSON, will other languages follow? ...

I personally agree with Norm. I think that most attacks to XML come from Web Developers for typical applications, and not really from integration developers. But that's my opinion! ;)

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

How to supply value to an annotation from a Constant java

I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.

With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.

In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

Simplest way to wait some asynchronous tasks complete, in Javascript?

All answers are quite old. Since the beginning of 2013 Mongoose started to support promises gradually for all queries, so that would be the recommended way of structuring several async calls in the required order going forward I guess.

How to split one string into multiple variables in bash shell?

Sounds like a job for set with a custom IFS.

IFS=-
set $STR
var1=$1
var2=$2

(You will want to do this in a function with a local IFS so you don't mess up other parts of your script where you require IFS to be what you expect.)

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

How to empty (clear) the logcat buffer in Android

The following command will clear only non-rooted buffers (main, system ..etc).

adb logcat -c

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

adb root
adb logcat -b all -c

or

adb root
adb shell logcat -b all -c 

Use the following commands to know the list of buffers that device supports

adb logcat -g
adb logcat -b all -g
adb shell logcat -b all -g

LINQ extension methods - Any() vs. Where() vs. Exists()

Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:

List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));

Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:

IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));

Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I found a solution to my issue and after a request, will post it here to help others. Apologies if I missed any details, it's been a while since I worked on this solution.

The first thing that is required is to install Openoffice.org on the server. I requested my hosting provider to install the open office RPM on my VPS. This can be done through WHM directly.

Now that the server has the capability to handle MS Office files you are able to convert the files by executing command line instructions via PHP. To handle this, I found PyODConverter: https://github.com/mirkonasato/pyodconverter

I created a directory on the server and placed the PyODConverter python file within it. I also created a plain text file above the web root (I named it "adocpdf"), with the following command line instructions in it:

directory=$1
filename=$2
extension=$3
SERVICE='soffice'
if [ "`ps ax|grep -v grep|grep -c $SERVICE`" -lt 1 ]; then 
unset DISPLAY
/usr/bin/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard & 
sleep 5s
fi
python /home/website/python/DocumentConverter.py /home/website/$directory$filename$extension /home/website/$directory$filename.pdf

This checks that the openoffice.org libraries are running and then calls the PyODConverter script to process the file and output it as a PDF. The 3 variables on the first three lines are provided when the script is executed from with a PHP file. The delay ("sleep 5s") is used to ensure that openoffice.org has enough to time to initiate if required. I have used this for months now and the 5s gap seems to give enough breathing room.

The script will create a PDF version of the document in the same directory as the original.

Finally, initiating the conversion of a Word / Excel file from within PHP (I have it within a function that checks if the file we are dealing with is a word / excel document)...

//use openoffice.org
$output = array();
$return_var = 0;
exec("/opt/adocpdf {$directory} {$filename} {$extension}", $output, $return_var);

This PHP function is called once the Word / Excel file has been uploaded to the server. The 3 variables in the exec() call relate directly to the 3 at the start of the plain text script above. Note that the $directory variable requires no leading forward slash if the file for conversion is within the web root.

OK, that's it! Hopefully this will be useful to someone and save them the difficulties and learning curve I faced.

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

What about [AllowHtml] attribute above property?

Check substring exists in a string in C

#include <stdio.h>
#include <string.h>

int findSubstr(char *inpText, char *pattern);
int main()
{
    printf("Hello, World!\n");
    char *Text = "This is my sample program";
    char *pattern = "sample";
    int pos = findSubstr(Text, pattern);
    if (pos > -1) {
        printf("Found the substring at position %d \n", pos);
    }
    else
        printf("No match found \n");

    return 0;
}

int findSubstr(char *inpText, char *pattern) {
    int inplen = strlen(inpText);
    while (inpText != NULL) {

        char *remTxt = inpText;
        char *remPat = pattern;

        if (strlen(remTxt) < strlen(remPat)) {
            /* printf ("length issue remTxt %s \nremPath %s \n", remTxt, remPat); */
            return -1;
        }

        while (*remTxt++ == *remPat++) {
            printf("remTxt %s \nremPath %s \n", remTxt, remPat);
            if (*remPat == '\0') {
                printf ("match found \n");
                return inplen - strlen(inpText+1);
            }
            if (remTxt == NULL) {
                return -1;
            }
        }
        remPat = pattern;

        inpText++;
    }
}

How to manually update datatables table with new JSON data

Here is solution for legacy datatable 1.9.4

    var myData = [
      {
        "id": 1,
        "first_name": "Andy",
        "last_name": "Anderson"
      }
   ];
    var myData2 = [
      {
        "id": 2,
        "first_name": "Bob",
        "last_name": "Benson"
      }
    ];

  $('#table').dataTable({
  //  data: myData,
       aoColumns: [
         { mData: 'id' },
         { mData: 'first_name' },
         { mData: 'last_name' }
      ]
  });

 $('#table').dataTable().fnClearTable();
 $('#table').dataTable().fnAddData(myData2);

batch file - counting number of files in folder and storing in a variable

Change into the directory and;

attrib.exe /s ./*.* |find /c /v ""

EDIT

I presumed that would be simple to discover. use

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "batchfile.bat";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

I run this and the variable output was holding this

D:\VSS\USSD V3.0\WTU.USSD\USSDConsole\bin\Debug>attrib.exe /s ./*.*   | find /c /v "" 13

where 13 is the file count. It should solve the issue

Javascript replace all "%20" with a space

using unescape(stringValue)

_x000D_
_x000D_
var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))
_x000D_
_x000D_
_x000D_

//Output
Passwords do not match!

use decodeURI(stringValue)

_x000D_
_x000D_
var str = "Passwords%20do%20not%20match%21";
 document.write(decodeURI(str))
_x000D_
_x000D_
_x000D_

Space = %20
? = %3F
! = %21
# = %23
...etc

Why Would I Ever Need to Use C# Nested Classes

A nested class can have private, protected and protected internal access modifiers along with public and internal.

For example, you are implementing the GetEnumerator() method that returns an IEnumerator<T> object. The consumers wouldn't care about the actual type of the object. All they know about it is that it implements that interface. The class you want to return doesn't have any direct use. You can declare that class as a private nested class and return an instance of it (this is actually how the C# compiler implements iterators):

class MyUselessList : IEnumerable<int> {
    // ...
    private List<int> internalList;
    private class UselessListEnumerator : IEnumerator<int> {
        private MyUselessList obj;
        public UselessListEnumerator(MyUselessList o) {
           obj = o;
        }
        private int currentIndex = -1;
        public int Current {
           get { return obj.internalList[currentIndex]; }
        }
        public bool MoveNext() { 
           return ++currentIndex < obj.internalList.Count;
        }
    }
    public IEnumerator<int> GetEnumerator() {
        return new UselessListEnumerator(this);
    }
}

Correct way to use StringBuilder in SQL

[[ There are some good answers here but I find that they still are lacking a bit of information. ]]

return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
     .toString();

So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the + work here because "select id1, " + " id2 " + " from " + " table" are all constants. So this turns into:

return new StringBuilder("select id1,  id2  from  table").toString();

In this case, obviously, there is no point in using StringBuilder. You might as well do:

// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";

However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder -- there's no need for you to define one:

// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;

Under the covers, this turns into code that is approximately equivalent to:

StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();

Really the only time you need to use StringBuilder directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder:

// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
   // another StringBuilder used here
   query += ' ' + where;
}

The + in the first line uses one StringBuilder instance. Then the += uses another StringBuilder instance. It is more efficient to do:

// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
   sb.append(' ').append(where);
}
return sb.toString();

Another time that I use a StringBuilder is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder argument:

private void addWhere(StringBuilder sb) {
   if (where != null) {
      sb.append(' ').append(where);
   }
}

When you are using a StringBuilder, you should watch for any usage of + at the same time:

sb.append("select " + fieldName);

That + will cause another internal StringBuilder to be created. This should of course be:

sb.append("select ").append(fieldName);

Lastly, as @T.J.rowder points out, you should always make a guess at the size of the StringBuilder. This will save on the number of char[] objects created when growing the size of the internal buffer.

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

I solve this trouble with config APACHE ! All methods (in this topic) is incorrect for me... Then I try chanche apache config:

Timeout 3600

Then my script worked!

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Excel: VLOOKUP that returns true or false?

We've always used an

if(iserror(vlookup,"n/a",vlookup))

Excel 2007 introduced IfError which allows you to do the vlookup and add output in case of error, but that doesn't help you with 2003...

How to compare different branches in Visual Studio Code

2019 answer

Here is the step by step guide:

  1. Install the GitLens extension: GitLens
  2. The GitLens icon will show up in nav bar. Click on it.

    Git lens icon

  3. Click on compare

    Enter image description here

  4. Select branches to compare

    enter image description here

  5. Now you can see the difference. You can select any file for which you want to see the diff for.

    Enter image description here

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:

  1. Go to folder:

    C:\AppServ\MySQL
    
  2. Right click and Run as Administrator these files:

    mysql_servicefix.bat
    
    mysql_serviceinstall.bat
    
    mysql_servicestart.bat
    

Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.

Explode PHP string by new line

this php function explode string by newline

Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.
pay attention that empty lines will be ignored

function splitNewLine($text) {
    $code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
    return explode("\n",$code);
}

example

$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );

output

Array
(
    [0] => salam
    [1] => man khobam
    [2] => to chi
    [3] => che khabar
    [4] => bashe baba raftam
)

How to set a default value for an existing column

This will work in SQL Server:

ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;

How to hide a button programmatically?

public void OnClick(View.v)
Button b1 = (Button) findViewById(R.id.playButton);
b1.setVisiblity(View.INVISIBLE);

Getting the first index of an object

Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:

_.pairs(obj)[0]

Then the key would be available with a further [0] subscript, the value with [1]

Move view with keyboard using Swift

i've read answers and solved my problem by this lines of code:

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var titleField: UITextField!
  @IBOutlet weak var priceField: UITextField!
  @IBOutlet weak var detailsField: UTtextField!

  override func viewDidLoad() {
   super.viewDidLoad()
// Do not to forget to set the delegate otherwise the textFieldShouldReturn(_:)
// won't work and the keyboard will never be hidden.
   priceField.delegate = self
   titleField.delegate = self
   detailsField.delegate = self

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
 name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
 name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }

   func textFieldShouldReturn(_ textField: UITextField) -> Bool {
      self.view.endEditing(true)
      return false
   }

 func keyboardWillShow(notification: NSNotification) {
   var translation:CGFloat = 0
   if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
     if detailsField.isEditing{
       translation = CGFloat(-keyboardSize.height)
     }else if priceField.isEditing{
       translation = CGFloat(-keyboardSize.height / 3.8)
     }
   }
    UIView.animate(withDuration: 0.2) {
   self.view.transform = CGAffineTransform(translationX: 0, y: translation)
    }
  }


 func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2) {
     self.view.transform = CGAffineTransform(translationX: 0, y: 0)
    } 
  }
}

I have a few UITextFields and want the view to move up differently depending on which textField is tapped.

How does the Python's range function work?

A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.

This code:

for i in range(5):
    print i

can be thought of working like this:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.

I assume that when you say "call a, it gives only 5", you mean like this:

for i in range(5):
    a=i+1
print a

this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.

Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.

I hope this answered your question.

Search and get a line in Python

you mentioned "entire line" , so i assumed mystring is the entire line.

if "token" in mystring:
    print(mystring)

however if you want to just get "token qwerty",

>>> mystring="""
...     qwertyuiop
...     asdfghjkl
...
...     zxcvbnm
...     token qwerty
...
...     asdfghjklñ
... """
>>> for item in mystring.split("\n"):
...  if "token" in item:
...     print (item.strip())
...
token qwerty

What's the difference between display:inline-flex and display:flex?

flex and inline-flex both apply flex layout to children of the container. Container with display:flex behaves like a block-level element itself, while display:inline-flex makes the container behaves like an inline element.

7-Zip command to create and extract a password-protected ZIP file on Windows?

To fully script-automate:

Create:

7z -mhc=on -mhe=on -pPasswordHere a %ZipDest% %WhatYouWantToZip%

Unzip:

7z x %ZipFile% -pPasswordHere

(Depending, you might need to: Set Path=C:\Program Files\7-Zip;%Path% )

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

How do you configure an OpenFileDialog to select folders?

Try this one from Codeproject (credit to Nitron):

I think it's the same dialog you're talking about - maybe it would help if you add a screenshot?

bool GetFolder(std::string& folderpath, const char* szCaption=NULL, HWND hOwner=NULL)
{
    bool retVal = false;

    // The BROWSEINFO struct tells the shell how it should display the dialog.
    BROWSEINFO bi;
    memset(&bi, 0, sizeof(bi));

    bi.ulFlags   = BIF_USENEWUI;
    bi.hwndOwner = hOwner;
    bi.lpszTitle = szCaption;

    // must call this if using BIF_USENEWUI
    ::OleInitialize(NULL);

    // Show the dialog and get the itemIDList for the selected folder.
    LPITEMIDLIST pIDL = ::SHBrowseForFolder(&bi);

    if(pIDL != NULL)
    {
        // Create a buffer to store the path, then get the path.
        char buffer[_MAX_PATH] = {'\0'};
        if(::SHGetPathFromIDList(pIDL, buffer) != 0)
        {
            // Set the string value.
            folderpath = buffer;
            retVal = true;
        }       

        // free the item id list
        CoTaskMemFree(pIDL);
    }

    ::OleUninitialize();

    return retVal;
}

Char to int conversion in C

You can use atoi, which is part of the standard library.

Using Composer's Autoload

In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

I was looking to autoload my package files using composer which I have under the dir structure given below.

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4 autoloading specification.

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

"autoload": {
        "psr-4": {
            "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

Elegant ways to support equivalence ("equality") in Python classes

You don't have to override both __eq__ and __ne__ you can override only __cmp__ but this will make an implication on the result of ==, !==, < , > and so on.

is tests for object identity. This means a is b will be True in the case when a and b both hold the reference to the same object. In python you always hold a reference to an object in a variable not the actual object, so essentially for a is b to be true the objects in them should be located in the same memory location. How and most importantly why would you go about overriding this behaviour?

Edit: I didn't know __cmp__ was removed from python 3 so avoid it.

Mongoose, update values in array of objects

update(
    {_id: 1, 'items.id': 2},
    {'$set': {'items.$[]': update}},
    {new: true})

Here is the doc about $[]: https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[]

How to add new activity to existing project in Android Studio?

To add an Activity using Android Studio.

This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.

[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.

enter image description here

  1. Right click either java package/java folder/module, I recommend to select a java package then right click it so that the destination of the Activity will be saved there
  2. Select/Click New
  3. Select Activity
  4. Choose an Activity that you want to create, probably the basic one.

To add a Service, or a BroadcastReceiver, just do the same step.

phpMyAdmin - config.inc.php configuration?

I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php is calling config-db.php

** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1

/etc/phpmyadmin/config-db.php:

$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';

Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration. That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs

How to change an Android app's name?

You might have to change the name of your main activity "android:label" also, as explained in Naming my application in android

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Use { before $ sign. And also add addslashes function to escape special characters.

$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";

Tab space instead of multiple non-breaking spaces ("nbsp")?

This is not a direct answer but I wanted to add a tab in Markdown document. I was drawing an object graph like this:

--Parent
    |
    + Child 1

Of course the easy way it to mark it as code by indenting by 4 spaces and is then treated as code in Markdown.

    --Parent
        |
        + Child 1

Can you issue pull requests from the command line on GitHub?

With the Hub command-line wrapper you can link it to git and then you can do git pull-request

From the man page of hub:

   git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
          Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one  of  the  following  formats:  "branch",  "owner:branch",
          "owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.

          If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.

          If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.

How can I tell when HttpClient has timed out?

I found that the best way to determine if the service call has timed out is to use a cancellation token and not the HttpClient's timeout property:

var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);

And then handle the CancellationException during the service call...

catch(TaskCanceledException)
{
    if(!cts.Token.IsCancellationRequested)
    {
        // Timed Out
    }
    else
    {
        // Cancelled for some other reason
    }
}

Of course if the timeout occurs on the service side of things, that should be able to handled by a WebException.

Displaying the build date

The option not discussed here is to insert your own data into AssemblyInfo.cs, the "AssemblyInformationalVersion" field seems appropriate - we have a couple of projects where we were doing something similar as a build step (however I'm not entirely happy with the way that works so don't really want to reproduce what we've got).

There's an article on the subject on codeproject: http://www.codeproject.com/KB/dotnet/Customizing_csproj_files.aspx

Timeout for python requests.get entire response

Despite the question being about requests, I find this very easy to do with pycurl CURLOPT_TIMEOUT or CURLOPT_TIMEOUT_MS.

No threading or signaling required:

import pycurl
import StringIO

url = 'http://www.example.com/example.zip'
timeout_ms = 1000
raw = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(pycurl.TIMEOUT_MS, timeout_ms)  # total timeout in milliseconds
c.setopt(pycurl.WRITEFUNCTION, raw.write)
c.setopt(pycurl.NOSIGNAL, 1)
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPGET, 1)
try:
    c.perform()
except pycurl.error:
    traceback.print_exc() # error generated on timeout
    pass # or just pass if you don't want to print the error

Making the Android emulator run faster

I recently switched from a core 2 @ 2.5 with 3gb of ram to an i7 @ 1.73 with 8gb ram (both systems ran Ubuntu 10.10) and the emulator runs at least twice as fast now. Throwing more hardware at it certainly does help.

How can I output UTF-8 from Perl?

Thanks, finally got an solution to not put utf8::encode all over code. To synthesize and complete for other cases, like write and read files in utf8 and also works with LoadFile of an YAML file in utf8

use utf8;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");

open(FH, ">test.txt"); 
print FH "something éá";

use YAML qw(LoadFile Dump);
my $PUBS = LoadFile("cache.yaml");
my $f = "2917";
my $ref = $PUBS->{$f};
print "$f \"".$ref->{name}."\" ". $ref->{primary_uri}." ";

where cache.yaml is:

---
2917:
  id: 2917
  name: Semanário
  primary_uri: 2917.xml

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

How to format a duration in java? (e.g format H:MM:SS)

In Scala, building up on YourBestBet's solution but simplified:

def prettyDuration(seconds: Long): List[String] = seconds match {
  case t if t < 60      => List(s"${t} seconds")
  case t if t < 3600    => s"${t / 60} minutes" :: prettyDuration(t % 60)
  case t if t < 3600*24 => s"${t / 3600} hours" :: prettyDuration(t % 3600)
  case t                => s"${t / (3600*24)} days" :: prettyDuration(t % (3600*24))
}

val dur = prettyDuration(12345).mkString(", ") // => 3 hours, 25 minutes, 45 seconds

Cross-Origin Request Headers(CORS) with PHP headers

In Windows, paste this command in run window just for time being to test the code

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

How to export data from Spark SQL to CSV

The error message suggests this is not a supported feature in the query language. But you can save a DataFrame in any format as usual through the RDD interface (df.rdd.saveAsTextFile). Or you can check out https://github.com/databricks/spark-csv.

AES Encrypt and Decrypt

I found the solution, it is a good library.

Cross platform 256bit AES encryption / decryption.

This project contains the implementation of 256 bit AES encryption which works on all the platforms (C#, iOS, Android). One of the key objective is to make AES work on all the platforms with simple implementation.

Platforms Supported: iOS , Android , Windows (C#).

https://github.com/Pakhee/Cross-platform-AES-encryption

How to decompile an APK or DEX file on Android platform?

Also you can use Android Multitool. You can make minor changes in the app like hiding GUI elements or modifying small part of Logic and rebuild the apk. Its easy to use and decompile/recompile apk and jar files. Here is the Link you can checkout.

Cheers

How to configure Eclipse build path to use Maven dependencies?

Maybe you could look into maven-eclipse-plugin instead of M2Eclipse.

There you basically add maven-eclipse-plugin configuration to your pom.xml and then execute mvn eclipse:eclipse which will generate the required .project and .classpath files for Eclipse. Then you'll have the correct build path in Eclipse.

How to get the children of the $(this) selector?

The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.

jQuery("img", this);

Which is the same as using .find() like this:

jQuery(this).find("img");

If the imgs you desire are only direct descendants of the clicked element, you can also use .children():

jQuery(this).children("img");

How do I get data from a table?

This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea

//gets table
var oTable = document.getElementById('myTable');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 0; i < rowLength; i++){

   //gets cells of current row
   var oCells = oTable.rows.item(i).cells;

   //gets amount of cells of current row
   var cellLength = oCells.length;

   //loops through each cell in current row
   for(var j = 0; j < cellLength; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

UPDATED - TESTED SCRIPT

<table id="myTable">
    <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
    </tr>
    <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
    </tr>
</table>
<script>
    //gets table
    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows    
    for (i = 0; i < rowLength; i++){

      //gets cells of current row  
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(j).innerHTML;
              alert(cellVal);
           }
    }
</script>

How to get the separate digits of an int number?

How about this?

public static void printDigits(int num) {
    if(num / 10 > 0) {
        printDigits(num / 10);
    }
    System.out.printf("%d ", num % 10);
}

or instead of printing to the console, we can collect it in an array of integers and then print the array:

public static void main(String[] args) {
    Integer[] digits = getDigits(12345);
    System.out.println(Arrays.toString(digits));
}

public static Integer[] getDigits(int num) {
    List<Integer> digits = new ArrayList<Integer>();
    collectDigits(num, digits);
    return digits.toArray(new Integer[]{});
}

private static void collectDigits(int num, List<Integer> digits) {
    if(num / 10 > 0) {
        collectDigits(num / 10, digits);
    }
    digits.add(num % 10);
}

If you would like to maintain the order of the digits from least significant (index[0]) to most significant (index[n]), the following updated getDigits() is what you need:

/**
 * split an integer into its individual digits
 * NOTE: digits order is maintained - i.e. Least significant digit is at index[0]
 * @param num positive integer
 * @return array of digits
 */
public static Integer[] getDigits(int num) {
    if (num < 0) { return new Integer[0]; }
    List<Integer> digits = new ArrayList<Integer>();
    collectDigits(num, digits);
    Collections.reverse(digits);
    return digits.toArray(new Integer[]{});
}

Updating a dataframe column in spark

DataFrames are based on RDDs. RDDs are immutable structures and do not allow updating elements on-site. To change values, you will need to create a new DataFrame by transforming the original one either using the SQL-like DSL or RDD operations like map.

A highly recommended slide deck: Introducing DataFrames in Spark for Large Scale Data Science.

Spring Boot yaml configuration for a list of strings

My guess is, that the @Value can not cope with "complex" types. You can go with a prop class like this:

@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
    List<String> filenames
}

Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.

See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list

Execute PowerShell Script from C# with Commandline Arguments

Here is a way to add Parameters to the script if you used

pipeline.Commands.AddScript(Script);

This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.

pipeline.Commands.AddScript(script));
FillVariables(pipeline, scriptParameter);
Collection<PSObject> results = pipeline.Invoke();

And the fill variable method is:

private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
  // Add additional variables to PowerShell
  if (scriptParameters != null)
  {
    foreach (DictionaryEntry entry in scriptParameters)
    {
      CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
      pipeline.Commands[0].Parameters.Add(Param);
    }
  }
}

this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:

Object resultcollection = runspace.SessionStateProxy.GetVariable("results");

//results being the name of the v

you'll have to do it the way I showed because for some reason if you do it the way Kosi2801 suggests the script variables list doesn't get filled with your own variables.

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

Generate random colors (RGB)

Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.

The cv::applyColorMap can easily generate a random RGB palette, and you can choose a favorite color map from the list here

Example for C++11:

#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>

std::random_device rd;
std::default_random_engine re(rd());

// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);

// ...

// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);

Example for Python3:

import numpy as np, cv2

palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...

rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)

If you don't need so many colors, you can just cut the palette to the desired length.

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

Directory.GetFiles of certain extension

Doesn't the Directory.GetFiles(String, String) overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)

If you want to put them in a list, then just replace the "*.jpg" with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)

Something like...

foreach(String fileExtension in extensionList){
    foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
        allFiles.Add(file);
    }
}

(If your directories are large, using EnumerateFiles instead of GetFiles can potentially be more efficient)

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

How to send 500 Internal Server Error error from a PHP script

You can just put:

header("HTTP/1.0 500 Internal Server Error");

inside your conditions like:

if (that happened) {
    header("HTTP/1.0 500 Internal Server Error");
}

As for the database query, you can just do that like this:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

You should remember that you have to put this code before any html tag (or output).

How to get a parent element to appear above child

Since your divs are position:absolute, they're not really nested as far as position is concerned. On your jsbin page I switched the order of the divs in the HTML to:

<div class="child"><div class="parent"></div></div>

and the red box covered the blue box, which I think is what you're looking for.

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

What is the iPhone 4 user-agent?

You cannot identify the (hardware) version of an iPhone by user agent.

It's only possible to recognize that it's an iPhone and which software versions it's running.

Using the Safari User Agent String

Not even WURLF can.

Responsive Images with CSS

check the images first with php if it is small then the standerd size for logo provide it any other css class and dont change its size

i think you have to take up scripting in between

Programmatically add custom event in the iPhone Calendar

Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.

https://developer.apple.com/bugreporter/

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

How to add comments into a Xaml file in WPF?

You cannot put comments inside UWP XAML tags. Your syntax is right.

TO DO:

<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
<!-- Cool comment -->

NOT TO DO:

<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    <!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib"/>

Change PictureBox's image to image from my resources?

Ok...so first you need to import in your project the image

1)Select the picturebox in Form Design

2)Open PictureBox Tasks (it's the little arrow pinted to right on the edge on the picturebox)

3)Click on "Choose image..."

4)Select the second option "Project resource file:" (this option will create a folder called "Resources" which you can acces with Properties.Resources)

5)Click on import and select your image from your computer (now a copy of the image with the same name as the image will be sent in Resources folder created at step 4)

6)Click on ok

Now the image is in your project and you can use it with Properties command.Just type this code when you want to change the picture from picturebox:

pictureBox1.Image = Properties.Resources.myimage;

Note: myimage represent the name of the image...after typing the dot after Resources,in your options it will be your imported image file

How can I set up an editor to work with Git on Windows?

Atom and Windows 10

  1. I right clicked the Atom icon at the desktop and clicked on properties.

  2. Copied the "Start in" location path

  3. Looked over there with Windows Explorer and found "atom.exe".

  4. I typed this in Git Bash:

    git config --global core.editor C:/Users/YOURNAMEUSER/AppData/Local/atom/app-1.7.4/atom.exe"
    

Note: I changed all \ for / . I created a .bashrc at my home directory and used / to set my home directory and it worked, so I assumed / will be the way to go.

How to check type of variable in Java?

I did it using: if(x.getClass() == MyClass.class){...}

Change R default library path using .libPaths in Rprofile.site fails to work

I was looking into this because R was having issues installing into the default location and was instead just putting the packages into the temp folder. It turned out to be the latest update for Mcaffee Endpoint Security which apparently has issues with R. You can disable the threat protection while you install the packages and it will work properly.

sendUserActionEvent() is null

Same issue on a Galaxy Tab and on a Xperia S, after uninstall and install again it seems that disappear.

The code that suddenly appear to raise this problem is this:

public void unlockMainActivity() {
    SharedPreferences prefs = getSharedPreferences("CALCULATOR_PREFS", 0);
    boolean hasCode = prefs.getBoolean("HAS_CODE", false);
    Context context = this.getApplicationContext();
    Intent intent = null;

    if (!hasCode) {
        intent = new Intent(context, WellcomeActivity.class);
    } else {
        intent = new Intent(context, CalculatingActivity.class);
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    (context).startActivity(intent);
}