Programs & Examples On #Primefaces

PrimeFaces is a JSF component library that ships with a large set of rich components which utilizes jQuery and jQuery UI under the covers. It supports the jQuery UI ThemeRoller CSS framework and FontAwesome icon set.

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

List of <p:ajax> events

I've got the list in debug mode; first I saw the point at which the error was thrown

javax.faces.view.facelets.TagException: /showcase/partial_submit.xhtml @26,36 Event:changed is not supported. org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.applyAttachedObject(AjaxBehaviorHandler.java:179) org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.apply(AjaxBehaviorHandler.java:157)

and then I debugged AjaxBehaviorHandler

enter image description here

so if you want discover the right list of supported event, you can generate an error (using an event name that is wrong), and follow this way

How to remove border from specific PrimeFaces p:panelGrid?

For the traditional as well as all the modern themes to have no border, apply the following;

<!--No Border on PanelGrid-->
    <h:outputStylesheet>
        .ui-panelgrid, .ui-panelgrid td, .ui-panelgrid tr, .ui-panelgrid tbody tr td
        {
            border: none !important;
            border-style: none !important;
            border-width: 0px !important;
        }
    </h:outputStylesheet>

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

I don't know what browser you're using, but according to w3schools.com, nth-child and nth-last-child do now work on MSIE 8. I don't know about 9. http://www.w3schools.com/cssref/pr_border-style.asp will give you more info.

selectOneMenu ajax events

I'd rather use more convenient itemSelect event. With this event you can use org.primefaces.event.SelectEvent objects in your listener.

<p:selectOneMenu ...>
    <p:ajax event="itemSelect" 
        update="messages"
        listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>

With such listener:

public void onItemSelectedListener(SelectEvent event){
    MyItem selectedItem = (MyItem) event.getObject();
    //do something with selected value
}

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

bean.xhtml

    <h:form enctype="multipart/form-data">    
<p:outputLabel value="Choose your file" for="submissionFile" />
                <p:fileUpload id="submissionFile"
                    value="#{bean.file}"
                    fileUploadListener="#{bean.uploadFile}" mode="advanced"
                    auto="true" dragDropSupport="false" update="messages"
                    sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" />

</h:form>

Bean.java

@ManagedBean

@ViewScoped public class Submission implements Serializable {

private UploadedFile file;

//Gets
//Sets

public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException {

    String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8");

    String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf";

    MyFileWriter.writeFile(filePath, content);

    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
            event.getFile().getFileName() + " is uploaded.", null);
    FacesContext.getCurrentInstance().addMessage(null, message);

}

}

web.xml

    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

Can I update a JSF component from a JSF backing bean method?

I also tried to update a component from a jsf backing bean/class

You need to do the following after manipulating the UI component:

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())

It is important to use the clientId instead of the (server-side) componentId!!

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

Convert timestamp long to normal date format

Not sure if JSF provides a built-in functionality, but you could use java.sql.Date's constructor to convert to a date object: http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html#Date(long)

Then you should be able to use higher level features provided by Java SE, Java EE to display and format the extracted date. You could instantiate a java.util.Calendar and explicitly set the time: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#setTime(java.util.Date)

EDIT: The JSF components should not take care of the conversion. Your data access layer (persistence layer) should take care of this. In other words, your JSF components should not handle the long typed attributes but only a Date or Calendar typed attributes.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

Another solution is to mix valueChangeListener, ajax and process:

<p:selectManyCheckbox id="employees" value="#{employees}" columns="1" layout="grid" valueChangeListener="#{mybean.fireSelection}"   >
    <f:selectItems var="employee" value="#{employeesSI}" />
    <p:ajax event="valueChange" immediate="true" process="@this"/>
</p:selectManyCheckbox>

Method in mybean is just :

public void fireSelection(ValueChangeEvent event) {
    log.debug("New: "+event.getNewValue()+", Old: "+event.getOldValue());
}

Like this, valueChangeEvent is very light !

PS: Works fine with PrimeFaces 5.0

SQL: Insert all records from one table to another table without specific the columns

You need to have at least the same number of columns and each column has to be defined in exactly the same way, i.e. a varchar column can't be inserted into an int column.

For bulk transfer, check the documentation for the SQL implementation you're using. There are often tools available to bulk transfer data from one table to another. For SqlServer 2005, for example, you could use the SQL Server Import and Export Wizard. Right-click on the database you're trying to move data around in and click Export to access it.

What is the proper way to re-throw an exception in C#?

You should always use "throw;" to rethrow the exceptions in .NET,

Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx

Basically MSIL (CIL) has two instructions - "throw" and "rethrow" and C#'s "throw ex;" gets compiled into MSIL's "throw" and C#'s "throw;" - into MSIL "rethrow"! Basically I can see the reason why "throw ex" overrides the stack trace.

Offline Speech Recognition In Android (JellyBean)

Google did quietly enable offline recognition in that Search update, but there is (as yet) no API or additional parameters available within the SpeechRecognizer class. {See Edit at the bottom of this post} The functionality is available with no additional coding, however the user’s device will need to be configured correctly for it to begin working and this is where the problem lies and I would imagine why a lot of developers assume they are ‘missing something’.

Also, Google have restricted certain Jelly Bean devices from using the offline recognition due to hardware constraints. Which devices this applies to is not documented, in fact, nothing is documented, so configuring the capabilities for the user has proved to be a matter of trial and error (for them). It works for some straight away – For those that it doesn't, this is the ‘guide’ I supply them with.

  1. Make sure the default Android Voice Recogniser is set to Google not Samsung/Vlingo
  2. Uninstall any offline recognition files you already have installed from the Google Voice Search Settings
  3. Go to your Android Application Settings and see if you can uninstall the updates for the Google Search and Google Voice Search applications.
  4. If you can't do the above, go to the Play Store see if you have the option there.
  5. Reboot (if you achieved 2, 3 or 4)
  6. Update Google Search and Google Voice Search from the Play Store (if you achieved 3 or 4 or if an update is available anyway).
  7. Reboot (if you achieved 6)
  8. Install English UK offline language files
  9. Reboot
  10. Use utter! with a connection
  11. Switch to aeroplane mode and give it a try
  12. Once it is working, the offline recognition of other languages, such as English US should start working too.

EDIT: Temporarily changing the device locale to English UK also seems to kickstart this to work for some.

Some users reported they still had to reboot a number of times before it would begin working, but they all get there eventually, often inexplicably to what was the trigger, the key to which are inside the Google Search APK, so not in the public domain or part of AOSP.

From what I can establish, Google tests the availability of a connection prior to deciding whether to use offline or online recognition. If a connection is available initially but is lost prior to the response, Google will supply a connection error, it won’t fall-back to offline. As a side note, if a request for the network synthesised voice has been made, there is no error supplied it if fails – You get silence.

The Google Search update enabled no additional features in Google Now and in fact if you try to use it with no internet connection, it will error. I mention this as I wondered if the ability would be withdrawn as quietly as it appeared and therefore shouldn't be relied upon in production.

If you intend to start using the SpeechRecognizer class, be warned, there is a pretty major bug associated with it, which require your own implementation to handle.

Not being able to specifically request offline = true, makes controlling this feature impossible without manipulating the data connection. Rubbish. You’ll get hundreds of user emails asking you why you haven’t enabled something so simple!

EDIT: Since API level 23 a new parameter has been added EXTRA_PREFER_OFFLINE which the Google recognition service does appear to adhere to.

Hope the above helps.

adding multiple entries to a HashMap at once in one statement

You could add this utility function to a utility class:

public static <K, V> Map<K, V> mapOf(Object... keyValues) {
    Map<K, V> map = new HashMap<>();

    for (int index = 0; index < keyValues.length / 2; index++) {
        map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
    }

    return map;
}

Map<Integer, String> map1 = YourClass.mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = YourClass.mapOf("key1", "value1", "key2", "value2");

Note: in Java 9 you can use Map.of

Better way to sum a property value in an array

I'm not sure this has been mentioned yet. But there is a lodash function for that. Snippet below where value is your attribute to sum is 'value'.

_.sumBy(objects, 'value');
_.sumBy(objects, function(o) { return o.value; });

Both will work.

Simple prime number generator in Python

Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).

Usage: primes = list(create_prime_iterator(1, 30))

import math
import itertools

def create_prime_iterator(rfrom, rto):
    """Create iterator of prime numbers in range [rfrom, rto]"""
    prefix = [2] if rfrom < 3 and rto > 1 else [] # include 2 if it is in range separately as it is a "weird" case of even prime
    odd_rfrom = 3 if rfrom < 3 else make_odd(rfrom) # make rfrom an odd number so that  we can skip all even nubers when searching for primes, also skip 1 as a non prime odd number.
    odd_numbers = (num for num in xrange(odd_rfrom, rto + 1, 2))
    prime_generator = (num for num in odd_numbers if not has_odd_divisor(num))
    return itertools.chain(prefix, prime_generator)

def has_odd_divisor(num):
    """Test whether number is evenly divisable by odd divisor."""
    maxDivisor = int(math.sqrt(num))
    for divisor in xrange(3, maxDivisor + 1, 2):
        if num % divisor == 0:
            return True
    return False

def make_odd(number):
    """Make number odd by adding one to it if it was even, otherwise return it unchanged"""
    return number | 1

Express.js - app.listen vs server.listen

There is one more difference of using the app and listening to http server is when you want to setup for https server

To setup for https, you need the code below:

var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
    console.log('Https App started');
});

The app from express will return http server only, you cannot set it in express, so you will need to use the https server command

var express = require('express');
var app = express();
app.listen(1234);

SQL how to increase or decrease one for a int column in one command

If my understanding is correct, updates should be pretty simple. I would just do the following.

UPDATE TABLE SET QUANTITY = QUANTITY + 1 and
UPDATE TABLE SET QUANTITY = QUANTITY - 1 where QUANTITY > 0

You may need additional filters to just update a single row instead of all the rows.

For inserts, you can cache some unique id related to your record locally and check against this cache and decide whether to insert or not. The alternative approach is to always insert and check for PK violation error and ignore since this is a redundant insert.

Get scroll position using jquery

Use scrollTop() to get or set the scroll position.

How to open Visual Studio Code from the command line on OSX?

After opening VSC and pressing (Command + Up + P) I tried typing in "shell command" and nothing came up. In order to get "Shell Command: Install 'code' command in PATH command" to come up, you must do the following:

  1. Press (Command, Up, P)

  2. Type > (this will show and run commands)

  3. Then type Shell Command: Install 'code' command in PATH command. It should then come up.

    Once you click it, it will update and you should be good to go!

MacOS X Launch from Command Line docs

How to convert a column of DataTable to a List

Is this what you need?

DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
    myList.Add((int)row[0]);
}

Entity Framework and Connection Pooling

  1. Connection pooling is handled as in any other ADO.NET application. Entity connection still uses traditional database connection with traditional connection string. I believe you can turn off connnection pooling in connection string if you don't want to use it. (read more about SQL Server Connection Pooling (ADO.NET))
  2. Never ever use global context. ObjectContext internally implements several patterns including Identity Map and Unit of Work. Impact of using global context is different per application type.
  3. For web applications use single context per request. For web services use single context per call. In WinForms or WPF application use single context per form or per presenter. There can be some special requirements which will not allow to use this approach but in most situation this is enough.

If you want to know what impact has single object context for WPF / WinForm application check this article. It is about NHibernate Session but the idea is same.

Edit:

When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.

Any changes made to the entity are not persisted until you call SaveChanges on the context. You can do changes in multiple entities and store them at once. This is called Unit of Work pattern. You can't selectively say which modified attached entity you want to save.

Combine these two patterns and you will see some interesting effects. You have only one instance of entity for the whole application. Any changes to the entity affect the whole application even if changes are not yet persisted (commited). In the most times this is not what you want. Suppose that you have an edit form in WPF application. You are working with the entity and you decice to cancel complex editation (changing values, adding related entities, removing other related entities, etc.). But the entity is already modified in shared context. What will you do? Hint: I don't know about any CancelChanges or UndoChanges on ObjectContext.

I think we don't have to discuss server scenario. Simply sharing single entity among multiple HTTP requests or Web service calls makes your application useless. Any request can just trigger SaveChanges and save partial data from another request because you are sharing single unit of work among all of them. This will also have another problem - context and any manipulation with entities in the context or a database connection used by the context is not thread safe.

Even for a readonly application a global context is not a good choice because you probably want fresh data each time you query the application.

How do format a phone number as a String in Java?

The easiest way to do this is by using the built in MaskFormatter in the javax.swing.text library.

You can do something like this :

import javax.swing.text.MaskFormatter;

String phoneMask= "###-###-####";
String phoneNumber= "123423452345";

MaskFormatter maskFormatter= new MaskFormatter(phoneMask);
maskFormatter.setValueContainsLiteralCharacters(false);
maskFormatter.valueToString(phoneNumber) ;

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

insert data into database with codeigniter

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cnt extends CI_Controller {


 public function insert_view()
 {
  $this->load->view('insert');
 }
 public function insert_data(){
  $name=$this->input->post('emp_name');
  $salary=$this->input->post('emp_salary');
  $arr=array(
   'emp_name'=>$name,
   'emp_salary'=>$salary
   );
  $resp=$this->Model->insert_data('emp1',$arr);
  echo "<script>alert('$resp')</script>";
  $this->insert_view();  
 }
}

for more detail visit: http://wheretodownloadcodeigniter.blogspot.com/2018/04/insert-using-codeigniter.html

Html encode in PHP

Encode.php

<h1>Encode HTML CODE</h1>

<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>

htmlencodeoutput.php

<?php

$code=bin2hex($_POST['inputval']); 
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
 $sublen=$totallen-1;
 $fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";

?> 
<textarea rows='20' cols='100'><?php echo $output?> </textarea> 

You can encode HTML like this .

Getting a count of objects in a queryset in django

Use related name to count votes for a specific contest

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest, related_name="contest_votes")
    comment = models.TextField()

>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()

C# Parsing JSON array of objects

I believe this is much simpler;

dynamic obj = JObject.Parse(jsonString);
string results  = obj.results;
foreach(string result in result.Split('))
{
//Todo
}

How to enable LogCat/Console in Eclipse for Android?

In the "Window" menu, open "Open Perspective" -> "Debug".

alt text click On the plus image icon(you see the below image at status bar), and then select "Logcat"....

Getting a machine's external IP address with Python

Use requests module:

import requests

myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']

print("\n[+] Public IP: "+myip)

Visual Studio 2012 Web Publish doesn't copy files

I ran into the same problem on VS 2010, after checking publish output, event logs, turning on and checking visual studio logs etc I then decided to remove the web publish (via add/remove) which I believe had been recently updated to v1.0.30810.0. This resolved the problem.

How can I escape latex code received through user input?

I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:

s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]

How do I return clean JSON from a WCF Service?

I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);

The returned object will no longer be wrapped.

ImportError: Cannot import name X

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

How to write a basic swap function in Java

Snippet-1

public int[] swap1(int[] values) {
  if (values == null || values.length != 2)
    throw new IllegalArgumentException("parameter must be an array of size 2");
  int temp = values[0];
  values[0]=values[1];
  values[1]=temp;
  return values;
}

Snippet-2

public Point swap2(java.awt.Point p) {
  if (p == null)
    throw new NullPointerException();
  int temp = p.x;
  p.x = p.y;
  p.y = temp;
  return p;
}

Usage:

int[] values = swap1(new int[]{x,y});
x = values[0];
y = values[1];

Point p = swap2(new Point(x,y));
x = p.x;
y = p.y;

How to set the maximum memory usage for JVM?

The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.

That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.

Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.

How to configure port for a Spring Boot application

Also, you can configure the port programmatically.

For Spring Boot 2.x.x:

@Configuration
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
  public void customize(ConfigurableServletWebServerFactory factory){
    factory.setPort(8042);
  }
}

For older versions:

@Configuration
public class ServletConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            container.setPort(8012);
        });
    }
}

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

Ping site and return result in PHP

Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).

Example usage:

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Git

This answer includes GitHub as many folks have asked about that too.

Local repositories

Git (locally) has a directory (.git) which you commit your files to and this is your 'local repository'. This is different from systems like SVN where you add and commit to the remote repository immediately.

Git stores each version of a file that changes by saving the entire file. It is also different from SVN in this respect as you could go to any individual version without 'recreating' it through delta changes.

Git doesn't 'lock' files at all and thus avoids the 'exclusive lock' functionality for an edit (older systems like pvcs come to mind), so all files can always be edited, even when off-line. It actually does an amazing job of merging file changes (within the same file!) together during pulls or fetches/pushes to a remote repository such as GitHub. The only time you need to do manual changes (actually editing a file) is if two changes involve the same line(s) of code.


Branches

Branches allow you to preserve the main code (the 'master' branch), make a copy (a new branch) and then work within that new branch. If the work takes a while or master gets a lot of updates since the branch was made then merging or rebasing (often preferred for better history and easier to resolve conflicts) against the master branch should be done. When you've finished, you merge the changes made in the branch back in to the master repository. Many organizations use branches for each piece of work whether it is a feature, bug or chore item. Other organizations only use branches for major changes such as version upgrades.

Fork: With a branch you control and manage the branch, whereas with a fork someone else controls accepting the code back in.

Broadly speaking, there are two main approaches to doing branches. The first is to keep most changes on the master branch, only using branches for larger and longer-running things like version changes where you want to have two branches available for different needs. The second is whereby you basically make a branch for every feature request, bug fix or chore and then manually decide when to actually merge those branches into the main master branch. Though this sounds tedious, this is a common approach and is the one that I currently use and recommend because this keeps the master branch cleaner and it's the master that we promote to production, so we only want completed, tested code, via the rebasing and merging of branches.

The standard way to bring a branch 'in' to master is to do a merge. Branches can also be "rebased" to 'clean up' history. It doesn't affect the current state and is done to give a 'cleaner' history.

Basically, the idea is that you branched from a certain point (usually from master). Since you branched, 'master' itself has since moved forward from that branching point. It will be 'cleaner' (easier to resolve issues and the history will be easier to understand) if all the changes you have done in a branch are played against the current state of master with all of its latest changes. So, the process is: save the changes; get the 'new' master, and then reapply (this is the rebase part) the changes again against that. Be aware that rebase, just like merge, can result in conflicts that you have to manually resolve (i.e. edit and fix).

One guideline to note:
Only rebase if the branch is local and you haven't pushed it to remote yet!
This is mainly because rebasing can alter the history that other people see which may include their own commits.

Tracking branches

These are the branches that are named origin/branch_name (as opposed to just branch_name). When you are pushing and pulling the code to/from remote repositories this is actually the mechanism through which that happens. For example, when you git push a branch called building_groups, your branch goes first to origin/building_groups and then that goes to the remote repository. Similarly, if you do a git fetch building_groups, the file that is retrieved is placed in your origin/building_groups branch. You can then choose to merge this branch into your local copy. Our practice is to always do a git fetch and a manual merge rather than just a git pull (which does both of the above in one step).

Fetching new branches.

Getting new branches: At the initial point of a clone you will have all the branches. However, if other developers add branches and push them to the remote there needs to be a way to 'know' about those branches and their names in order to be able to pull them down locally. This is done via a git fetch which will get all new and changed branches into the locally repository using the tracking branches (e.g., origin/). Once fetched, one can git branch --remote to list the tracking branches and git checkout [branch] to actually switch to any given one.

Merging

Merging is the process of combining code changes from different branches, or from different versions of the same branch (for example when a local branch and remote are out of sync). If one has developed work in a branch and the work is complete, ready and tested, then it can be merged into the master branch. This is done by git checkout master to switch to the master branch, then git merge your_branch. The merge will bring all the different files and even different changes to the same files together. This means that it will actually change the code inside files to merge all the changes.

When doing the checkout of master it's also recommended to do a git pull origin master to get the very latest version of the remote master merged into your local master. If the remote master changed, i.e., moved forward, you will see information that reflects that during that git pull. If that is the case (master changed) you are advised to git checkout your_branch and then rebase it to master so that your changes actually get 'replayed' on top of the 'new' master. Then you would continue with getting master up-to-date as shown in the next paragraph.

If there are no conflicts, then master will have the new changes added in. If there are conflicts, this means that the same files have changes around similar lines of code that it cannot automatically merge. In this case git merge new_branch will report that there's conflict(s) to resolve. You 'resolve' them by editing the files (which will have both changes in them), selecting the changes you want, literally deleting the lines of the changes you don't want and then saving the file. The changes are marked with separators such as ======== and <<<<<<<<.

Once you have resolved any conflicts you will once again git add and git commit those changes to continue the merge (you'll get feedback from git during this process to guide you).

When the process doesn't work well you will find that git merge --abort is very handy to reset things.

Interactive rebasing and squashing / reordering / removing commits

If you have done work in a lot of small steps, e.g., you commit code as 'work-in-progress' every day, you may want to 'squash' those many small commits into a few larger commits. This can be particularly useful when you want to do code reviews with colleagues. You don't want to replay all the 'steps' you took (via commits), you want to just say here is the end effect (diff) of all of my changes for this work in one commit.

The key factor to evaluate when considering whether to do this is whether the multiple commits are against the same file or files more than once (better to squash commits in that case). This is done with the interactive rebasing tool. This tool lets you squash commits, delete commits, reword messages, etc. For example, git rebase -i HEAD~10 (note: that's a ~, not a -) brings up the following:

interactive rebasing in Git

Be careful though and use this tool 'gingerly'. Do one squash/delete/reorder at a time, exit and save that commit, then reenter the tool. If commits are not contiguous you can reorder them (and then squash as needed). You can actually delete commits here too, but you really need to be sure of what you are doing when you do that!

Forks

There are two main approaches to collaboration in Git repositories. The first, detailed above, is directly via branches that people pull and push from/to. These collaborators have their SSH keys registered with the remote repository. This will let them push directly to that repository. The downside is that you have to maintain the list of users. The other approach - forking - allows anybody to 'fork' the repository, basically making a local copy in their own Git repository account. They can then make changes and when finished send a 'pull request' (really it's more of a 'push' from them and a 'pull' request for the actual repository maintainer) to get the code accepted.

This second method, using forks, does not require someone to maintain a list of users for the repository.


GitHub

GitHub (a remote repository) is a remote source that you normally push and pull those committed changes to if you have (or are added to) such a repository, so local and remote are actually quite distinct. Another way to think of a remote repository is that it is a .git directory structure that lives on a remote server.

When you 'fork' - in the GitHub web browser GUI you can click on this button Image of fork button - you create a copy ('clone') of the code in your GitHub account. It can be a little subtle first time you do it, so keep making sure you look at whose repository a code base is listed under - either the original owner or 'forked from' and you, e.g., like this:

Image of name of forked repository

Once you have the local copy, you can make changes as you wish (by pulling and pushing them to a local machine). When you are done then you submit a 'pull request' to the original repository owner/admin (sounds fancy but actually you just click on this: Image of pull request button) and they 'pull' it in.

More common for a team working on code together is to 'clone' the repository (click on the 'copy' icon on the repository's main screen). Then, locally type git clone and paste. This will set you up locally and you can also push and pull to the (shared) GitHub location.

Clones

As indicated in the section on GitHub, a clone is a copy of a repository. When you have a remote repository you issue the git clone command against its URL and you then end up with a local copy, or clone, of the repository. This clone has everything, the files, the master branch, the other branches, all the existing commits, the whole shebang. It is this clone that you do your adds and commits against and then the remote repository itself is what you push those commits to. It's this local/remote concept that makes Git (and systems similar to it such as Mercurial) a DVCS (Distributed Version Control System) as opposed to the more traditional CVSs (Code Versioning Systems) such as SVN, PVCS, CVS, etc. where you commit directly to the remote repository.

Visualization

Visualization of the core concepts can be seen at
http://marklodato.github.com/visual-git-guide/index-en.html and
http://ndpsoftware.com/git-cheatsheet.html#loc=index

If you want a visual display of how the changes are working, you can't beat the visual tool gitg (gitx for macOS) with a GUI that I call 'the subway map' (esp. London Underground), great for showing who did what, how things changes, diverged and merged, etc.

You can also use it to add, commit and manage your changes!

Image of gitg/gitx interface

Although gitg/gitx is fairly minimal, the number of GUI tools continues to expand. Many Mac users use brotherbard's fork of gitx and for Linux, a great option is smart-git with an intuitive yet powerful interface:

Image of smart-git GUI

Note that even with a GUI tool, you will probably do a lot of commands at the command line.

For this, I have the following aliases in my ~/.bash_aliases file (which is called from my ~/.bashrc file for each terminal session):

# git
alias g='git status'
alias gcob='git checkout -b '
alias gcom='git checkout master'
alias gd='git diff'
alias gf='git fetch'
alias gfrm='git fetch; git reset --hard origin/master'
alias gg='git grep '
alias gits='alias | grep "^alias g.*git.*$"'
alias gl='git log'
alias gl1='git log --oneline'
alias glf='git log --name-status'
alias glp='git log -p'
alias gpull='git pull '
alias gpush='git push '

AND I have the following "git aliases" in my ~/.gitconfig file - why have these ?
So that branch completion (with the TAB key) works !

So these are:

[alias]
  co = checkout
  cob = checkout -b

Example usage: git co [branch] <- tab completion for branches will work.

GUI Learning Tool

You may find https://learngitbranching.js.org/ useful in learning some of the base concepts. Screen shot: enter image description here
Video: https://youtu.be/23JqqcLPss0

Finally, 7 key lifesavers!

  1. You make changes, add and commit them (but don't push) and then oh! you realize you are in master!

    git reset [filename(s)]
    git checkout -b [name_for_a_new_branch]
    git add [file(s)]
    git commit -m "A useful message"
    
    Voila!  You've moved that 'master' commit to its own branch !
    
  2. You mess up some files while working in a local branch and simply want to go back to what you had the last time you did a git pull:

    git reset --hard origin/master  # You will need to be comfortable doing this!
    
  3. You start making changes locally, you edit half a dozen files and then, oh crap, you're still in the master (or another) branch:

    git checkout -b new_branch_name  # just create a new branch
    git add .                      # add the changes files
    git commit -m"your message"    # and commit them
    
  4. You mess up one particular file in your current branch and want to basically 'reset' that file (lose changes) to how it was the the last time you pulled it from the remote repository:

    git checkout your/directories/filename
    

    This actually resets the file (like many Git commands it is not well named for what it is doing here).

  5. You make some changes locally, you want to make sure you don't lose them while you do a git reset or rebase: I often make a manual copy of the entire project (cp -r ../my_project ~/) when I am not sure if I might mess up in Git or lose important changes.

  6. You are rebasing but things gets messed up:

    git rebase --abort # To abandon interactive rebase and merge issues
    
  7. Add your Git branch to your PS1 prompt (see https://unix.stackexchange.com/a/127800/10043), e.g.

    Image of prompt

    The branch is selenium_rspec_conversion.

'MOD' is not a recognized built-in function name

If using JDBC driver you may use function escape sequence like this:

select {fn MOD(5, 2)}
#Result 1

select  mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

Composer: how can I install another dependency without updating old ones?

In my case, I had a repo with:

  • requirements A,B,C,D in .json
  • but only A,B,C in the .lock

In the meantime, A,B,C had newer versions with respect when the lock was generated.

For some reason, I deleted the "vendors" and wanted to do a composer install and failed with the message:

Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.

I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD but composer insisted to update more things, so .lock had too changes seen my my git tool.

The solution I used was:

  1. Delete all the vendors dir.
  2. Temporarily remove the requirement VendorD/LibraryD from the .json.
  3. run composer install.
  4. Then delete the file .json and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).
  5. Then run Seldaek's solution composer update vendorD/libraryD

It did install the library, but in addition, git diff showed me that in the .lock only the new things were added without editing the other ones.

(Thnx Seldaek for the pointer ;) )

Remove all child elements of a DOM node in JavaScript

This is a pure javascript i am not using jQuery but works in all browser even IE and it is verry simple to understand

   <div id="my_div">
    <p>Paragraph one</p>
    <p>Paragraph two</p>
    <p>Paragraph three</p>
   </div>
   <button id ="my_button>Remove nodes ?</button>

   document.getElementById("my_button").addEventListener("click",function(){

  let parent_node =document.getElemetById("my_div"); //Div which contains paagraphs

  //Let find numbers of child inside the div then remove all
  for(var i =0; i < parent_node.childNodes.length; i++) {
     //To avoid a problem which may happen if there is no childNodes[i] 
     try{
       if(parent_node.childNodes[i]){
         parent_node.removeChild(parent_node.childNodes[i]);
       }
     }catch(e){
     }
  }

})

or you may simpli do this which is a quick way to do

document.getElementById("my_button").addEventListener("click",function(){

 let parent_node =document.getElemetById("my_div");
 parent_node.innerHTML ="";

})

Stack smashing detected

It means that you wrote to some variables on the stack in an illegal way, most likely as the result of a Buffer overflow.

Interactive shell using Docker Compose

You need to include the following lines in your docker-compose.yml:

version: "3"
services:
  app:
    image: app:1.2.3
    stdin_open: true # docker run -i
    tty: true        # docker run -t

The first corresponds to -i in docker run and the second to -t.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

For all those people stuck with this problem, but still couldn't solve it: I stumbled upon the same error and found the _id field being empty.

I described it here in more detail. Still have not found a solution except changing the fields in _id to not-ID fields which is a dirty hack to me. I'm probably going to file a bug report for mongoose. Any help would be appreciated!

Edit: I updated my thread. I filed a ticket and they confirmed the missing _id problem. It is going to be fixed in the 4.x.x version which has a release candidate available right now. The rc is not recommended for productive use!

Kill process by name?

If you want to kill the process(es) or cmd.exe carrying a particular title(s).

import csv, os
import subprocess
# ## Find the command prompt windows.
# ## Collect the details of the command prompt windows and assign them.
tasks = csv.DictReader(subprocess.check_output('tasklist /fi "imagename eq cmd.exe" /v /fo csv').splitlines(), delimiter=',', quotechar='"')
# ## The cmds with titles to be closed.
titles= ["Ploter", "scanFolder"]

# ## Find the PIDs of the cmds with the above titles.
PIDList = []
for line in tasks:
    for title in titles:
        if  title in line['Window Title']:
           print line['Window Title']       
           PIDList.append(line['PID'])

# ## Kill the CMDs carrying the PIDs in PIDList
for id in PIDList:
    os.system('taskkill /pid ' + id ) 

Hope it helps. Their might be numerous better solutions to mine.

How do I get a YouTube video thumbnail from the YouTube API?

    function get_video_thumbnail( $src ) {
            $url_pieces = explode('/', $src);
            if( $url_pieces[2] == 'dai.ly'){
                $id = $url_pieces[3];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if($url_pieces[2] == 'www.dailymotion.com'){
                $id = $url_pieces[4];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if ( $url_pieces[2] == 'vimeo.com' ) { // If Vimeo
                $id = $url_pieces[3];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'youtu.be' ) { // If Youtube
                $extract_id = explode('?', $url_pieces[3]);
                $id = $extract_id[0];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            }else if ( $url_pieces[2] == 'player.vimeo.com' ) { // If Vimeo
                $id = $url_pieces[4];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'www.youtube.com' ) { // If Youtube
                $extract_id = explode('=', $url_pieces[3]);
                $id = $extract_id[1];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            } else{
                $thumbnail = tim_thumb_default_image('video-icon.png', null, 147, 252);
            }
            return $thumbnail;
        }

get_video_thumbnail('https://vimeo.com/154618727');
get_video_thumbnail('https://www.youtube.com/watch?v=SwU0I7_5Cmc');
get_video_thumbnail('https://youtu.be/pbzIfnekjtM');
get_video_thumbnail('http://www.dailymotion.com/video/x5thjyz');

Programmatically scroll to a specific position in an Android ListView

I have set OnGroupExpandListener and override onGroupExpand() as:

and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This can also happen when you disabled MFA. There will be an old long term entry in the AWS credentials.

Edit the file manually with editor of choice, here using vi (please backup before):

vi ~/.aws/credentials

Then remove the [default-long-term] section. As result in a minimal setup there should be one section [default] left with the actual credentials.

[default-long-term]
aws_access_key_id = ...
aws_secret_access_key = ...
aws_mfa_device = ...

How do you get the index of the current iteration of a foreach loop?

Here is another solution to this problem, with a focus on keeping the syntax as close to a standard foreach as possible.

This sort of construct is useful if you are wanting to make your views look nice and clean in MVC. For example instead of writing this the usual way (which is hard to format nicely):

 <%int i=0;
 foreach (var review in Model.ReviewsList) { %>
    <div id="review_<%=i%>">
        <h3><%:review.Title%></h3>                      
    </div>
    <%i++;
 } %>

You could instead write this:

 <%foreach (var review in Model.ReviewsList.WithIndex()) { %>
    <div id="review_<%=LoopHelper.Index()%>">
        <h3><%:review.Title%></h3>                      
    </div>
 <%} %>

I've written some helper methods to enable this:

public static class LoopHelper {
    public static int Index() {
        return (int)HttpContext.Current.Items["LoopHelper_Index"];
    }       
}

public static class LoopHelperExtensions {
    public static IEnumerable<T> WithIndex<T>(this IEnumerable<T> that) {
        return new EnumerableWithIndex<T>(that);
    }

    public class EnumerableWithIndex<T> : IEnumerable<T> {
        public IEnumerable<T> Enumerable;

        public EnumerableWithIndex(IEnumerable<T> enumerable) {
            Enumerable = enumerable;
        }

        public IEnumerator<T> GetEnumerator() {
            for (int i = 0; i < Enumerable.Count(); i++) {
                HttpContext.Current.Items["LoopHelper_Index"] = i;
                yield return Enumerable.ElementAt(i);
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }

In a non-web environment you could use a static instead of HttpContext.Current.Items.

This is essentially a global variable, and so you cannot have more than one WithIndex loop nested, but that is not a major problem in this use case.

How to serve up images in Angular2?

Angular only points to src/assets folder, nothing else is public to access via url so you should use full path

 this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'

Or

 this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'

This will only work if the base href tag is set with /

You can also add other folders for data in angular/cli. All you need to modify is angular-cli.json

"assets": [
 "assets",
 "img",
 "favicon.ico",
 ".htaccess"
]

Note in edit : Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.

How can I parse JSON with C#?

System.Json works now...

Install nuget https://www.nuget.org/packages/System.Json

PM> Install-Package System.Json -Version 4.5.0

Sample:

// PM>Install-Package System.Json -Version 4.5.0

using System;
using System.Json;

namespace NetCoreTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Note that JSON keys are case sensitive, a is not same as A.

            // JSON Sample
            string jsonString = "{\"a\": 1,\"b\": \"string value\",\"c\":[{\"Value\": 1}, {\"Value\": 2,\"SubObject\":[{\"SubValue\":3}]}]}";

            // You can use the following line in a beautifier/JSON formatted for better view
            // {"a": 1,"b": "string value","c":[{"Value": 1}, {"Value": 2,"SubObject":[{"SubValue":3}]}]}

            /* Formatted jsonString for viewing purposes:
            {
               "a":1,
               "b":"string value",
               "c":[
                  {
                     "Value":1
                  },
                  {
                     "Value":2,
                     "SubObject":[
                        {
                           "SubValue":3
                        }
                     ]
                  }
               ]
            }
            */

            // Verify your JSON if you get any errors here
            JsonValue json = JsonValue.Parse(jsonString);

            // int test
            if (json.ContainsKey("a"))
            {
                int a = json["a"]; // type already set to int
                Console.WriteLine("json[\"a\"]" + " = " + a);
            }

            // string test
            if (json.ContainsKey("b"))
            {
                string b = json["b"];  // type already set to string
                Console.WriteLine("json[\"b\"]" + " = " + b);
            }

            // object array test
            if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array)
            {
                // foreach loop test
                foreach (JsonValue j in json["c"])
                {
                    Console.WriteLine("j[\"Value\"]" + " = " + j["Value"].ToString());
                }

                // multi level key test
                Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][0]["Value"].ToString());
                Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][1]["Value"].ToString());
                Console.WriteLine("json[\"c\"][1][\"SubObject\"][0][\"SubValue\"]" + " = " + json["c"][1]["SubObject"][0]["SubValue"].ToString());
            }

            Console.WriteLine();
            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

How to grant remote access to MySQL for a whole subnet?

MySQL 8.0.23 onwards now support CIDR notation also.

So, basically:

-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...

-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...

Facebook share link - can you customize the message body text?

Facebook does not allow you to change the "What's on your mind?" text box, unless of course you're developing an application for use on Facebook.

Is there a GUI design app for the Tkinter / grid geometry?

The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.

Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.

* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).

Exact difference between CharSequence and String in java

From the Java API of CharSequence:

A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences.

This interface is then used by String, CharBuffer and StringBuffer to keep consistency for all method names.

Correct mime type for .mp4

video/mp4should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4. Also, as a server, you should try to include the codecs or profiles parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.

Android disable screen timeout while app is running

Simple add below line into your MainActivity and your App never turn lights off.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

How to make html <select> element look like "disabled", but pass values?

Wow, I had the same problem, but a line of code resolved my problem. I wrote

$last_child_topic.find( "*" ).prop( "disabled", true );
$last_child_topic.find( "option" ).prop( "disabled", false );   //This seems to work on mine

I send the form to a php script then it prints the correct value for each options while it was "null" before.

Tell me if this works out. I wonder if this only works on mine somehow.

How to rename a table in SQL Server?

Nothing worked from proposed here .. So just pored the data into new table

SELECT * 
INTO [acecodetable].['PSCLineReason']
FROM [acecodetable].['15_PSCLineReason'];

maybe will be useful for someone..

In my case it didn't recognize the new schema also the dbo was the owner..

UPDATE

EXECUTE sp_rename N'[acecodetable].[''TradeAgreementClaim'']', N'TradeAgreementClaim';

Worked for me. I found it from the script generated automatically when updating the PK for one of the tables. This way it recognized the new schema as well..

Spring Data JPA - "No Property Found for Type" Exception

I ran into this same issue and found the solution here: https://dzone.com/articles/persistence-layer-spring-data

I had renamed an entity property. But with Springs Automatic Custom Queries there was an interface defined for the old property name.

public interface IFooDAO extends JpaRepository< Foo, Long >{
     Foo findByOldPropName( final String name );
}

The error indicated that it could no longer find "OldPropName" and threw the exception.

To quote the article on DZone:

When Spring Data creates a new Repository implementation, it analyzes all the methods defined by the interfaces and tries to automatically generate queries from the method name. While this has limitations, it is a very powerful and elegant way of defining new custom access methods with very little effort. For example, if the managed entity has a name field (and the Java Bean standard getter and setter for that field), defining the findByName method in the DAO interface will automatically generate the correct query:

public interface IFooDAO extends JpaRepository< Foo, Long >{
     Foo findByName( final String name );
}

This is a relatively simple example; a much larger set of keywords is supported by query creation mechanism.

In the case that the parser cannot match the property with the domain object field, the following exception is thrown:

java.lang.IllegalArgumentException: No property nam found for type class org.rest.model.Foo

Mipmap drawables for icons

The Android implementation of mipmaps in 4.3 is exactly the technique from 1983 explained in the Wikipedia article :)

Each bitmap image of the mipmap set is a downsized duplicate of the main texture, but at a certain reduced level of detail. Although the main texture would still be used when the view is sufficient to render it in full detail, the renderer will switch to a suitable mipmap image (...) when the texture is viewed from a distance or at a small size.

Although this is described as a technique for 3D graphics (as it mentions "viewing from a distance"), it applies just as well to 2D (translated as "drawn is a smaller space", i.e. "downscaled").

For a concrete Android example, imagine you have a View with a certain background drawable (in particular, a BitmapDrawable). You now use an animation to scale it to 0.15 of its original size. Normally, this would require downscaling the background bitmap for each frame. This "extreme" downscaling, however, may produce visual artifacts.

You can, however, provide a mipmap, which means that the image is already pre-rendered for a few specific scales (let's say 1.0, 0.5, and 0.25). Whenever the animation "crosses" the 0.5 threshold, instead of continuing to downscale the original, 1.0-sized image, it will switch to the 0.5 image and downscale it, which should provide a better result. And so forth as the animation continues.

This is a bit theoretical, since it's actually done by the renderer. According to the source of the Bitmap class, it's just a hint, and the renderer may or may not honor it.

/**
 * Set a hint for the renderer responsible for drawing this bitmap
 * indicating that it should attempt to use mipmaps when this bitmap
 * is drawn scaled down.
 *
 * If you know that you are going to draw this bitmap at less than
 * 50% of its original size, you may be able to obtain a higher
 * quality by turning this property on.
 * 
 * Note that if the renderer respects this hint it might have to
 * allocate extra memory to hold the mipmap levels for this bitmap.
 *
 * This property is only a suggestion that can be ignored by the
 * renderer. It is not guaranteed to have any effect.
 *
 * @param hasMipMap indicates whether the renderer should attempt
 *                  to use mipmaps
 *
 * @see #hasMipMap()
 */
public final void setHasMipMap(boolean hasMipMap) {
    nativeSetHasMipMap(mNativeBitmap, hasMipMap);
}

I'm not quite sure why this would be especially suitable for application icons, though. Although Android on tablets, as well as some launchers (e.g. GEL), request an icon "one density higher" to show it bigger, this is supposed to be done using the regular mechanism (i.e. drawable-xxxhdpi, &c).

How to fix Subversion lock error

I had similar problem. Team->Refresh/Cleanup Solved my problem

Return Result from Select Query in stored procedure to a List

I had the same question, took me ages to find a simple solution.

Using ASP.NET MVC 5 and EF 6:

When you add a stored procedure to your .edmx model, the result of the stored procedure will be delivered via an auto-generated object called yourStoredProcName_result.

This _result object contains the attributes corresponding to the columns in the database that your stored procedure selected.

The _result class can be simply converted to a list:

yourStoredProcName_result.ToList()

How to replace a string in a SQL Server Table Column

UPDATE [table]
SET [column] = REPLACE([column], '/foo/', '/bar/')

How does facebook, gmail send the real time notification?

Update

As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.


I had the same issue recently and researched about the subject.

The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).

Long Polling - Client

Here, to keep code short, I will use jQuery:

function pollTask() { 

    $.ajax({

        url: '/api/Polling',
        async: true,            // by default, it's async, but...
        dataType: 'json',       // or the dataType you are working with
        timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
        cache: false

    }).done(function (eventList) {  

       // Handle your data here
       var data;
       for (var eventName in eventList) {

            data = eventList[eventName];
            dispatcher.handle(eventName, data); // handle the `eventName` with `data`

       }

    }).always(pollTask);

}

It is important to remember that (from jQuery docs):

In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

Long Polling - Server

It is not in any specific language, but it would be something like this:

function handleRequest () {  

     while (!anythingHappened() || hasTimedOut()) { sleep(2); }

     return events();

} 

Here, hasTimedOut will make sure your code does not wait forever, and anythingHappened, will check if any event happend. The sleep is for releasing your thread to do other stuff while nothing happens. The events will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).

It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.

Solution

Use sockets!

On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.

On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.

If you don't like this solution, try APE (Ajax Push Engine).

Hope I helped.

How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

How to export data from Spark SQL to CSV

With the help of spark-csv we can write to a CSV file.

val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`

Failed to execute 'atob' on 'Window'

Here I got the error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Because you didn't pass a base64-encoded string. Look at your functions: both download and dataURItoBlob do expect a data URI for some reason; you however are passing a plain html markup string to download in your example.

Not only is HTML invalid as base64, you are calling .split(',')[1] on it which will yield undefined - and "undefined" is not a valid base64-encoded string either.

I don't know, but I read that I need to encode my string to base64

That doesn't make much sense to me. You want to encode it somehow, only to decode it then?

What should I call and how?

Change the interface of your download function back to where it received the filename and text arguments.

Notice that the BlobBuilder does not only support appending whole strings (so you don't need to create those ArrayBuffer things), but also is deprecated in favor of the Blob constructor.

Can I put a name on my saved file?

Yes. Don't use the Blob constructor, but the File constructor.

function download(filename, text) {
    try {
        var file = new File([text], filename, {type:"text/plain"});
    } catch(e) {
        // when File constructor is not supported
        file = new Blob([text], {type:"text/plain"});
    }
    var url  = window.URL.createObjectURL(file);
    …
}

download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");

See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.

CSS last-child(-1)

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How to use zIndex in react-native

I finally solved this by creating a second object that imitates B.

My schema now looks like this:

enter image description here

I now have B1 (within parent of A) and B2 outside of it.

B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

How do I get an Excel range using row and column numbers in VSTO / C#?

If you want like Cells(Rows.Count, 1).End(xlUp).Row , you can do it.

just use the following code:

using Excel = Microsoft.Office.Interop.Excel;

string xlBk = @"D:\Test.xlsx";
Excel.Application xlApp;
Excel.Workbook xlWb;
Excel.Worksheet xlWs;

Excel.Range rng;
int iLast;

xlApp = new Excel.Application();
xlWb = xlApp.Workbooks.Open(xlBk, 0, true, 5, "", "", true, 
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1);

iLast = xlWs.Rows.Count;
rng = (Excel.Range)xlWs.Cells[iLast, 1];
iLast = rng.get_End(Excel.XlDirection.xlUp).Row;

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

Dynamically access object property using variable

ES5 // Check Deeply Nested Variables

This simple piece of code can check for deeply nested variable / value existence without having to check each variable along the way...

var getValue = function( s, context ){
    return Function.call( context || null, 'return ' + s )();
}

Ex. - a deeply nested array of objects:

a = [ 
    {
      b : [
          {
             a : 1,
             b : [
                 {
                    c : 1,
                    d : 2   // we want to check for this
                 }
             ]
           }
      ]
    } 
]

Instead of :

if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 )  // true

We can now :

if( getValue('a[0].b[0].b[0].d') == 2 ) // true

Cheers!

How to remove duplicates from a list?

The "contains" method searched for whether the list contains an entry that returns true from Customer.equals(Object o). If you have not overridden equals(Object) in Customer or one of its parents then it will only search for an existing occurrence of the same object. It may be this was what you wanted, in which case your code should work. But if you were looking for not having two objects both representing the same customer, then you need to override equals(Object) to return true when that is the case.

It is also true that using one of the implementations of Set instead of List would give you duplicate removal automatically, and faster (for anything other than very small Lists). You will still need to provide code for equals.

You should also override hashCode() when you override equals().

What is the difference between Tomcat, JBoss and Glassfish?

Tomcat is merely an HTTP server and Java servlet container. JBoss and GlassFish are full-blown Java EE application servers, including an EJB container and all the other features of that stack. On the other hand, Tomcat has a lighter memory footprint (~60-70 MB), while those Java EE servers weigh in at hundreds of megs. Tomcat is very popular for simple web applications, or applications using frameworks such as Spring that do not require a full Java EE server. Administration of a Tomcat server is arguably easier, as there are fewer moving parts.

However, for applications that do require a full Java EE stack (or at least more pieces that could easily be bolted-on to Tomcat)... JBoss and GlassFish are two of the most popular open source offerings (the third one is Apache Geronimo, upon which the free version of IBM WebSphere is built). JBoss has a larger and deeper user community, and a more mature codebase. However, JBoss lags significantly behind GlassFish in implementing the current Java EE specs. Also, for those who prefer a GUI-based admin system... GlassFish's admin console is extremely slick, whereas most administration in JBoss is done with a command-line and text editor. GlassFish comes straight from Sun/Oracle, with all the advantages that can offer. JBoss is NOT under the control of Sun/Oracle, with all the advantages THAT can offer.

How to convert a ruby hash object to JSON?

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

So, take a look here:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
#   from (irb):11
#   from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"

As you can see, requiring json has magically brought method to_json to our Hash.

Sort Dictionary by keys

Swift 5

Input your dictionary that you want to sort alphabetically by keys.

// Sort inputted dictionary with keys alphabetically.
func sortWithKeys(_ dict: [String: Any]) -> [String: Any] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [String: Any] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

dict.sorted(by: { $0.key < $1.key }) by it self returns a tuple (value, value) instead of a dictionary [value: value]. Thus, the for loop parses the tuple to return as a dictionary. That way, you put in a dictionary & get a dictionary back.

module.exports vs exports in Node.js

Basically the answer lies in what really happens when a module is required via require statement. Assuming this is the first time the module is being required.

For example:

var x = require('file1.js');

contents of file1.js:

module.exports = '123';

When the above statement is executed, a Module object is created. Its constructor function is:

function Module(id, parent) {
    this.id = id;
    this.exports = {};
    this.parent = parent;
    if (parent && parent.children) {
        parent.children.push(this);
    }

    this.filename = null;
    this.loaded = false;
    this.children = [];
}

As you see each module object has a property with name exports. This is what is eventually returned as part of require.

Next step of require is to wrap the contents of file1.js into an anonymous function like below:

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js
    module.exports = '123;
});

And this anonymous function is invoked the following way, module here refers to the Module Object created earlier.

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js
    module.exports = '123;
}) (module.exports,require, module, "path_to_file1.js","directory of the file1.js");

As we can see inside the function, exports formal argument refers to module.exports. In essence it's a convenience provided to the module programmer.

However this convenience need to be exercised with care. In any case if trying to assign a new object to exports ensure we do it this way.

exports = module.exports = {};

If we do it following way wrong way, module.exports will still be pointing to the object created as part of module instance.

exports = {};

As as result adding anything to the above exports object will have no effect to module.exports object and nothing will be exported or returned as part of require.

MongoDB distinct aggregation

You can call $setUnion on a single array, which also filters dupes:

{ $project: {Package: 1, deps: {'$setUnion': '$deps.Package'}}}

How does "cat << EOF" work in bash?

Using tee instead of cat

Not exactly as an answer to the original question, but I wanted to share this anyway: I had the need to create a config file in a directory that required root rights.

The following does not work for that case:

$ sudo cat <<EOF >/etc/somedir/foo.conf
# my config file
foo=bar
EOF

because the redirection is handled outside of the sudo context.

I ended up using this instead:

$ sudo tee <<EOF /etc/somedir/foo.conf >/dev/null
# my config file
foo=bar
EOF

How to collapse blocks of code in Eclipse?

In Preferences, you'll find General > Keys. It's for setting your keyboard shortcuts.

What I use it for more often, though, is to find stuff in Eclipse. You should see an input box labelled "type filter text." It's as close as Eclipse comes to a search feature for every Eclipse command.

What's the proper way to compare a String to an enum value?

public class Main {

    enum Vehical{
        Car,
        Bus,
        Van
    }

    public static void main(String[] args){

      String vehicalType = "CAR";

        if(vehicalType.equals(Vehical.Car.name())){
            System.out.println("The provider is Car");
        }

     String vehical_Type = "BUS";

       if(vehical_Type.equals(Vehical.Bus.toString())){
            System.out.println("The provider is Bus");
        }


    }
}

Use PHP composer to clone git repo

You can include git repository to composer.json like this:

"repositories": [
{
    "type": "package",
    "package": {
        "name": "example-package-name", //give package name to anything, must be unique
        "version": "1.0",
        "source": {
            "url": "https://github.com/example-package-name.git", //git url
            "type": "git",
            "reference": "master" //git branch-name
        }
    }
}],
"require" : {
  "example-package-name": "1.0"
}

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

Oracle: how to UPSERT (update or insert into a table?)

An alternative to MERGE (the "old fashioned way"):

begin
   insert into t (mykey, mystuff) 
      values ('X', 123);
exception
   when dup_val_on_index then
      update t 
      set    mystuff = 123 
      where  mykey = 'X';
end;   

Best way to "push" into C# array

Check out this documentation page: https://msdn.microsoft.com/en-us/library/ms132397(v=vs.110).aspx

The Add function is the first one under Methods.

href="tel:" and mobile numbers

I know the OP is asking about international country codes but for North America, you could use the following:

_x000D_
_x000D_
<a href="tel:+1-847-555-5555">1-847-555-5555</a>

<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

This might help you.

Call an overridden method from super class in typescript

If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

abstract class A {
    // The abstract method the subclass will have to call
    protected abstract doStuff():void;

    constructor(){
     alert("Super class A constructed, calling now 'doStuff'")
     this.doStuff();
    }
}

class B extends A{

    // Define here the abstract method
    protected doStuff()
    {
        alert("Submethod called");
    }
}

var b = new B();

Test it Here

And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

abstract class A {
    constructor() {
        alert("Super class A constructed, calling now 'doStuff'")
        this.doStuff();
    }

    // The fallback method the subclass will call if not overridden
    protected doStuff(): void {
        alert("Default doStuff");
    };
}

class B extends A {
    // Override doStuff()
    protected doStuff() {
        alert("Submethod called");
    }
}

class C extends A {
    // No doStuff() overriding, fallback on A.doStuff()
}

var b = new B();
var c = new C();

Try it Here

Python: How to get stdout after running os.system?

import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)

Set default value of javascript object attributes

This is actually possible to do with Object.create. It will not work for "non defined" properties. But for the ones that has been given a default value.

var defaults = {
    a: 'test1',
    b: 'test2'
};

Then when you create your properties object you do it with Object.create

properties = Object.create(defaults);

Now you will have two object where the first object is empty, but the prototype points to the defaults object. To test:

console.log('Unchanged', properties);
properties.a = 'updated';
console.log('Updated', properties);
console.log('Defaults', Object.getPrototypeOf(properties));

How to execute a raw update sql with dynamic binding in rails

Why use raw SQL for this?

If you have a model for it use where:

f1 = 'foo'
f2 = 'bar'
f3 = 'buzz'
YourModel.where('f1 = ? and f2 = ?', f1, f2).each do |ym|
  # or where(f1: f1, f2: f2).each do (...)
  ym.update(f3: f3) 
end

If you don't have a model for it (just the table), you can create a file and model that will inherit from ActiveRecord::Base

class YourTable < ActiveRecord::Base
  self.table_name = 'your_table' # specify explicitly if needed
end

and again use where the same as above:

How to get MAC address of client using PHP?

The MAC address (the low-level local network interface address) does not survive hops through IP routers. You can't find the client MAC address from a remote server.

In a local subnet, the MAC addresses are mapped to IP addresses through the ARP system. Interfaces on the local net know how to map IP addresses to MAC addresses. However, when your packets have been routed on the local subnet to (and through) the gateway out to the "real" Internet, the originating MAC address is lost. Simplistically, each subnet-to-subnet hop of your packets involve the same sort of IP-to-MAC mapping for local routing in each subnet.

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

What does "both" mean in <div style="clear:both">

Description of the possible values:

  • left: No floating elements allowed on the left side
  • right: No floating elements allowed on the right side
  • both: No floating elements allowed on either the left or the right side
  • none: Default. Allows floating elements on both sides
  • inherit: Specifies that the value of the clear property should be inherited from the parent element

Source: w3schools.com

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Automating running command on Linux from Windows using PuTTY

You can create a putty session, and auto load the script on the server, when starting the session:

putty -load "sessionName" 

At remote command, point to the remote script.

#pragma once vs include guards?

#pragma once has unfixable bugs. It should never be used.

If your #include search path is sufficiently complicated, the compiler may be unable to tell the difference between two headers with the same basename (e.g. a/foo.h and b/foo.h), so a #pragma once in one of them will suppress both. It may also be unable to tell that two different relative includes (e.g. #include "foo.h" and #include "../a/foo.h" refer to the same file, so #pragma once will fail to suppress a redundant include when it should have.

This also affects the compiler's ability to avoid rereading files with #ifndef guards, but that is just an optimization. With #ifndef guards, the compiler can safely read any file it isn't sure it has seen already; if it's wrong, it just has to do some extra work. As long as no two headers define the same guard macro, the code will compile as expected. And if two headers do define the same guard macro, the programmer can go in and change one of them.

#pragma once has no such safety net -- if the compiler is wrong about the identity of a header file, either way, the program will fail to compile. If you hit this bug, your only options are to stop using #pragma once, or to rename one of the headers. The names of headers are part of your API contract, so renaming is probably not an option.

(The short version of why this is unfixable is that neither the Unix nor the Windows filesystem API offer any mechanism that guarantees to tell you whether two absolute pathnames refer to the same file. If you are under the impression that inode numbers can be used for that, sorry, you're wrong.)

(Historical note: The only reason I didn't rip #pragma once and #import out of GCC when I had the authority to do so, ~12 years ago, was Apple's system headers relying on them. In retrospect, that shouldn't have stopped me.)

(Since this has now come up twice in the comment thread: The GCC developers did put quite a bit of effort into making #pragma once as reliable as possible; see GCC bug report 11569. However, the implementation in current versions of GCC can still fail under plausible conditions, such as build farms suffering from clock skew. I do not know what any other compiler's implementation is like, but I would not expect anyone to have done better.)

how to make UITextView height dynamic according to text length?

1 Add an observer to the content length of textfield

   yourTextView.addObserver(self, forKeyPath: "contentSize", options: (NSKeyValueObservingOptions.new), context: nil);

2 Implement observer

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let tv = object as! UITextView;
        var topCorrect = (tv.bounds.size.height - tv.contentSize.height * tv.zoomScale)/2.0;
        topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
        tv.contentOffset.x = 0;
        tv.contentOffset.y = -topCorrect;
        self.yourTextView.contentSize.height = tv.contentSize.height;
        UIView.animate(withDuration: 0.2, animations: {
            self.view.layoutIfNeeded();
        });
    }

Get the row(s) which have the max value in groups using groupby

df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

df.groupby(['sp', 'mt']).apply(lambda grp: grp.nlargest(1, 'count'))

how to check if a datareader is null or empty

First of all, you probably want to check for a DBNull not a regular Null.

Or you could look at the IsDBNull method

Form/JavaScript not working on IE 11 with error DOM7011

I had a similar problem on Internet Explorer, and got the same error number. The culprit was an HTML comment. I know it sounds unbelievable, so here is the story.

I saw a series of 6 articles on the Internet. I liked them, so I decided to download the 6 Web-Pages and store them on my Hard Drive. At the top of each page, was a couple of HTML <a> Tags, that would allow you to go to the next article or the previous article. So I changed the href attribute to point to the next folder on my Hard Drive, instead of the next URL on the Internet.

After all of the links had been re-directed, the Browser refused to display any of the Web-Pages when I clicked on the Links. The message in the Console was the Error Number that was mentioned at the top of this page.

However, the real problem was a Comment. Whenever you download a Web-Page using Google Chrome, the Chrome Browser inserts a Comment at the very top of the page that includes the URL of the location that you got the Web-Page from. After I removed the Comment at the top of each one of the 6 Pages, all of the Links worked fine ( although I continued to get the same Error Message in the Console. )

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

Access images inside public folder in laravel

You simply need to use the asset helper function in Laravel. (The url helper can also be used in this manner)

<img src="{{ asset('images/arrow.gif') }}" />

For the absolute path, you use public_path instead.

<p>Absolute path: {{ public_path('images/arrow.gif') }}</p>

If you are providing the URL to a public image from a controller (backend) you can use asset as well, or secure_asset if you want HTTPS. eg:

$url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
$secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif

return $secure_url;

Lastly, if you want to go directly to the image on a given route you can redirect to it:

return \Redirect::to($secure_url);

More Laravel helper functions can be found here

Could not open input file: artisan

After struggling with this issue, I found out that you need to find where artisan resides by running sudo find / -name artisan, and from there run the command php artisan ....

twitter bootstrap text-center when in xs mode

Bootstrap 4

<div class="col-md-9 col-xs-12 text-md-left text-center">md left, xs center</div>
<div class="col-md-9 col-xs-12 text-md-right text-center">md right, xs center</div>

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

while True:
    try:
        msg = s.recv(4096)
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep(1)
            print 'No data available'
            continue
        else:
            # a "real" error occurred
            print e
            sys.exit(1)
    else:
        # got a message, do something :)

The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n) or socket.setblocking(False). In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:

import sys
import socket
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)

while True:
    try:
        msg = s.recv(4096)
    except socket.timeout, e:
        err = e.args[0]
        # this next if/else is a bit redundant, but illustrates how the
        # timeout exception is setup
        if err == 'timed out':
            sleep(1)
            print 'recv timed out, retry later'
            continue
        else:
            print e
            sys.exit(1)
    except socket.error, e:
        # Something else happened, handle error, exit, etc.
        print e
        sys.exit(1)
    else:
        if len(msg) == 0:
            print 'orderly shutdown on server end'
            sys.exit(0)
        else:
            # got a message do something :)

As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.

See recv(2) and python socket for more details.

How to remove lines in a Matplotlib plot

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).

>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]

>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)

>>> #The object in ax is the same as the object in fig.axes[0], which is 
>>> #   a list of axes objects attached to fig 
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects

This also extends to lines in an axes object:

>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))

>>> #Lines and ax.lines contain the same line2D instances 
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]

>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)

>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

A figure containing a set of axes and a single line

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

>>> id(lines), id(ax.lines)
(212754584, 211335288)

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

>>> #THIS DOES NOTHING:
>>> lines.pop(0)

>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and two lines

>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and only the second line

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:

>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]

>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.

>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.

Check if a file exists with wildcard in shell script

Here's a solution for your specific problem that doesn't require for loops or external commands like ls, find and the like.

if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.

If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).

This could be achieved by the following function, in bash.

function doesAnyFileExist {
   local arg="$*"
   local files=($arg)
   [ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}

Going back to your example, it could be invoked like this.

if doesAnyFileExist "xorg-x11-fonts*"; then
    printf "BLAH"
fi

Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.

The second line in the function body sets the files var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.

The third line in the function body does two things:

  1. It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.

  2. If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

Strange out of memory issue while loading an image to a Bitmap object

This works for me.

Bitmap myBitmap;

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.InPurgeable = true;
options.OutHeight = 50;
options.OutWidth = 50;
options.InSampleSize = 4;

File imgFile = new File(filepath);
myBitmap = BitmapFactory.DecodeFile(imgFile.AbsolutePath, options);

and this is on C# monodroid. you can easily change the path of the image. what important here is the options to be set.

Best way to include CSS? Why use @import?

I'm going to play devil's advocate, because I hate it when people agree too much.

1. If you need a stylesheet that depends on another one, use @import. Do the optimization in a separate step.

There are two variables you're optimizing for at any given time - the performance of your code, and the performance of the developer. In many, if not a majority of cases, it's more important to make the developer more efficient, and only then make the code more performant.

If you have one stylesheet that depends on another, the most logical thing to do is to put them in two separate files and use @import. That will make the most logical sense to the next person who looks at the code.

(When would such a dependency happen? It's pretty rare, in my opinion - usually one stylesheet is enough. However, there are some logical places to put things in different CSS files:)

  • Theming: If you have different color schemes or themes for the same page, they may share some, but not all components.
  • Subcomponents: A contrived example - say you have a restaurant page that includes a menu. If the menu is very different from the rest of the page, it'll be easier to maintain if it's in its own file.

Usually stylesheets are independent, so it's reasonable to include them all using <link href>. However, if they are a dependent hierarchy, you should do the thing that makes the most logical sense to do.

Python uses import; C uses include; JavaScript has require. CSS has import; when you need it, use it!

2. Once you get to the point where the site needs to scale, concatenate all the CSS.

Multiple CSS requests of any kind - whether through links or through @imports - are bad practice for high performance web sites. Once you're at the point where optimization matters, all your CSS should be flowing through a minifier. Cssmin combines import statements; as @Brandon points out, grunt has multiple options for doing so as well. (See also this question).

Once you're at the minified stage, <link> is faster, as people have pointed out, so at most link to a few stylesheets and don't @import any if at all possible.

Before the site reaches production scale though, it's more important that the code is organized and logical, than that it goes slightly faster.

Add Insecure Registry to Docker

Anyone looking to add insecure registry on amazon linux 2: You will have to change the setting under /etc/sysconfig/docker and then restart docker daemon: here's how my /etc/sysconfig/docker looks like

# The max number of open files for the daemon itself, and all
# running containers.  The default value of 1048576 mirrors the value
# used by the systemd service unit.
DAEMON_MAXFILES=1048576

# Additional startup options for the Docker daemon, for example:
# OPTIONS="--ip-forward=true --iptables=true"
# By default we limit the number of open files per container
OPTIONS="--default-ulimit nofile=1024:4096 --insecure-registry yourinsecureregistryhostname:port"

# How many seconds the sysvinit script waits for the pidfile to appear
# when starting the daemon.
DAEMON_PIDFILE_TIMEOUT=10

Difference between spring @Controller and @RestController annotation

@Controller is used in legacy systems which use JSPs. it can return views. @RestController is to mark the controller is providing REST services with JSON response type. so it wraps @Controller and @ResponseBody annotations together.

Create Carriage Return in PHP String?

Carriage return is "\r". Mind the double quotes!

I think you want "\r\n" btw to put a line break in your text so it will be rendered correctly in different operating systems.

  • Mac: \r
  • Linux/Unix: \n
  • Windows: \r\n

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

Simple file write function in C++

Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.

Getting the base url of the website and globally passing it to twig in Symfony 2

I tried all the options here but they didnt work for me. Eventually I got it working using

{{ site.url }}

Hope this helps someone who is still struggling.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

This is my solution, may be it can helps I use IntelliJ IDE. File -> Setting -> Maven -> Importing change JDK for importer to 1.8( you can change to lower, higher)

ReactJS - Does render get called any time "setState" is called?

Even though it's stated in many of the other answers here, the component should either:

  • implement shouldComponentUpdate to render only when state or properties change

  • switch to extending a PureComponent, which already implements a shouldComponentUpdate method internally for shallow comparisons.

Here's an example that uses shouldComponentUpdate, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.

_x000D_
_x000D_
var TimeInChild = React.createClass({_x000D_
    render: function() {_x000D_
        var t = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <p>Time in child:{t}</p>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Main = React.createClass({_x000D_
    onTest: function() {_x000D_
        this.setState({'test':'me'});_x000D_
    },_x000D_
_x000D_
    shouldComponentUpdate: function(nextProps, nextState) {_x000D_
      if (this.state == null)_x000D_
        return true;_x000D_
  _x000D_
      if (this.state.test == nextState.test)_x000D_
        return false;_x000D_
        _x000D_
      return true;_x000D_
  },_x000D_
_x000D_
    render: function() {_x000D_
        var currentTime = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <div onClick={this.onTest}>_x000D_
            <p>Time in main:{currentTime}</p>_x000D_
            <p>Click me to update time</p>_x000D_
            <TimeInChild/>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(<Main/>, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_

How to connect HTML Divs with Lines?

Create a div that is the line with the code like this:

CSS

div#lineHorizontal {
    background-color: #000;
    width: //the width of the line or how far it goes sidewards;
    height: 2px;
    display: inline-block;
    margin: 0px;
 }
div#block {
    background-color: #777;
    display: inline-block;
    margin: 0px;
}

HTML

<div id="block">
</div>
<div id="lineHorizontal">
</div>
<div id="block">
</div>

This will display a block with a horizontal line to another block.

On mobile devices you could use (caniuse.com/transforms2d)

Disable webkit's spin buttons on input type="number"?

You can also hide spinner with following trick :

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  opacity:0;
  pointer-events:none;
}

laravel-5 passing variable to JavaScript

Is very easy, I use this code:

Controller:

$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));

View:

<script type="text/javascript">
    var langs = <?php echo json_decode($langs); ?>;
    console.log(langs);
</script>

hope it has been helpful, regards!

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

WebRTC is designed for high-performance, high quality communication of video, audio and arbitrary data. In other words, for apps exactly like what you describe.

WebRTC apps need a service via which they can exchange network and media metadata, a process known as signaling. However, once signaling has taken place, video/audio/data is streamed directly between clients, avoiding the performance cost of streaming via an intermediary server.

WebSocket on the other hand is designed for bi-directional communication between client and server. It is possible to stream audio and video over WebSocket (see here for example), but the technology and APIs are not inherently designed for efficient, robust streaming in the way that WebRTC is.

As other replies have said, WebSocket can be used for signaling.

I maintain a list of WebRTC resources: strongly recommend you start by looking at the 2013 Google I/O presentation about WebRTC.

Notepad++ incrementally replace


Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!

stackoverflow Find/Replace but Increment Value

A button to start php script, how?

I know this question is 5 years old, but for anybody wondering how to do this without re-rendering the main page. This solution uses the dart editor/scripting language.

You could have an <object> tag that contains a data attribute. Make the <object> 1px by 1px and then use something like dart to dynamically change the <object>'s data attribute which re-renders the data in the 1px by 1px object.

HTML Script:

<object id="external_source" type="text/html" data="" width="1px" height="1px">
</object>

<button id="button1" type="button">Start Script</button>

<script async type="application/dart" src="dartScript.dart"></script>
<script async src="packages/browser/dart.js"></script>

someScript.php:

<?php
echo 'hello world';
?>

dartScript.dart:

import 'dart:html';

InputElement button1;
ObjectElement externalSource;

void main() {
    button1 = querySelector('#button1')
        ..onClick.listen(runExternalSource);

    externalSource = querySelector('#external_source');
}

void runExternalSource(Event e) {
    externalSource.setAttribute('data', 'someScript.php');
}

So long as you aren't posting any information and you are just looking to run a script, this should work just fine.

Just build the dart script using "pub Build(generate JS)" and then upload the package onto your server.

SQL DROP TABLE foreign key constraint

Here is another way to drop all tables correctly, using sp_MSdropconstraints procedure. The shortest code I could think of:

exec sp_MSforeachtable "declare @name nvarchar(max); set @name = parsename('?', 1); exec sp_MSdropconstraints @name";
exec sp_MSforeachtable "drop table ?";

Align button to the right

Bootstrap 4 uses .float-right as opposed to .pull-right in Bootstrap 3. Also, don't forget to properly nest your rows with columns.

<div class="row">
    <div class="col-lg-12">
        <h3 class="one">Text</h3>
        <button class="btn btn-secondary float-right">Button</button>
    </div>
</div>

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

How to check empty object in angular 2 template using *ngIf

Above answers are okay. But I have found a really nice option to use following in the view:

{{previous_info?.title}}

probably duplicated question Angular2 - error if don't check if {{object.field}} exists

How to return a table from a Stored Procedure?

In SQL Server 2008 you can use

http://www.sommarskog.se/share_data.html#tableparam

or else simple and same as common execution

CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS

SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
     JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

I hopes its help to you

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

Running Python code in Vim

If you don't want to see ":exec python file.py" printed each time, use this:

nnoremap <F9> :echo system('python2 "' . expand('%') . '"')<cr>
nnoremap <F10> :echo system('python3 "' . expand('%') . '"')<cr>

It didn't mess up my powerline / vim-airline statusbar either.

CSS3 Box Shadow on Top, Left, and Right Only

The following code did it for me to make a shadow inset of the right side:

-moz-box-shadow: inset -10px 0px 10px -10px #000;
-webkit-box-shadow: inset -10px 0px 10px -10px #000;
box-shadow: inset -10px 0px 10px -10px #000;

Hope it will help!!!!

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Preventing console window from closing on Visual Studio C/C++ Console application

Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.

  1. Create a batch file. I called mine runthenpause.bat, with the following contents:

    %1 %2 %3 %4 %5 %6 %7 %8 %9
    pause
    

    The first line will run whatever command you provide and up to eight arguments. The second line will... pause.

  2. Open the project properties | Configuration properties | Debugging.

  3. Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
  4. Change "Command" to the full path to runthenpause.bat.
  5. Hit OK.

Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.

I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

How to POST a FORM from HTML to ASPX page

Hope this will help - Put this tag in html and

remove your login.aspx design content..just write only page directive

and you will get the values in aspx page after submit button click like this- protected void Page_Load(object sender, EventArgs e) {

        if (!IsPostBack)
        {
            CompleteRegistration();
        }
    }

public void CompleteRegistration() {

        NameValueCollection nv = Request.Form;
        if (nv.Count != 0)
        {
            string strname = nv["txtbox1"];
            string strPwd = nv["txtbox2"];
        }
    }

What's the difference between '$(this)' and 'this'?

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

moving committed (but not pushed) changes to a new branch after pull

  1. Checkout fresh copy of you sources

    git clone ........

  2. Make branch from desired position

    git checkout {position} git checkout -b {branch-name}

  3. Add remote repository

    git remote add shared ../{original sources location}.git

  4. Get remote sources

    git fetch shared

  5. Checkout desired branch

    git checkout {branch-name}

  6. Merge sources

    git merge shared/{original branch from shared repository}

How to delete the contents of a folder?

the easiest way to delete all files in a folder/remove all files

import os
files = os.listdir(yourFilePath)
for f in files:
    os.remove(yourFilePath + f)

How to calculate time difference in java?

I found this more cleaner.

       Date start = new Date();
        //Waiting for 10 seconds
        Thread.sleep(10000);
        Date end = new Date();
        long diff = end.getTime() - start.getTime();
        String TimeTaken = String.format("[%s] hours : [%s] mins : [%s] secs",
                Long.toString(TimeUnit.MILLISECONDS.toHours(diff)), 
                TimeUnit.MILLISECONDS.toMinutes(diff),
                TimeUnit.MILLISECONDS.toSeconds(diff));
        System.out.println(String.format("Time taken %s", TimeTaken));

Output : Time taken [0] hours : [0] mins : [10] secs

Bootstrap 4 - Inline List?

Shouldn't it be just the .list-group? See below,

<ul class="list-group">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>

Reference: Bootstrap 4 Basic Example of a List group

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Word wrap for a label in Windows Forms

This helped me in my Form called InpitWindow: In Designer for Label:

AutoSize = true;
Achors = Top, Left, Right.

private void InputWindow_Shown(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left - btOK.Margin.Right -
        lbCaption.Margin.Right - lbCaption.Margin.Left, 
        Screen.GetWorkingArea(this).Height / 2);
    this.Height = this.Height + (lbCaption.Height - btOK.Height - btCancel.Height);
    //Uncomment this line to prevent form height chage to values lower than initial height
    //this.MinimumSize = new Size(this.MinimumSize.Width, this.Height);
}
//Use this handler if you want your label change it size according to form clientsize.
private void InputWindow_ClientSizeChanged(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left * 2 - btOK.Margin.Right * 2 -
        lbCaption.Margin.Right * 2 - lbCaption.Margin.Left * 2,
        Screen.GetWorkingArea(this).Height / 2);
}

Whole code of my form

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

For boolean logic, use & and |.

np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,3), columns=list('ABC'))

>>> df
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
2  0.950088 -0.151357 -0.103219
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

>>> df.loc[(df.C > 0.25) | (df.C < -0.25)]
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

To see what is happening, you get a column of booleans for each comparison, e.g.

df.C > 0.25
0     True
1    False
2    False
3     True
4     True
Name: C, dtype: bool

When you have multiple criteria, you will get multiple columns returned. This is why the join logic is ambiguous. Using and or or treats each column separately, so you first need to reduce that column to a single boolean value. For example, to see if any value or all values in each of the columns is True.

# Any value in either column is True?
(df.C > 0.25).any() or (df.C < -0.25).any()
True

# All values in either column is True?
(df.C > 0.25).all() or (df.C < -0.25).all()
False

One convoluted way to achieve the same thing is to zip all of these columns together, and perform the appropriate logic.

>>> df[[any([a, b]) for a, b in zip(df.C > 0.25, df.C < -0.25)]]
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

For more details, refer to Boolean Indexing in the docs.

Resizing a button

try this one out resizeable button

<button type="submit me" style="height: 25px; width: 100px">submit me</button>

jQuery checkbox change and click event

Most of the answers won't catch it (presumably) if you use <label for="cbId">cb name</label>. This means when you click the label it will check the box instead of directly clicking on the checkbox. (Not exactly the question, but various search results tend to come here)

<div id="OuterDivOrBody">
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox label</label>
    <br />
    <br />
    The confirm result:
    <input type="text" id="textbox1" />
</div>

In which case you could use:

Earlier versions of jQuery:

$('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with jQuery 1.6.4

jQuery 1.7+

$('#checkbox1').on('change', function() { 
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with the latest jQuery 2.x

  • Added jsfiddle examples and the html with the clickable checkbox label

How to get a user's time zone?

You can use below code for getting current time zone

 func getCurrentTimeZone() -> String{

         return TimeZone.current.identifier

  }

  let currentTimeZone = getCurrentTimeZone()
   print(currentTimeZone)

How to use Sublime over SSH

You can try something that I've been working on called 'xeno'. It will allow you to open up files/folders in Sublime Text (or any local editor really) over an SSH connection and automatically synchronize changes to the remote machine. It should work on almost all POSIX systems (I myself use it from OS X to connect to Linux machines and edit files in Sublime Text). It's free and open source. I'd love some feedback.

For more information: it's basically a Git/SSH mashup written in Python that allows you to edit files and folders on a remote machine in a local editor. You don't have to configure kernel modules, you don't need to have a persistent connection, it's all automatic, and it won't interfere with existing source control because it uses an out-of-worktree Git repository. Also, because it's built on Git, it's extremely fast and supports automatic merging of files that might be changing on both ends, unlike SSHFS/SFTP which will just clobber any files with older timestamps.

How to avoid "Permission denied" when using pip with virtualenv

virtualenv permission problems might occur when you create the virtualenv as sudo and then operate without sudo in the virtualenv.

As found out in your question's comment, the solution here is to create the virtualenv without sudo to be able to work (esp. write) in it without sudo.

calling server side event from html button control

The easiest way to accomplish this is to override the RaisePostBackEvent method.

<input type="button" ID="btnRaisePostBack" runat="server" onclick="raisePostBack();" ... />

And in your JavaScript:

raisePostBack = function(){
    __doPostBack("<%=btnRaisePostBack.ClientID%>", "");
}

And in your code:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    if (source == btnRaisePostBack)
    {
         //do some logic
    }
}

Git: How to remove proxy

Did you already check your proxys here?

git config --global --list

or

git config --local --list

git discard all changes and pull from upstream

There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.

To be concrete, here's a simple extension of Nevik Rehnel's original answer:

git reset --hard origin/master
git pull origin master

NOTE: using git reset --hard will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.

How to delete a column from a table in MySQL

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;

Here's a working example.

Note that the COLUMN keyword is optional, as MySQL will accept just DROP IsDeleted. Also, to drop multiple columns, you have to separate them by commas and include the DROP for each one.

ALTER TABLE tbl_Country
  DROP COLUMN IsDeleted,
  DROP COLUMN CountryName;

This allows you to DROP, ADD and ALTER multiple columns on the same table in the one statement. From the MySQL reference manual:

You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.

What are good message queue options for nodejs?

Here's a couple of recommendations I can make:

node-amqp: A RabbitMQ client that I have successfully used in combination with Socket.IO to make a real-time multi-player game and chat application amongst other things. Seems reliable enough.

zeromq.node: If you want to go down the non-brokered route this might be worth a look. More work to implement functionality but your more likely to get lower latency and higher throughput.

How to read a file in reverse order?

You can also use python module file_read_backwards.

After installing it, via pip install file_read_backwards (v1.2.1), you can read the entire file backwards (line-wise) in a memory efficient manner via:

#!/usr/bin/env python2.7

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/path/to/file", encoding="utf-8") as frb:
    for l in frb:
         print l

It supports "utf-8","latin-1", and "ascii" encodings.

Support is also available for python3. Further documentation can be found at http://file-read-backwards.readthedocs.io/en/latest/readme.html

Remove blue border from css custom-styled button in Chrome

The fix for Chrome and other browsers

button:focus { outline: none !important; box-shadow: none !important; }

Postgres "psql not recognized as an internal or external command"

Find your binaries file where it is saved. get the path in terminal mine is

C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin

then find your local user data path, it is in mostly

C:\usr\local\pgsql\data

now all we have to hit the following command in the binary terminal path:

C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start

done!

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

How can I align YouTube embedded video in the center in bootstrap

You dont have to put <iframe> in a parent div at all. You can target exactly youtube iframe with CSS/3:

iframe[src*="//youtube.com/"], iframe[src*="//www.youtube.com/"] {
   display: block;
   margin: 0 auto;
}

ENOENT, no such file or directory

Another possibility is that you are missing an .npmrc file if you are pulling any packages that are not publicly available.

You will need to add an .npmrc file at the root directory and add the private/internal registry inside of the .npmrc file like this:

registry=http://private.package.source/secret/npm-packages/

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

Request format is unrecognized for URL unexpectedly ending in

Make sure you're using right method: Post/Get, right content type and right parameters (data).

$.ajax({
    type: "POST",
    url: "/ajax.asmx/GetNews",
    data: "{Lang:'tr'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) { generateNews(msg); }
})

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

display:inline vs display:block

block elements expand to fill their parent.

inline elements contract to be just big enough to hold their children.

How do I get rid of the b-prefix in a string in python?

****How to remove b' ' chars which is decoded string in python ****

import base64
a='cm9vdA=='
b=base64.b64decode(a).decode('utf-8')
print(b)

Need to navigate to a folder in command prompt

To access another drive, type the drive's letter, followed by ":".

D:

Then enter:

cd d:\windows\movie

Why doesn't the height of a container element increase if it contains floated elements?

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

Docker: How to use bash with an Alpine based docker image?

Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash:

RUN apk update && apk add bash

If youre using Alpine 3.3+ then you can just do

RUN apk add --no-cache bash

to keep docker image size small. (Thanks to comment from @sprkysnrky)

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

UPDATE  table
SET     columnx = CASE WHEN condition THEN 25 ELSE columnx END,
        columny = CASE WHEN condition THEN columny ELSE 25 END

What exactly is OAuth (Open Authorization)?

OAuth(Open Authorization) is an open standard for access granting/deligation protocol. It used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. It does not deal with authentication.

Or

OAuth 2.0 is a protocol that allows a user to grant limited access to their resources on one site, to another site, without having to expose their credentials.

  • Analogy 1: Many luxury cars today come with a valet key. It is a special key you give the parking attendant and unlike your regular key, will not allow the car to drive more than a mile or two. Some valet keys will not open the trunk, while others will block access to your onboard cell phone address book. Regardless of what restrictions the valet key imposes, the idea is very clever. You give someone limited access to your car with a special key, while using your regular key to unlock everything. src from auth0

  • Analogy 2: Assume, we want to fill an application form for a bank account. Here Oauth works as, instead of filling the form by applicant, bank can fill the form using Adhaar or passport.

    Here the following three entities are involved:

    1. Applicant i.e. Owner
    2. Bank Account is OAuth Client, they need information
    3. Adhaar/Passport ID is OAuth Provider

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

SELECT INTO USING UNION QUERY

select *
into new_table
from table_A
UNION
Select * 
From table_B

This only works if Table_A and Table_B have the same schemas

Instantiating a generic class in Java

One option is to pass in Bar.class (or whatever type you're interested in - any way of specifying the appropriate Class<T> reference) and keep that value as a field:

public class Test {
    public static void main(String[] args) throws IllegalAccessException,
            InstantiationException {
        Generic<Bar> x = new Generic<>(Bar.class);
        Bar y = x.buildOne();
    }
}

public class Generic<T> {
    private Class<T> clazz;

    public Generic(Class<T> clazz) {
        this.clazz = clazz;
    }

    public T buildOne() throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}

public class Bar {
    public Bar() {
        System.out.println("Constructing");
    }
}

Another option is to have a "factory" interface, and you pass a factory to the constructor of the generic class. That's more flexible, and you don't need to worry about the reflection exceptions.

How can I remove an entry in global configuration with git config?

Try these commands to remove all users' usernames and emails.

git config --global --unset-all user.name
git config --global --unset-all user.email

Checking oracle sid and database name

As has been mentioned above,

select global_name from global_name;

is the way to go.

You couldn't query v$database/v$instance/v$thread because your user does not have the required permissions. You can grant them (via a DBA account) with:

grant select on v$database to <username here>;

When should we use Observer and Observable?

They are parts of the Observer design pattern. Usually one or more obervers get informed about changes in one observable. It's a notifcation that "something" happened, where you as a programmer can define what "something" means.

When using this pattern, you decouple the both entities from each another - the observers become pluggable.

How do I set bold and italic on UILabel of iPhone/iPad?

@Edinator have a look on this..

myLabel.font = [UIFont boldSystemFontOfSize:16.0f]
myLabel.font = [UIFont italicSystemFontOfSize:16.0f];

use any one of the above at a time you want

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick.

The HTTP request parameter format would be like so:

Yes ?id=1,2,3
No  ?id=1&id=2&id=3

The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

Floating elements within a div, floats outside of div. Why?

Here's more modern approach:

.parent {display: flow-root;} 

No more clearfixes.

p.s. Using overflow: hidden; hides the box-shadow so...

How can I create a copy of an object in Python?

I believe the following should work with many well-behaved classed in Python:

def copy(obj):
    return type(obj)(obj)

(Of course, I am not talking here about "deep copies," which is a different story, and which may be not a very clear concept -- how deep is deep enough?)

According to my tests with Python 3, for immutable objects, like tuples or strings, it returns the same object (because there is no need to make a shallow copy of an immutable object), but for lists or dictionaries it creates an independent shallow copy.

Of course this method only works for classes whose constructors behave accordingly. Possible use cases: making a shallow copy of a standard Python container class.

cannot redeclare block scoped variable (typescript)

Regarding the error itself, let is used to declare local variables that exist in block scopes instead of function scopes. It's also more strict than var, so you can't do stuff like this:

if (condition) {
    let a = 1;
    ...
    let a = 2;
}

Also note that case clauses inside switch blocks don't create their own block scopes, so you can't redeclare the same local variable across multiple cases without using {} to create a block each.


As for the import, you are probably getting this error because TypeScript doesn't recognize your files as actual modules, and seemingly model-level definitions end up being global definitions for it.

Try importing an external module the standard ES6 way, which contains no explicit assignment, and should make TypeScript recognize your files correctly as modules:

import * as co from "./co"

This will still result in a compile error if you have something named co already, as expected. For example, this is going to be an error:

import * as co from "./co"; // Error: import definition conflicts with local definition
let co = 1;

If you are getting an error "cannot find module co"...

TypeScript is running full type-checking against modules, so if you don't have TS definitions for the module you are trying to import (e.g. because it's a JS module without definition files), you can declare your module in a .d.ts definition file that doesn't contain module-level exports:

declare module "co" {
    declare var co: any;
    export = co;
}

How to search a Git repository by commit message?

To search the commit log (across all branches) for the given text:

git log --all --grep='Build 0051'

To search the actual content of commits through a repo's history, use:

git grep 'Build 0051' $(git rev-list --all)

to show all instances of the given text, the containing file name, and the commit sha1.

Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the -g flag (short for --walk-reflogs:

git log -g --grep='Build 0051'

EDIT: if you seem to have lost your history, check the reflog as your safety net. Look for Build 0051 in one of the commits listed by

git reflog

You may have simply set your HEAD to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.

To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)

git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
# git checkout HEAD@{10}
git checkout -b build_0051 # make a new branch with the build_0051 as the tip

Table row and column number in jQuery

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

$('td').click(function(){
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  alert('Row: ' + row + ', Column: ' + col);
});

Check a running example here.

Scroll back to the top of scrollable div

scrollTo

window.scrollTo(0, 0);

is the ultimate solution for scrolling the windows to the top - the best part is that it does not require any id selector and even if we use the IFRAME structure it will work extremely well.

The scrollTo() method scrolls the document to the specified coordinates.
window.scrollTo(xpos, ypos);
xpos Number Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
ypos Number Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

jQuery

Another option to do the same is using jQuery and it will give a smoother look for the same

$('html,body').animate({scrollTop: 0}, 100);

where 0 after the scrollTop specifies the vertical scrollbar position in the pixel and second parameter is an optional parameter which shows the time in microseconds to complete the task.

How to sign an android apk file

I ran into this problem and was solved by checking the min sdk version in the manifest. It was set to 15 (ICS), but my phone was running 10(Gingerbread)

Passing a variable from node.js to html

With Node and HTML alone you won't be able to achieve what you intend to; it's not like using PHP, where you could do something like <title> <?php echo $custom_title; ?>, without any other stuff installed.

To do what you want using Node, you can either use something that's called a 'templating' engine (like Jade, check this out) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.

Both require some extra work; it's not as plug'n'play as PHP when it comes to doing stuff like you want.

How to sort a list of strings?

But how does this handle language specific sorting rules? Does it take locale into account?

No, list.sort() is a generic sorting function. If you want to sort according to the Unicode rules, you'll have to define a custom sort key function. You can try using the pyuca module, but I don't know how complete it is.

How exactly does __attribute__((constructor)) work?

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
   printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this

Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

OR

Thanks @Tomáš Hubálek

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

Error in MySQL when setting default value for DATE or DATETIME

Option combinations for mysql Ver 14.14 Distrib 5.7.18, for Linux (x86_64).

Doesn't throw:

STRICT_TRANS_TABLES + NO_ZERO_DATE

Throws:

STRICT_TRANS_TABLES + NO_ZERO_IN_DATE

My settings in /etc/mysql/my.cnf on Ubuntu:

[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Check whether IIS is installed or not?

Check

Control Panel --> Administrative Tools --> Services --> IIS Admin

For reinstalling

How to remove and reinstall IIS 5.0, 5.1 and 6.0

How does OkHttp get Json string?

I hope you managed to obtain the json data from the json string.

Well I think this will be of help

try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(urls[0])
    .build();
Response responses = null;

try {
    responses = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}   

String jsonData = responses.body().string();

JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");

//define the strings that will temporary store the data
String fname,lname;

//get the length of the json array
int limit = Jarray.length()

//datastore array of size limit
String dataStore[] = new String[limit];

for (int i = 0; i < limit; i++) {
    JSONObject object     = Jarray.getJSONObject(i);

    fname = object.getString("firstName");
    lname = object.getString("lastName");

    Log.d("JSON DATA", fname + " ## " + lname);

    //store the data into the array
    dataStore[i] = fname + " ## " + lname;
}

//prove that the data was stored in the array      
 for (String content ; dataStore ) {
        Log.d("ARRAY CONTENT", content);
    }

Remember to use AsyncTask or SyncAdapter(IntentService), to prevent getting a NetworkOnMainThreadException

Also import the okhttp library in your build.gradle

compile 'com.squareup.okhttp:okhttp:2.4.0'

Get single listView SelectedItem

foreach (ListViewItem itemRow in taskShowListView.Items)
{
    if (itemRow.Items[0].Checked == true)
    {
        int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

        string taskDate = itemRow.SubItems[1].ToString();
        string taskDescription = itemRow.SubItems[2].ToString();            
    }
}

Get connection string from App.config

//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}

Twitter Bootstrap: Print content of modal window

I was facing two issues Issue 1: all fields were coming one after other and Issue 2 white space at the bottom of the page when used to print from popup.

I Resolved this by

making display none to all body * elements most of them go for visibility hidden which creates space so avoid visibility hidden

    @media print {
        body * {
           display:none;
        width:auto;
        height:auto;
        margin:0px;padding:0px; 
        }
        #printSection, #printSection * {
            display:inline-block!important;
        }
        #printSection {
            position:absolute;
            left:0;
            top:0;  
            margin:0px; 
            page-break-before: none;
            page-break-after: none;
            page-break-inside: avoid;      
        }
#printSection .form-group{

      width:100%!important;
      float:left!important;
      page-break-after: avoid;
    }
#printSection label{
        float:left!important;
        width:200px!important;
        display:inline-block!important;
      }

#printSection .form-control.search-input{
        float:left!important;
        width:200px!important;
        display: inline-block!important;
      }
}

SQL update query using joins

You can use the following query:

UPDATE im
SET mf_item_number = (some value) 
FROM item_master im
JOIN group_master gm
    ON im.sku = gm.sku 
JOIN Manufacturer_Master mm
    ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
      gm.manufacturerID = 34    `sql`