Programs & Examples On #Kohana auth

The Kohana Auth module provides an easy-to-use API for basic website authentication (users) and authorization (roles)

Making authenticated POST requests with Spring RestTemplate for Android

Slightly different approach:

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);

restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);

How can I get System variable value in Java?

To clarify, system variables are the same as environment variables. User environment variables are set per user and are different whenever a different user logs in. System wide environment variables are the same no matter what user logs on.

To access either the current value of a system wide variable or a user variable in Java, see below:

String javaHome = System.getenv("JAVA_HOME");

For more information on environment variables see this wikipedia page.

Also make sure the environment variable you are trying to read is properly set before invoking Java by doing a:

echo %MYENVVAR%

You should see the value of the environment variable. If not, you may need to reopen the shell (DOS) or log off and log back on.

Generate random number between two numbers in JavaScript

I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:

function random(n, b = 0) {
    return Math.random() * (b-n) + n;
}

Push origin master error on new repository

To actually resolve the issue I used the following command to stage all my files to the commit.

$ git add .
$ git commit -m 'Your message here'
$ git push origin master

The problem I had was that the -u command in git add didn't actually add the new files and the git add -A command wasn't supported on my installation of git. Thus as mentioned in this thread the commit I was trying to stage was empty.

How do I share a global variable between c files?

In the second .c file use extern keyword with the same variable name.

Does JavaScript guarantee object property order?

Just found this out the hard way.

Using React with Redux, the state container of which's keys I want to traverse in order to generate children is refreshed everytime the store is changed (as per Redux's immutability concepts).

Thus, in order to take Object.keys(valueFromStore) I used Object.keys(valueFromStore).sort(), so that I at least now have an alphabetical order for the keys.

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When I encountered this exception, I solved this by using Run Configurations... panel as picture shows below.Especially, at JRE tab, the VM Arguments are the critical
( "-Xmx1024m -Xms512m -XX:MaxPermSize=1024m -XX:PermSize=512m" ).

enter image description here

LaTeX package for syntax highlighting of code in various languages

I recommend Pygments. It accepts a piece of code in any language and outputs syntax highlighted LaTeX code. It uses fancyvrb and color packages to produce its output. I personally prefer it to the listing package. I think fancyvrb creates much prettier results.

Copying HTML code in Google Chrome's inspect element

This is bit tricky

Now a days most of website new techniques to save websites from scraping

1st Technique

Ctrl+U this will show you Page Source enter image description here

2nd Technique

This one is small hack if the website has ajax like functionality.

Just Hover the mouse key on inspect element untill whole screen becomes just right click then and copy element enter image description here

That's it you are good to go.

How to write character & in android strings.xml

Even your question is answered, still i want tell more entities same like this. These are html entities, so in android you will write them like:

Replace below with:

& with &amp;
> with &gt;
< with &lt;
" with &quot;, &ldquo; or &rdquo;
' with &apos;, &lsquo; or &rsquo;
} with &#125;

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

How can I trigger the click event of another element in ng-click using angularjs?

Simply have them in the same controller, and do something like this:

HTML:

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="startUpload()">Upload</button>

JS:

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.files = [];
  $scope.startUpload = function(){
    for (var i = 0; i < $scope.files.length; i++) {
      $upload($scope.files[i]);
    } 
  }
  $scope.onFileSelect = function($files) {
     $scope.files = $files;
  };
}];

This is, in my opinion, the best way to do it in angular. Using jQuery to find the element and trigger an event isn't the best practice.

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

Bootstrap: align input with button

I was also struggling with same issue. The bootstrap classes I use are not working for me. I came up with an workaround, as below:

<form action='...' method='POST' class='form-group'>
  <div class="form-horizontal">
    <input type="text" name="..." 
        class="form-control" 
        placeholder="Search People..."
        style="width:280px;max-width:280px;display:inline-block"/>

    <button type="submit" 
        class="btn btn-primary" 
        style="margin-left:-8px;margin-top:-2px;min-height:36px;">
      <i class="glyphicon glyphicon-search"></i>
     </button>
  </div>
</form>

Basically, I overrode the display property of class "form-control", and used other style properties for correcting the size and position.

Following is the result:

enter image description here

Remove all HTMLtags in a string (with the jquery text() function)

I found in my specific case that I just needed to trim the content. Maybe not the answer asked in the question. But I thought I should add this answer anyway.

$(myContent).text().trim()

to_string is not a member of std, says g++ (mingw)

to_string() is only present in c++11 so if c++ version is less use some alternate methods such as sprintf or ostringstream

DataGridView changing cell background color

You can use the VisibleChanged event handler.

private void DataGridView1_VisibleChanged(object sender, System.EventArgs e)
{
    var grid = sender as DataGridView;
    grid.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}

What's the difference between OpenID and OAuth?

OpenID and OAuth are each HTTP-based protocols for authentication and/or authorization. Both are intended to allow users to perform actions without giving authentication credentials or blanket permissions to clients or third parties. While they are similar, and there are proposed standards to use them both together, they are separate protocols.

OpenID is intended for federated authentication. A client accepts an identity assertion from any provider (although clients are free to whitelist or blacklist providers).

OAuth is intended for delegated authorization. A client registers with a provider, which provides authorization tokens which it will accept to perform actions on the user's behalf.

OAuth is currently better suited for authorization, because further interactions after authentication are built into the protocol, but both protocols are evolving. OpenID and its extensions could be used for authorization, and OAuth can be used for authentication, which can be thought of as a no-op authorization.

How can I set the color of a selected row in DataGrid

I've tried ControlBrushKey but it didn't work for unselected rows. The background for the unselected row was still white. But I've managed to find out that I have to override the rowstyle.

<DataGrid x:Name="pbSelectionDataGrid" Height="201" Margin="10,0"
          FontSize="20" SelectionMode="Single" FontWeight="Bold">
    <DataGrid.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FFFDD47C"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#FFA6E09C"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Violet"/>
    </DataGrid.Resources>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="LightBlue" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

How do I make the method return type generic?

As you said passing a class would be OK, you could write this:

public <T extends Animal> T callFriend(String name, Class<T> clazz) {
   return (T) friends.get(name);
}

And then use it like this:

jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();

Not perfect, but this is pretty much as far as you get with Java generics. There is a way to implement Typesafe Heterogenous Containers (THC) using Super Type Tokens, but that has its own problems again.

How can I add "href" attribute to a link dynamically using JavaScript?

More actual solution:

<a id="someId">Link</a>

const a = document.querySelector('#someId');
a.href = 'url';

Is it possible to have placeholders in strings.xml for runtime values?

Was looking for the same and finally found the following very simple solution. Best: it works out of the box.
1. alter your string ressource:

<string name="welcome_messages">Hello, <xliff:g name="name">%s</xliff:g>! You have 
<xliff:g name="count">%d</xliff:g> new messages.</string>

2. use string substitution:

c.getString(R.string.welcome_messages,name,count);

where c is the Context, name is a string variable and count your int variable

You'll need to include

<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">

in your res/strings.xml. Works for me. :)

Convert pandas dataframe to NumPy array

It seems like df.to_records() will work for you. The exact feature you're looking for was requested and to_records pointed to as an alternative.

I tried this out locally using your example, and that call yields something very similar to the output you were looking for:

rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)],
      dtype=[(u'ID', '<i8'), (u'A', '<f8'), (u'B', '<f8'), (u'C', '<f8')])

Note that this is a recarray rather than an array. You could move the result in to regular numpy array by calling its constructor as np.array(df.to_records()).

Get value when selected ng-option changes

I may be late for this but I had somewhat the same problem.

I needed to pass both the id and the name into my model but all the orthodox solutions had me make code on the controller to handle the change.

I macgyvered my way out of it using a filter.

<select 
        ng-model="selected_id" 
        ng-options="o.id as o.name for o in options" 
        ng-change="selected_name=(options|filter:{id:selected_id})[0].name">
</select>
<script>
  angular.module("app",[])
  .controller("ctrl",['$scope',function($scope){
    $scope.options = [
      {id:1, name:'Starbuck'},
      {id:2, name:'Appolo'},
      {id:3, name:'Saul Tigh'},
      {id:4, name:'Adama'}
    ]
  }])
</script>

The "trick" is here:

ng-change="selected_name=(options|filter:{id:selected_id})[0].name"

I'm using the built-in filter to retrieve the correct name for the id

Here's a plunkr with a working demo.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

You need to change the Solution Platform from "Any CPU" to "x86" or "x64" based on the bitness of office installation.

The steps are given below:

  1. Right click on the Solution File in Solution Explorer: enter image description here

    1. Click on the Configuration Manager.
    2. Click on the Active Platform Drop down, if x86 is already there then select that, else click on New. enter image description here

    3. Select x86 or x64 from the new platform dropdown: enter image description here

Compile and run your application.

How to create an empty file with Ansible?

The documentation of the file module says

If state=file, the file will NOT be created if it does not exist, see the copy or template module if you want that behavior.

So we use the copy module, using force=no to create a new empty file only when the file does not yet exist (if the file exists, its content is preserved).

- name: ensure file exists
  copy:
    content: ""
    dest: /etc/nologin
    force: no
    group: sys
    owner: root
    mode: 0555

This is a declarative and elegant solution.

Auto margins don't center image in page

You can center auto width div using display:table;

div{
margin: 0px auto;
float: none;
display: table;
}

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

Get an element by index in jQuery

You could skip the jquery and just use CSS style tagging:

 <ul>
 <li>India</li>
 <li>Indonesia</li>
 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>
 </ul>

How to completely DISABLE any MOUSE CLICK

something like:

    $('#doc').click(function(e){
       e.preventDefault()
       e.stopImmediatePropagation() //charles ma is right about that, but stopPropagation isn't also needed
});

should do the job you could also bind more mouse events with replacing for: edit: add this in the feezing part

    $('#doc').bind('click mousedown dblclick',function(e){
       e.preventDefault()
       e.stopImmediatePropagation()
});

and this in the unfreezing:

  $('#doc').unbind();

Creating instance list of different objects

List anyObject = new ArrayList();

or

List<Object> anyObject = new ArrayList<Object>();

now anyObject can hold objects of any type.

use instanceof to know what kind of object it is.

Radio/checkbox alignment in HTML/CSS

I found the best fix for this was to give the input a height that matches the label. At least this fixed my problem with inconsistencies in Firefox and IE.

input { height: 18px; margin: 0; float: left; }
label { height: 18px; float: left; }

<li>
  <input id="option1" type="radio" name="opt" />
  <label for="option1">Option 1</label>
</li>

Java Compare Two List's object values?

Logic should be something like:

  1. First step: For class MyData implements Comparable interface, override the compareTo method as per the per object requirement.

  2. Second step: When it comes to list comparison (after checking for nulls), 2.1 Check the size of both lists, if equal returns true else return false, continue to object iteration 2.2 If step 2.1 returns true, iterate over elements from both lists and invoke something like,

    listA.get(i).compareTo(listB.get(i))

This will be as per the code mentioned in step-1.

package javax.servlet.http does not exist

On *nix, try:

javac -cp $CLASSPATH:$CATALINA_HOME/lib/servlet-api.jar Filename.java

Or on Windows, try:

javac -cp %CLASSPATH%;%CATALINA_HOME%\lib\servlet-api.jar Filename.java

Setting Column width in Apache POI

I answered my problem with a default width for all columns and cells, like below:

int width = 15; // Where width is number of caracters 
sheet.setDefaultColumnWidth(width);

How do you attach and detach from Docker's process?

I'm on a Mac, and for some reason, Ctrl-p Ctrl-q would only work if I also held Shift

How do I disable fail_on_empty_beans in Jackson?

If you use org.codehaus.jackson.map.ObjectMapper, then pls. use the following lines

mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

apache ProxyPass: how to preserve original IP address

If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.

Set the space between Elements in Row Flutter

I believe the original post was about removing the space between the buttons in a row, not adding space.

The trick is that the minimum space between the buttons was due to padding built into the buttons as part of the material design specification.

So, don't use buttons! But a GestureDetector instead. This widget type give the onClick / onTap functionality but without the styling.

See this post for an example.

https://stackoverflow.com/a/56001817/766115

What is the string length of a GUID?

It depends on how you format the Guid:

  • Guid.NewGuid().ToString() => 36 characters (Hyphenated)
    outputs: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("D") => 36 characters (Hyphenated, same as ToString())
    outputs: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("N") => 32 characters (Digits only)
    outputs: 12345678123412341234123456789abc

  • Guid.NewGuid().ToString("B") => 38 characters (Braces)
    outputs: {12345678-1234-1234-1234-123456789abc}

  • Guid.NewGuid().ToString("P") => 38 characters (Parentheses)
    outputs: (12345678-1234-1234-1234-123456789abc)

  • Guid.NewGuid().ToString("X") => 68 characters (Hexadecimal)
    outputs: {0x12345678,0x1234,0x1234,{0x12,0x34,0x12,0x34,0x56,0x78,0x9a,0xbc}}

How to split a data frame?

You could also use

data2 <- data[data$sum_points == 2500, ]

This will make a dataframe with the values where sum_points = 2500

It gives :

airfoils sum_points field_points   init_t contour_t   field_t
...
491        5       2500         5625 0.000086  0.004272  6.321774
498        5       2500         5625 0.000087  0.004507  6.325083
504        5       2500         5625 0.000088  0.004370  6.336034
603        5        250        10000 0.000072  0.000525  1.111278
577        5        250        10000 0.000104  0.000559  1.111431
587        5        250        10000 0.000072  0.000528  1.111524
606        5        250        10000 0.000079  0.000538  1.111685
....
> data2 <- data[data$sum_points == 2500, ]
> data2
airfoils sum_points field_points   init_t contour_t   field_t
108        5       2500          625 0.000082  0.004329  0.733109
106        5       2500          625 0.000102  0.004564  0.733243
117        5       2500          625 0.000087  0.004321  0.733274
112        5       2500          625 0.000081  0.004428  0.733587

Should import statements always be at the top of a module?

Readability

In addition to startup performance, there is a readability argument to be made for localizing import statements. For example take python line numbers 1283 through 1296 in my current first python project:

listdata.append(['tk font version', font_version])
listdata.append(['Gtk version', str(Gtk.get_major_version())+"."+
                 str(Gtk.get_minor_version())+"."+
                 str(Gtk.get_micro_version())])

import xml.etree.ElementTree as ET

xmltree = ET.parse('/usr/share/gnome/gnome-version.xml')
xmlroot = xmltree.getroot()
result = []
for child in xmlroot:
    result.append(child.text)
listdata.append(['Gnome version', result[0]+"."+result[1]+"."+
                 result[2]+" "+result[3]])

If the import statement was at the top of file I would have to scroll up a long way, or press Home, to find out what ET was. Then I would have to navigate back to line 1283 to continue reading code.

Indeed even if the import statement was at the top of the function (or class) as many would place it, paging up and back down would be required.

Displaying the Gnome version number will rarely be done so the import at top of file introduces unnecessary startup lag.

Custom checkbox image android

If you use androidx.appcompat:appcompat and want a custom drawable (of type selector with android:state_checked) to work on old platform versions in addition to new platform versions, you need to use

    <CheckBox
        app:buttonCompat="@drawable/..."

instead of

    <CheckBox
        android:button="@drawable/..."

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Use AsNoTracking() where you are getting your query.

  var result = dbcontext.YourModel.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();

Mercurial undo last commit

Its workaround.

If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

C# go to next item in list based on if statement in foreach

Try this:

foreach (Item item in myItemsList)
{
  if (SkipCondition) continue;
  // More stuff here
}

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

You are not allowed to have a CNAME record for the domain, as the CNAME is an aliasing feature that covers all data types (regardless of whether the client looks for MX, NS or SOA records). CNAMEs also always refer to a new name, not an ip-address, so there are actually two errors in the single line

@                        IN CNAME   88.198.38.XXX

Changing that CNAME to an A record should make it work, provided the ip-address you use is the correct one for your Heroku app.

The only correct way in DNS to make a simple domain.com name work in the browser, is to point the domain to an IP-adress with an A record.

What is the point of WORKDIR on Dockerfile?

You dont have to

RUN mkdir -p /usr/src/app

This will be created automatically when you specifiy your WORKDIR

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ] 

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

Linux command to print directory structure in the form of a tree

Since it was a successful comment, I am adding it as an answer:
with files:

 find . | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/" 

Changing the interval of SetInterval while it's running

A much simpler way would be to have an if statement in the refreshed function and a control to execute your command at regular time intervals . In the following example, I run an alert every 2 seconds and the interval (intrv) can be changed dynamically...

var i=1;
var intrv=2; // << control this variable

var refreshId = setInterval(function() {
  if(!(i%intrv)) {
    alert('run!');
  }
  i++;
}, 1000);

Get random item from array

echo $items[array_rand($items)];

array_rand()

What is the difference between private and protected members of C++ classes?

  • Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule.

  • Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.

Counter increment in Bash loop not working

Source script has some problem with subshell. First example, you probably do not need subshell. But We don't know what is hidden under "Some more action". The most popular answer has hidden bug, that will increase I/O, and won't work with subshell, because it restores couter inside loop.

Do not fortot add '\' sign, it will inform bash interpreter about line continuation. I hope it will help you or anybody. But in my opinion this script should be fully converted to AWK script, or else rewritten to python using regexp, or perl, but perl popularity over years is degraded. Better do it with python.

Corrected Version without subshell:

#!/bin/bash
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
#(  #unneeded bracket
while read WFY_URL
do
    echo $WFY_URL #Some more action
    COUNTER=$((COUNTER+1))
done
# ) unneeded bracket

echo $COUNTER # output = 0

Version with subshell if it is really needed

#!/bin/bash

TEMPFILE=/tmp/$$.tmp  #I've got it from the most popular answer
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
(
while read WFY_URL
do
    echo $WFY_URL #Some more action
    COUNTER=$((COUNTER+1))
done
echo $COUNTER > $TEMPFILE  #store counter only once, do it after loop, you will save I/O
)

COUNTER=$(cat $TEMPFILE)  #restore counter
unlink $TEMPFILE
echo $COUNTER # output = 0

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Windows recursive grep command-line

findstr can do recursive searches (/S) and supports some variant of regex syntax (/R).

C:\>findstr /?
Searches for strings in files.

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]

  /B         Matches pattern if at the beginning of a line.
  /E         Matches pattern if at the end of a line.
  /L         Uses search strings literally.
  /R         Uses search strings as regular expressions.
  /S         Searches for matching files in the current directory and all
             subdirectories.
  /I         Specifies that the search is not to be case-sensitive.
  /X         Prints lines that match exactly.
  /V         Prints only lines that do not contain a match.
  /N         Prints the line number before each line that matches.
  /M         Prints only the filename if a file contains a match.
  /O         Prints character offset before each matching line.
  /P         Skip files with non-printable characters.
  /OFF[LINE] Do not skip files with offline attribute set.
  /A:attr    Specifies color attribute with two hex digits. See "color /?"
  /F:file    Reads file list from the specified file(/ stands for console).
  /C:string  Uses specified string as a literal search string.
  /G:file    Gets search strings from the specified file(/ stands for console).
  /D:dir     Search a semicolon delimited list of directories
  strings    Text to be searched for.
  [drive:][path]filename
             Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C.  For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y.  'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurrences of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

For full information on FINDSTR regular expressions refer to the online Command
Reference.

How to convert date format to milliseconds?

You could use

Calendar cal = Calendar.getInstance();
cal.setTime(beginupd);
long millis = cal.getTimeInMillis();

What is the question mark for in a Typescript parameter name

This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

Open Sublime Text from Terminal in macOS

In OS X Mavericks running Sublime Text 2 the following worked for me.

sudo ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/bin/subl

Its handy to locate the file in the finder and drag and drop that into the terminal window so you can be sure the path is the correct one, I'm not a huge terminal user so this was more comfortable for me. then you can go to the start of the path and start adding in the other parts like the shorthand UNIX commands. Hope this helps

Rails: FATAL - Peer authentication failed for user (PG::Error)

For permanent solution:

The problem is with your pg_hba. This line:

local   all             postgres                                peer

Should be

local   all             postgres                                md5

Then restart your postgresql server after changing this file.

If you're on Linux, command would be

sudo service postgresql restart

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Tomcat is not running even though JAVA_HOME path is correct

Remove the 'bin' from JAVA_HOME. That solves the issue.

How to write into a file in PHP?

fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead. Article

file_put_contents(file,data,mode,context):

The file_put_contents writes a string to a file.

This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.

fwrite(file,string,length):

The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length, whichever comes first.This function returns the number of bytes written or FALSE on failure.

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

I'd try to declare i outside of the loop!

Good luck on solving 3n+1 :-)

Here's an example:

#include <stdio.h>

int main() {

   int i;

   /* for loop execution */
   for (i = 10; i < 20; i++) {
       printf("i: %d\n", i);
   }   

   return 0;
}

Read more on for loops in C here.

Hidden Features of C#?

I found that only few developers know about this feature.

If you need a method that works with a value-type variable via some interface (implemented by this value type), it's easy to avoid boxing during the method call.

Example code:

using System;
using System.Collections;

interface IFoo {
    void Foo();
}
struct MyStructure : IFoo {
    public void Foo() {
    }
}
public static class Program {
    static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo {
        t.Foo();
    }
    static void Main(string[] args) {
        MyStructure s = new MyStructure();
        MethodThatDoesNotBoxArguments(s);
    }
}

IL code doesn't contain any box instructions:

.method private hidebysig static void  MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed
{
  // Code size       14 (0xe)
  .maxstack  8
  IL_0000:  ldarga.s   t
  IL_0002:  constrained. !!T
  IL_0008:  callvirt   instance void IFoo::Foo()
  IL_000d:  ret
} // end of method Program::MethodDoesNotBoxArguments

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] valuetype MyStructure s)
  IL_0000:  ldloca.s   s
  IL_0002:  initobj    MyStructure
  IL_0008:  ldloc.0
  IL_0009:  call       void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0)
  IL_000e:  ret
} // end of method Program::Main

See Richter, J. CLR via C#, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.

See also my answer to another question.

Get environment variable value in Dockerfile

So you can do: cat Dockerfile | envsubst | docker build -t my-target -

Then have a Dockerfile with something like:

ENV MY_ENV_VAR $MY_ENV_VAR

I guess there might be a problem with some special characters, but this works for most cases at least.

How to restart a rails server on Heroku?

If you have several heroku apps, you must type heroku restart --app app_name or heroku restart -a app_name

How to autowire RestTemplate using annotations

@Autowired
private RestOperations restTemplate;

You can only autowire interfaces with implementations.

How to run Tensorflow on CPU

You can also set the environment variable to

CUDA_VISIBLE_DEVICES=""

without having to modify the source code.

Extension mysqli is missing, phpmyadmin doesn't work

For the record, my system is Ubuntu Server 20.04 and none of the solutions here worked. For me, I installed PHP 7.4 and I had to edit enter code here/etc/php/7.4/apache2/php.ini`.

Within this, search for ;extension=mysqli, uncomment and change mysqli to mysqlnd so it should look like this extension=mysqlnd. I tried using mysqli but I faced the same error as if I didn't enable it but mysqlnd worked for me.

How can I use pointers in Java?

Java reference types are not the same as C pointers as you can't have a pointer to a pointer in Java.

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

Converting byte array to String (Java)

public static String readFile(String fn)   throws IOException 
{
    File f = new File(fn);

    byte[] buffer = new byte[(int)f.length()];
    FileInputStream is = new FileInputStream(fn);
    is.read(buffer);
    is.close();

    return  new String(buffer, "UTF-8"); // use desired encoding
}

Proper way to wait for one function to finish before continuing?

Use async/await :

async function firstFunction(){
  for(i=0;i<x;i++){
    // do something
  }
  return;
};

then use await in your other function to wait for it to return:

async function secondFunction(){
  await firstFunction();
  // now wait for firstFunction to finish...
  // do something else
};

Convert any object to a byte[]

Alternative way to convert object to byte array:

TypeConverter objConverter = TypeDescriptor.GetConverter(objMsg.GetType());
byte[] data = (byte[])objConverter.ConvertTo(objMsg, typeof(byte[]));

Android basics: running code in the UI thread

As of Android P you can use getMainExecutor():

getMainExecutor().execute(new Runnable() {
  @Override public void run() {
    // Code will run on the main thread
  }
});

From the Android developer docs:

Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

From the CommonsBlog:

You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.

Finding element in XDocument?

The Elements() method returns an IEnumerable<XElement> containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:

var query = from c in xmlFile.Root.Elements("Band")
            select c;

jQuery make global variable

set the variable on window:

window.a_href = a_href;

Java 8 Stream API to find Unique Object matching a property value

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.

jquery disable form submit on enter

I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!

$j(':input:not(textarea)').keydown(function(event){
    var kc = event.witch || event.keyCode;
    if(kc == 13){
    event.preventDefault();
        $j(this).closest('form').attr('data-oldaction', function(){
            return $(this).attr('action');
        }).attr('action', 'javascript:;');

        alert('some_text_if_you_want');

        $j(this).closest('form').attr('action', function(){
            return $(this).attr('data-oldaction');
        });
        return false;
    }
});

Batch - If, ElseIf, Else

batchfiles perform simple string substitution with variables. so, a simple

goto :language%language%
echo notfound
...

does this without any need for if.

Angular 2: Passing Data to Routes?

You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.

The old router allows to pass data but the new (RC.1) router doesn't yet.

Update

data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?

Angular 2 router no base href set

Since 2.0 beta :)

import { APP_BASE_HREF } from 'angular2/platform/common';

How do I find all of the symlinks in a directory tree?

What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

you could make one lsl ls -lR | grep ^l

Just chmod them +x and you are good to go.

Get exit code for command in bash/ksh

Try

safeRunCommand() {
   "$@"

   if [ $? != 0 ]; then
      printf "Error when executing command: '$1'"
      exit $ERROR_CODE
   fi
}

xcode-select active developer directory error

I was having the same problem in high sierra. running the following command solved it

npm explore npm -g -- npm install node-gyp@latest

Integrating the ZXing library directly into my Android application

Having issues building with ANT? Keep reading

If ant -f core/build.xml says something like:

Unable to locate tools.jar. Expected to find it in
C:\Program Files\Java\jre6\lib\tools.jar

then set your JAVA_HOME environment variable to the proper java folder. I found tools.jar in my (for Windows):

C:\Program Files\Java\jdk1.6.0_21\lib

so I set my JAVA_HOME to:

C:\Progra~1\Java\jdk1.6.0_25

the reason for the shorter syntax I found at some site which says:

"It is strongly advised that you choose an installation directory that does not include spaces in the path name (e.g., do NOT install in C:\Program Files). If Java is installed in such a directory, it is critical to set the JAVA_HOME environment variable to a path that does not include spaces (e.g., C:\Progra~1); failure to do this will result in exceptions thrown by some programs that depend on the value of JAVA_HOME."

I then relaunched cmd (important because DOS shell only reads env vars upon launching, so changing an env var will require you to use a new shell to get the updated value)

and finally the ant -f core/build.xml worked.

How to install pip in CentOS 7?

The CentOS 7 yum package for python34 does include the ensurepip module, but for some reason is missing the setuptools and pip files that should be a part of that module. To fix, download the latest wheels from PyPI into the module's _bundled directory (/lib64/python3.4/ensurepip/_bundled/):

setuptools-18.4-py2.py3-none-any.whl
pip-7.1.2-py2.py3-none-any.whl

then edit __init__.py to match the downloaded versions:

_SETUPTOOLS_VERSION = "18.4"
_PIP_VERSION = "7.1.2"

after which python3.4 -m ensurepip works as intended. Ensurepip is invoked automatically every time you create a virtual environment, for example:

pyvenv-3.4 py3
source py3/bin/activate

Hopefully RH will fix the broken Python3.4 yum package so that manual patching isn't needed.

Getting full JS autocompletion under Sublime Text

Check if the snippets have <tabTrigger> attributes that start with special characters. If they do, they won't show up in the autocomplete box. This is currently a problem on Windows with the available jQuery plugins.

See my answer on this thread for more details.

Target Unreachable, identifier resolved to null in JSF 2.2

  1. You need

    @ManagedBean(name="userBean")

  2. Make sure you have getUser() method.

  3. Type of setUser() method should be void.

  4. Make sure that User class has proper setters and getters as well.

Use of Application.DoEvents()

It can be, but it's a hack.

See Is DoEvents Evil?.

Direct from the MSDN page that thedev referenced:

Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. For more information about asynchronous programming, see Asynchronous Programming Overview.

So Microsoft cautions against its use.

Also, I consider it a hack because its behavior is unpredictable and side effect prone (this comes from experience trying to use DoEvents instead of spinning up a new thread or using background worker).

There is no machismo here - if it worked as a robust solution I would be all over it. However, trying to use DoEvents in .NET has caused me nothing but pain.

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

Draw text in OpenGL ES

Look at the "Sprite Text" sample in the GLSurfaceView samples.

Algorithm to calculate the number of divisors of a given number

the prime number method is very clear here . P[] is a list of prime number less than or equal the sq = sqrt(n) ;

for (int i = 0 ; i < size && P[i]<=sq ; i++){
          nd = 1;
          while(n%P[i]==0){
               n/=P[i];
               nd++;
               }
          count*=nd;
          if (n==1)break;
          }
      if (n!=1)count*=2;//the confusing line :D :P .

     i will lift the understanding for the reader  .
     i now look forward to a method more optimized  .

Change / Add syntax highlighting for a language in Sublime 2/3

This is my recipe

Note: This isn't exactly what OP is asking. These instructions will help you change the colors of items (comments, keywords, etc) that are defined syntax matching rules. For example, use these instructions to change so that all code comments are colored blue instead of green.

I believe the OP is asking how to define this as an item to be colored when found in a JavaScript source file.

  1. Install Package: PackageResourceViewer

  2. Ctrl+Shift+P > [PackageResourceViewer: Open Resource] > [Color Scheme - Default] > [Marina.sublime-color-scheme] (or whichever color scheme you use)

  3. The above command will open a new tab to the file "Marina.sublime-color-scheme".

    • For me, this file was located in my roaming profile %appdata% (C:\Users\walter\AppData\Roaming\Sublime Text 3\Packages\Color Scheme - Default\) .
    • However, if I browse to that path in Windows Explorer, [Color Scheme - Default] is not of a child-dir of [Packages] dir. I suspect that PackageResourceViewer is doing some virtualization.

optional step: On the new color-scheme tab: Ctrl+Shift+P > [Set Syntax: JSON]

  1. Search for the rule you want to change. I wanted to make comments be move visible, so I searched for "Comment"

    • I found it in the "rules" section
 "rules":
    [
        {
            "name": "Comment",
            "scope": "comment, punctuation.definition.comment",
            "foreground": "var(blue6)"
        },
  1. Search for the string "blue6": to find the color variable definitions section. I found it in the "variables" section.

  2. Pick a new color using a tool like http://hslpicker.com/ .

  3. Either define a new color variable, or overwrite the color setting for blue6.

    • Warning: overwriting blue6 will affect all other text-elements in that color scheme which also use blue6 ("Punctuation" "Accessor").
  4. Save your file, the changes will be applied instantly to any open files/tabs.

NOTES

Sublime will handle any of these color styles. Possibly more.

hsla = hue, saturation, lightness, alpha rgba = red, green, blue, alpha

hsla(151, 100%, 41%, 1) - last param is the alpha level (transparency) 1 = opaque, 0.5 = half-transparent, 0 = full-transparent

hsl(151, 100%, 41%) - no alpha channel

rgba(0, 209, 108, 1) - rgb with an alpha channel

rgb(0, 209, 108) - no alpha channel

How to make a page redirect using JavaScript?

You can achieve this using the location object.

location.href = "http://someurl"; 

Removing duplicates from a String in Java

Java 8 has a new String.chars() method which returns a stream of characters in the String. You can use stream operations to filter out the duplicate characters like so:

String out = in.chars()
            .mapToObj(c -> Character.valueOf((char) c)) // bit messy as chars() returns an IntStream, not a CharStream (which doesn't exist)
            .distinct()
            .map(Object::toString)
            .collect(Collectors.joining(""));

How can I do GUI programming in C?

A C compiler itself won't provide you with GUI functionality, but there are plenty of libraries for that sort of thing. The most popular is probably GTK+, but it may be a little too complicated if you are just starting out and want to quickly get a GUI up and running.

For something a little simpler, I would recommend IUP. With it, you can use a simple GUI definition language called LED to layout controls (but you can do it with pure C, if you want to).

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.

It can also be opened using the vertical tabs on the right-hand side of the main window.

Convert Unicode data to int in python

int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])

Format decimal for percentage values?

If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.

For example, to get a decimal value with a trailing "%" and no space between the value and the "%":

myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });

More complete example:

using System.Globalization; 

...

decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Best data type for storing currency values in a MySQL database

Something like Decimal(19,4) usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money" as it's non-standard.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

textarea's rows, and cols attribute in CSS

I just wanted to post a demo using calc() for setting rows/height, since no one did.

_x000D_
_x000D_
body {_x000D_
  /* page default */_x000D_
  font-size: 15px;_x000D_
  line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
  /* demo related */_x000D_
  width: 300px;_x000D_
  margin-bottom: 1em;_x000D_
  display: block;_x000D_
  _x000D_
  /* rows related */_x000D_
  font-size: inherit;_x000D_
  line-height: inherit;_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows); */_x000D_
  height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
  height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
_x000D_
_x000D_

If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.

Set environment variables on Mac OS X Lion

Here's a bit more information specifically regarding the PATH variable in Lion OS 10.7.x:

If you need to set the PATH globally, the PATH is built by the system in the following order:

  1. Parsing the contents of the file /private/etc/paths, one path per line
  2. Parsing the contents of the folder /private/etc/paths.d. Each file in that folder can contain multiple paths, one path per line. Load order is determined by the file name first, and then the order of the lines in the file.
  3. A setenv PATH statement in /private/etc/launchd.conf, which will append that path to the path already built in #1 and #2 (you must not use $PATH to reference the PATH variable that has been built so far). But, setting the PATH here is completely unnecessary given the other two options, although this is the place where other global environment variables can be set for all users.

These paths and variables are inherited by all users and applications, so they are truly global -- logging out and in will not reset these paths -- they're built for the system and are created before any user is given the opportunity to login, so changes to these require a system restart to take effect.

BTW, a clean install of OS 10.7.x Lion doesn't have an environment.plist that I can find, so it may work but may also be deprecated.

How to use moment.js library in angular 2 typescript app?

In addition to SnareChop's answer, I had to change the typings file for momentjs.

In moment-node.d.ts I replaced:

export = moment;

with

export default moment;

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

Is either GET or POST more secure than the other?

You have no greater security provided because the variables are sent over HTTP POST than you have with variables sent over HTTP GET.

HTTP/1.1 provides us with a bunch of methods to send a request:

  • OPTIONS
  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • TRACE
  • CONNECT

Lets suppose you have the following HTML document using GET:

<html>
<body>
<form action="http://example.com" method="get">
    User: <input type="text" name="username" /><br/>
    Password: <input type="password" name="password" /><br/>
    <input type="hidden" name="extra" value="lolcatz" />
    <input type="submit"/>
</form>
</body>
</html>

What does your browser ask? It asks this:

 GET /?username=swordfish&password=hunter2&extra=lolcatz HTTP/1.1
 Host: example.com
 Connection: keep-alive
 Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/ [...truncated]
 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) [...truncated]
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Now lets pretend we changed that request method to a POST:

 POST / HTTP/1.1
 Host: example.com
 Connection: keep-alive
 Content-Length: 49
 Cache-Control: max-age=0
 Origin: null
 Content-Type: application/x-www-form-urlencoded
 Accept: application/xml,application/xhtml+xml,text/ [...truncated]
 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; [...truncated]
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

 username=swordfish&password=hunter2&extra=lolcatz

BOTH of these HTTP requests are:

  • Not encrypted
  • Included in both examples
  • Can be evesdroped on, and subject to MITM attacks.
  • Easily reproduced by third party, and script bots.

Many browsers do not support HTTP methods other than POST/GET.

Many browsers behaviors store the page address, but this doesn't mean you can ignore any of these other issues.

So to be specific:

Is one inherently more secure then another? I realize that POST doesn't expose information on the URL but is there any real value in that or is it just security through obscurity? What is the best practice here?

This is correct, because the software you're using to speak HTTP tends to store the request variables with one method but not another only prevents someone from looking at your browser history or some other naive attack from a 10 year old who thinks they understand h4x0r1ng, or scripts that check your history store. If you have a script that can check your history store, you could just as easily have one that checks your network traffic, so this entire security through obscurity is only providing obscurity to script kiddies and jealous girlfriends.

Over https, POST data is encoded, but could urls be sniffed by a 3rd party?

Here's how SSL works. Remember those two requests I sent above? Here's what they look like in SSL: (I changed the page to https://encrypted.google.com/ as example.com doesn't respond on SSL).

POST over SSL

q5XQP%RWCd2u#o/T9oiOyR2_YO?yo/3#tR_G7 2_RO8w?FoaObi)
oXpB_y?oO4q?`2o?O4G5D12Aovo?C@?/P/oOEQC5v?vai /%0Odo
QVw#6eoGXBF_o?/u0_F!_1a0A?Q b%TFyS@Or1SR/O/o/_@5o&_o
9q1/?q$7yOAXOD5sc$H`BECo1w/`4?)f!%geOOF/!/#Of_f&AEI#
yvv/wu_b5?/o d9O?VOVOFHwRO/pO/OSv_/8/9o6b0FGOH61O?ti
/i7b?!_o8u%RS/Doai%/Be/d4$0sv_%YD2_/EOAO/C?vv/%X!T?R
_o_2yoBP)orw7H_yQsXOhoVUo49itare#cA?/c)I7R?YCsg ??c'
(_!(0u)o4eIis/S8Oo8_BDueC?1uUO%ooOI_o8WaoO/ x?B?oO@&
Pw?os9Od!c?/$3bWWeIrd_?( `P_C?7_g5O(ob(go?&/ooRxR'u/
T/yO3dS&??hIOB/?/OI?$oH2_?c_?OsD//0/_s%r

GET over SSL

rV/O8ow1pc`?058/8OS_Qy/$7oSsU'qoo#vCbOO`vt?yFo_?EYif)
43`I/WOP_8oH0%3OqP_h/cBO&24?'?o_4`scooPSOVWYSV?H?pV!i
?78cU!_b5h'/b2coWD?/43Tu?153pI/9?R8!_Od"(//O_a#t8x?__
bb3D?05Dh/PrS6_/&5p@V f $)/xvxfgO'q@y&e&S0rB3D/Y_/fO?
_'woRbOV?_!yxSOdwo1G1?8d_p?4fo81VS3sAOvO/Db/br)f4fOxt
_Qs3EO/?2O/TOo_8p82FOt/hO?X_P3o"OVQO_?Ww_dr"'DxHwo//P
oEfGtt/_o)5RgoGqui&AXEq/oXv&//?%/6_?/x_OTgOEE%v (u(?/
t7DX1O8oD?fVObiooi'8)so?o??`o"FyVOByY_ Supo? /'i?Oi"4
tr'9/o_7too7q?c2Pv

(note: I converted the HEX to ASCII, some of it should obviously not be displayable)

The entire HTTP conversation is encrypted, the only visible portion of communication is on the TCP/IP layer (meaning the IP address and connection port information).

So let me make a big bold statement here. Your website is not provided greater security over one HTTP method than it is another, hackers and newbs all over the world know exactly how to do what I've just demonstrated here. If you want security, use SSL. Browsers tend to store history, it's recommended by RFC2616 9.1.1 to NOT use GET to perform an action, but to think that POST provides security is flatly wrong.

The only thing that POST is a security measure towards? Protection against your jealous ex flipping through your browser history. That's it. The rest of the world is logged into your account laughing at you.

To further demonstrate why POST isn't secure, Facebook uses POST requests all over the place, so how can software such as FireSheep exist?

Note that you may be attacked with CSRF even if you use HTTPS and your site does not contain XSS vulnerabilities. In short, this attack scenario assumes that the victim (the user of your site or service) is already logged in and has a proper cookie and then the victim's browser is requested to do something with your (supposedly secure) site. If you do not have protection against CSRF the attacker can still execute actions with the victims credentials. The attacker cannot see the server response because it will be transferred to the victim's browser but the damage is usually already done at that point.

How to get the latest record in each group using GROUP BY?

this query return last record for every Form_id:

    SELECT m1.*
     FROM messages m1 LEFT JOIN messages m2
     ON (m1.Form_id = m2.Form_id AND m1.id < m2.id)
     WHERE m2.id IS NULL;

How to define an optional field in protobuf 3

you can find if one has been initialized by comparing the references with the default instance:

GRPCContainer container = myGrpcResponseBean.getContainer();
if (container.getDefaultInstanceForType() != container) {
...
}

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

How may I align text to the left and text to the right in the same line?

HTML FILE:

<div class='left'> Left Aligned </div> 
<div class='right'> Right Aligned </div>

CSS FILE:

.left
{
  float: left;
}

.right
{
  float: right;
}

and you are done ....

Matplotlib tight_layout() doesn't take into account figure suptitle

This website has a simple solution to this with an example that worked for me. The line of code that does the actual leaving of space for the title is the following:

plt.tight_layout(rect=[0, 0, 1, 0.95]) 

Here is an image of proof that it worked for me: Image Link

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You must add it to entryComponents, as specified in the docs.

@NgModule({
  imports: [
    // ...
  ],
  entryComponents: [
    DialogInvokingComponent, 
    DialogResultExampleDialog
  ],
  declarations: [
    DialogInvokingComponent,   
    DialogResultExampleDialog
  ],
  // ...
})

Here is a full example for an app module file with a dialog defined as entryComponents.

How to concatenate two numbers in javascript?

You can return a number by using this trick:
not recommended

[a] + b - 0

Example :

let output = [5] + 6 - 0;
console.log(output); // 56
console.log(typeof output); // number

Difference between Interceptor and Filter in Spring MVC

A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.

Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.

Reference: http://static.springframework.org/sp...ng-interceptor

How can I find the location of origin/master in git, and how do I change it?

I had this problem recently and I figured it was because I had deleted some files that I did not need anymore. The problem is that git does not know that the files have been deleted and it sees that the server still has it. (server = origin)

So I ran

git rm $(git ls-files --deleted)

And then ran a commit and push.

That solved the issue.

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:

code1:

[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here

code2:

[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true

conclusion:

as u can see [] and new Array() create a new instance of Array.And they all get the prototype functions from Array.prototype

They are just different instance of Array.so this explain why [] != []

:)

Initializing a dictionary in python with a key value and no corresponding values

You can initialize the values as empty strings and fill them in later as they are found.

dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

If we need to move from one component to another service then we have to define that service into app.module providers array.

How to implement infinity in Java?

Since the class Number is not final, here is an idea, that I don't find yet in the other posts. Namely to subclass the class Number.

This would somehow deliver an object that can be treated as infinity for Integer, Long, Double, Float, BigInteger and BigDecimal.

Since there are only two values, we could use the singleton pattern:

public final class Infinity extends Number {
    public final static Infinity POSITIVE = new Infinity(false);
    public final static Infinity NEGATIVE = new Infinity(true);
    private boolean negative;
    private Infinity(boolean n) {
        negative = n;
    }
}

Somehow I think the remaining methods intValue(), longValue() etc.. should then be overriden to throw an exceptions. So that the infinity value cannot be used without further precautions.

How to pass ArrayList of Objects from one to another activity using Intent in android?

Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra

example:

Implement parcelable on your custom class -(Alt +enter) Implement its methods

public class Model implements Parcelable {

private String Id;

public Model() {

}

protected Model(Parcel in) {
    Id= in.readString();       
}

public static final Creator<Model> CREATOR = new Creator<Model>() {
    @Override
    public ModelcreateFromParcel(Parcel in) {
        return new Model(in);
    }

    @Override
    public Model[] newArray(int size) {
        return new Model[size];
    }
};

public String getId() {
    return Id;
}

public void setId(String Id) {
    this.Id = Id;
}


@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(Id);
}
}

Pass class object from activity 1

 Intent intent = new Intent(Activity1.this, Activity2.class);
            intent.putParcelableArrayListExtra("model", modelArrayList);
            startActivity(intent);

Get extra from Activity2

if (getIntent().hasExtra("model")) {
        Intent intent = getIntent();
        cartArrayList = intent.getParcelableArrayListExtra("model");

    } 

When to use If-else if-else over switch statements and vice versa

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.

Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

Add the following to the avd config.ini

disk.dataPartition.size=1024MB

Let me know if this works for you also.

I added in the line Add Data Partition Size Configuration
Screen Shot of AVD Storage Space being increased

TypeError: coercing to Unicode: need string or buffer

Here is the best way I found for Python 2:

def inplace_change(file,old,new):
        fin = open(file, "rt")
        data = fin.read()
        data = data.replace(old, new)
        fin.close()

        fin = open(file, "wt")
        fin.write(data)
        fin.close()

An example:

inplace_change('/var/www/html/info.txt','youtub','youtube')

I am not able launch JNLP applications using "Java Web Start"?

Although this question is bit old, the issue was caused by corrupted ClearType registry setting and resolved by fixing it, as described in this ClearType, install4j and case of Java bug post.

ClearType, install4j and case of Java bug Java

Do you know what ClearType (font-smoothing technology in Windows) has in common with Java (programming language and one of the recommended frameworks)?

Nothing except that they were working together hard at making me miserable for few months. I had some Java software that I couldn’t install. I mean really couldn’t – not even figure out reason or reproduce it on another PC.

Recently I was approved for Woopra beta (site analytics service) and it uses desktop client written in Java… I couldn’t install. That got me really mad. :)

Story All of the software in question was similar :

setup based on install4j; setup crashing with bunch of errors. I was blaming install4j during early (hundred or so) attempts to solve issue. Later I slowly understood that if it was that bugged for that long time – solution would have been created and googled.

Tracing After shifting focus from install4j I decided to push Java framework. I was trying stable versions earlier so decided to go for non-stable 1.6 Update 10 Release Candidate.

This actually fixed error messages but not crashes. I had also noticed that there was new error log created in directory with setup files. Previously I had only seen logs in Windows temporary directory.

New error log was saying following :

Could not display the GUI. This application needs access to an X Server. If you have access there is probably an X library missing. ******************************************************************* You can also run this application in console mode without access to an X server by passing the argument -c Very weird to look for X-Server on non-Linux PC, isn’t it? So I decided to try that “-c” argument. And was actually able to install in console mode.

Happy ending? Nope. Now installed app was crashing. But it really got me thinking. If console works but graphical interface doesn’t – there must be problem with latter.

One more error log (in application folder) was now saying (among other things) :

Caused by: java.lang.IllegalArgumentException: -60397977 incompatible with Text-specific LCD contrast key Which successfully googled me description of bug with Java unable to read non-standard ClearType registry setting.

Solution I immediately launched ClearType Tuner from Control Panel and found setting showing gibberish number. After correcting it to proper one all problems with Java were instantly gone.

cleartypetuner_screenshot Lessons learned Don’t be fast to blame software problems on single application. Even minor and totally unrelated settings can launch deadly chain reactions. Links Jave Runtime Environment http://www.java.com/en/download/index.jsp

ClearType Tuner http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx

Woopra http://www.woopra.com/

install4j http://www.ej-technologies.com/products/install4j/overview.html

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

In my rare case it was color wrapper who spoiled gcc. Solved by disabling cw excluding its directory /usr/libexec/cw from PATH environmental variable.

Extract values in Pandas value_counts()

First you have to sort the dataframe by the count column max to min if it's not sorted that way already. In your post, it is in the right order already but I will sort it anyways:

dataframe.sort_index(by='count', ascending=[False])
    col     count
0   apple   5
1   sausage 2
2   banana  2
3   cheese  1 

Then you can output the col column to a list:

dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']

Better way to get type of a Javascript variable?

You can apply Object.prototype.toString to any object:

var toString = Object.prototype.toString;

console.log(toString.call([]));
//-> [object Array]

console.log(toString.call(/reg/g));
//-> [object RegExp]

console.log(toString.call({}));
//-> [object Object]

This works well in all browsers, with the exception of IE - when calling this on a variable obtained from another window it will just spit out [object Object].

Turn off warnings and errors on PHP and MySQL

You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, so now we can simply write

<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">

If you are using an earlier version of Angular, your two choices are:

  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]

item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

E.g.,

<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
 or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>

$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.

With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values.

An example of 1) was given above. Here is an example of 3, which I think reads much better:

 <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>

The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.

ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,

 <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Basic True / False Declaration

$is_admin = ($user['permissions'] == 'admin' ? true : false);

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Conditional Items Message

echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';

ref: https://davidwalsh.name/php-ternary-examples

How does RewriteBase work in .htaccess

When I develop, it's on a different domain within a folder. When I take a site live, that folder doesn't exist anymore. Using RewriteBase allows me to use the same .htaccess file in both environments.

When live:

RewriteBase /
# RewriteBase /dev_folder/

When developing:

# RewriteBase /
RewriteBase /dev_folder/

How to copy a char array in C?

If your arrays are not string arrays, use: memcpy(array2, array1, sizeof(array2));

"CSV file does not exist" for a filename with embedded quotes

What worked for me:

import csv
import pandas as pd
import os

base =os.path.normpath(r"path")



with open(base, 'r') as csvfile:
    readCSV = csv.reader(csvfile, delimiter='|')
    data=[]
    for row in readCSV:
        data.append(row)
    df = pd.DataFrame(data[1:],columns=data[0][0:15])
    print(df)


This reads in the file , delimit by |, and appends to list which is converted to a pandas df (taking 15 columns)

C# version of java's synchronized keyword?

Does c# have its own version of the java "synchronized" keyword?

No. In C#, you explicitly lock resources that you want to work on synchronously across asynchronous threads. lock opens a block; it doesn't work on method level.

However, the underlying mechanism is similar since lock works by invoking Monitor.Enter (and subsequently Monitor.Exit) on the runtime. Java works the same way, according to the Sun documentation.

Pygame mouse clicking detection

The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

Crontab Day of the Week syntax

    :-) Sunday    |    0  ->  Sun
                  |  
        Monday    |    1  ->  Mon
       Tuesday    |    2  ->  Tue
     Wednesday    |    3  ->  Wed
      Thursday    |    4  ->  Thu
        Friday    |    5  ->  Fri
      Saturday    |    6  ->  Sat
                  |  
    :-) Sunday    |    7  ->  Sun

As you can see above, and as said before, the numbers 0 and 7 are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.

Examples of Number or Abbreviation Use

15 09 * * 5,6,0             command
15 09 * * 5,6,7             command
15 09 * * 5-7               command
15 09 * * Fri,Sat,Sun       command

The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.

In Detail

Having two numbers 0 and 7 for Sunday can be useful for writing weekday ranges starting with 0 or ending with 7. So you can write ranges starting with Sunday or ending with it, like 0-2 or 5-7 for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

Ansible: copy a directory content to another directory

The simplest solution I've found to copy the contents of a folder without copying the folder itself is to use the following:

- name: Move directory contents
  command: cp -r /<source_path>/. /<dest_path>/

This resolves @surfer190's follow-up question:

Hmmm what if you want to copy the entire contents? I noticed that * doesn't work – surfer190 Jul 23 '16 at 7:29

* is a shell glob, in that it relies on your shell to enumerate all the files within the folder before running cp, while the . directly instructs cp to get the directory contents (see https://askubuntu.com/questions/86822/how-can-i-copy-the-contents-of-a-folder-to-another-folder-in-a-different-directo)

Empty set literal?

By all means, please use set() to create an empty set.

But, if you want to impress people, tell them that you can create an empty set using literals and * with Python >= 3.5 (see PEP 448) by doing:

>>> s = {*()}  # or {*{}} or {*[]}
>>> print(s)
set()

this is basically a more condensed way of doing {_ for _ in ()}, but, don't do this.

Is Safari on iOS 6 caching $.ajax results?

After a bit of investigation, turns out that Safari on iOS6 will cache POSTs that have either no Cache-Control headers or even "Cache-Control: max-age=0".

The only way I've found of preventing this caching from happening at a global level rather than having to hack random querystrings onto the end of service calls is to set "Cache-Control: no-cache".

So:

  • No Cache-Control or Expires headers = iOS6 Safari will cache
  • Cache-Control max-age=0 and an immediate Expires = iOS6 Safari will cache
  • Cache-Control: no-cache = iOS6 Safari will NOT cache

I suspect that Apple is taking advantage of this from the HTTP spec in section 9.5 about POST:

Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.

So in theory you can cache POST responses...who knew. But no other browser maker has ever thought it would be a good idea until now. But that does NOT account for the caching when no Cache-Control or Expires headers are set, only when there are some set. So it must be a bug.

Below is what I use in the right bit of my Apache config to target the whole of my API because as it happens I don't actually want to cache anything, even gets. What I don't know is how to set this just for POSTs.

Header set Cache-Control "no-cache"

Update: Just noticed that I didn't point out that it is only when the POST is the same, so change any of the POST data or URL and you're fine. So you can as mentioned elsewhere just add some random data to the URL or a bit of POST data.

Update: You can limit the "no-cache" just to POSTs if you wish like this in Apache:

SetEnvIf Request_Method "POST" IS_POST
Header set Cache-Control "no-cache" env=IS_POST

How to count lines in a document?

This drop-in portable shell function [?]  works like a charm. Just add the following snippet to your .bashrc file (or the equivalent for your shell environment).

# ---------------------------------------------
#  Count lines in a file
#
#  @1 = path to file
#
#  EXAMPLE USAGE: `count_file_lines $HISTFILE`
# ---------------------------------------------
count_file_lines() {
    local subj=$(wc -l $1)
    subj="${subj//$1/}"
    echo ${subj//[[:space:]]}
}

This should be fully compatible with all POSIX-compliant shells in addition to bash and zsh.

Multiple radio button groups in one form

Just do one thing, We need to set the name property for the same types. for eg.

Try below:

<form>
    <div id="group1">
        <input type="radio" value="val1" name="group1">
        <input type="radio" value="val2" name="group1">
    </div>
</form>

And also we can do it in angular1,angular 2 or in jquery also.

<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>  

How to convert a List<String> into a comma separated string without iterating List explicitly

One Liner (pure Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

Error 0x8007000d means URL rewriting module (referenced in web.config) is missing or proper version is not installed.

Just install URL rewriting module via web platform installer.

I recommend to check all dependencies from web.config and install them.

OpenCV - DLL missing, but it's not?

In Visual Studio 2013 you need to add this to the Environment Variables and then Restart your pc. This is the path where .dll file located in.

enter image description here

Spring 3 MVC accessing HttpRequest from controller

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**
 * Generate a PDF report...
 */
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
        @PathVariable("objectId") Long objectId, 
        HttpServletRequest request, 
        HttpServletResponse response) {

    // ...
    // Here you can use the request and response objects like:
    // response.setContentType("application/pdf");
    // response.getOutputStream().write(...);

}

As you see, simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession object too.

EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.

I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.

Open youtube video in Fancybox jquery

I started by using the answers here, but modified it to use YouTube's new iframe embedding...

$('a.more').on('click', function(event) {
    event.preventDefault();
    $.fancybox({
        'type' : 'iframe',
        // hide the related video suggestions and autoplay the video
        'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
        'overlayShow' : true,
        'centerOnScroll' : true,
        'speedIn' : 100,
        'speedOut' : 50,
        'width' : 640,
        'height' : 480
    });
});

How to do joins in LINQ on multiple fields in single join

var result = from x in entity
   join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

How to round a number to significant figures in Python

This returns a string, so that results without fractional parts, and small values which would otherwise appear in E notation are shown correctly:

def sigfig(x, num_sigfig):
    num_decplace = num_sigfig - int(math.floor(math.log10(abs(x)))) - 1
    return '%.*f' % (num_decplace, round(x, num_decplace))

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

Limit the size of a file upload (html input element)

Video file example (HTML + Javascript):

_x000D_
_x000D_
function upload_check()
{
    var upl = document.getElementById("file_id");
    var max = document.getElementById("max_id").value;

    if(upl.files[0].size > max)
    {
       alert("File too big!");
       upl.value = "";
    }
};
_x000D_
<form action="some_script" method="post" enctype="multipart/form-data">
    <input id="max_id" type="hidden" name="MAX_FILE_SIZE" value="250000000" />
    <input onchange="upload_check()" id="file_id" type="file" name="file_name" accept="video/*" />
    <input type="submit" value="Upload"/>
</form>
_x000D_
_x000D_
_x000D_

How to create a WPF Window without a border that can be resized via a grip only?

I was having difficulty getting the answer by @fernando-aguirre using WindowChrome to work. It was not working in my case because I was overriding OnSourceInitialized in the MainWindow and not calling the base class method.

protected override void OnSourceInitialized(EventArgs e)
{
    ViewModel.Initialize(this);
    base.OnSourceInitialized(e); // <== Need to call this!
}

This stumped me for a very long time.

Error in Swift class: Property not initialized at super.init call

Sorry for ugly formatting. Just put a question character after declaration and everything will be ok. A question tells the compiler that the value is optional.

class Square: Shape {
    var sideLength: Double?   // <=== like this ..

    init(sideLength:Double, name:String) {
        super.init(name:name) // Error here
        self.sideLength = sideLength
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Edit1:

There is a better way to skip this error. According to jmaschad's comment there is no reason to use optional in your case cause optionals are not comfortable in use and You always have to check if optional is not nil before accessing it. So all you have to do is to initialize member after declaration:

class Square: Shape {
    var sideLength: Double=Double()   

    init(sideLength:Double, name:String) {
        super.init(name:name)
        self.sideLength = sideLength
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Edit2:

After two minuses got on this answer I found even better way. If you want class member to be initialized in your constructor you must assign initial value to it inside contructor and before super.init() call. Like this:

class Square: Shape {
    var sideLength: Double  

    init(sideLength:Double, name:String) {
        self.sideLength = sideLength   // <= before super.init call..
        super.init(name:name)
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Good luck in learning Swift.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I think that the most straight forward way to run jobs in parallel and check for status is using temporary files. There are already a couple similar answers (e.g. Nietzche-jou and mug896).

#!/bin/bash
rm -f fail
for i in `seq 0 9`; do
  doCalculations $i || touch fail &
done
wait 
! [ -f fail ]

The above code is not thread safe. If you are concerned that the code above will be running at the same time as itself, it's better to use a more unique file name, like fail.$$. The last line is to fulfill the requirement: "return exit code 1 when any of subprocesses ends with code !=0?" I threw an extra requirement in there to clean up. It may have been clearer to write it like this:

#!/bin/bash
trap 'rm -f fail.$$' EXIT
for i in `seq 0 9`; do
  doCalculations $i || touch fail.$$ &
done
wait 
! [ -f fail.$$ ] 

Here is a similar snippet for gathering results from multiple jobs: I create a temporary directory, story the outputs of all the sub tasks in a separate file, and then dump them for review. This doesn't really match the question - I'm throwing it in as a bonus:

#!/bin/bash
trap 'rm -fr $WORK' EXIT

WORK=/tmp/$$.work
mkdir -p $WORK
cd $WORK

for i in `seq 0 9`; do
  doCalculations $i >$i.result &
done
wait 
grep $ *  # display the results with filenames and contents

What is Bootstrap?

By today's standards and web terminology, I'd say Bootstrap is actually not a framework, although that's what their website claims. Most developers consider Angular, Vue and React frameworks, while Bootstrap is commonly referred to as a "library".

But, to be exact and correct, Bootstrap is an open-source, mobile-first collection of CSS, JavaScript and HTML design utilities aimed at providing means to develop commonly used web elements considerably faster (and smarter) than having to code them from scratch.

A few core principles which contributed to Bootstrap's success:

  • it's reusable
  • it's flexible (i.e: allows custom grid systems, changing responsiveness breakpoints, column gutter sizes or state colors with ease; as a rule of thumb, most settings are controlled by global variables)
  • it's intuitive
  • it's modular (both JavaScript and (S)CSS use a modular approach; one can easily find tutorials on making custom Bootstrap builds, to include only the parts they need)
  • has above average cross-browser compatibility
  • web accessibility out of the box (screenreader ready)
  • it's fairly well documented

It contains design templates and functionality for: layout, typography, forms, navigation, menus (including dropdowns), buttons, panels, badges, modals, alerts, tabs, collapsible, accordions, carousels, lists, tables, pagination, media utilities (including embeds, images and image replacement), responsiveness utilities, color-based utilities (primary, secondary, danger, warning, info, light, dark, muted, white), other utilities (position, margin, padding, sizing, spacing, alignment, visibility), scrollspy, affix, tooltips, popovers.


By default it relies on jQuery, but you'll find jQuery free variants powered by each of the modern popular progressive JavaScript frameworks:

Working with Bootstrap relies heavily on applying certain classes (or, depending on JS framework: directives, methods or attributes/props) and on using particular markup structures.

Documentation typically contains generic examples which can be easily copy-pasted and used as starter templates.


Another advantage of developing with Bootstrap is its vibrant community, translated into an abundance of themes, templates and plugins available for it, most of which are open-source (i.e: calendars, date/time-pickers, plugins for tabular content management, as well as libraries/component collections built on top of Bootstrap, such as MDB, portfolio templates, admin templates, etc...)

Last, but not least, Bootstrap has been well maintained over the years, which makes it a solid choice for production-ready applications/websites.

How to work on UAC when installing XAMPP

Basically there's three things you can do

  1. Ensure that your user account has administrator privilege.
  2. Disable User Account Control (UAC).
  3. Install in C://xampp.

I've just writen an answer to a very similar answer here where I explain how you can disable UAC since Windows 8.

SQLite table constraint - unique on multiple columns

Put the UNIQUE declaration within the column definition section; working example:

CREATE TABLE a (
    i INT,
    j INT,
    UNIQUE(i, j) ON CONFLICT REPLACE
);

MySQL Delete all rows from table and reset ID to zero

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a database with approximately 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

C# password TextBox in a ASP.net website

Use the password input type.

<input type="password" name="password" />

Here is a simple demo http://jsfiddle.net/cPaEN/

What's the Android ADB shell "dumpsys" tool and what are its benefits?

According to official Android information about dumpsys:

The dumpsys tool runs on the device and provides information about the status of system services.

To get a list of available services use

adb shell dumpsys -l

Javascript Regexp dynamic generation from variables?

You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);

How to set div's height in css and html

To write inline styling use:

<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>

Inline styling serves a purpose however, it is not recommended in most situations.

The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.

if you have the file structure:

index.html
>>/css/
>>/css/styles.css

Then in your HTML document between <head> and </head> write:

<link href="css/styles.css" rel="stylesheet" />

Then, change your div structure to be:

<div id="someidname" class="someclassname">
    asdfashdjkfhaskjdf
</div>

In css, you can reference your div from the ID or the CLASS.

To do so write:

.someclassname { height: 100px; }

OR

#someidname { height: 100px; }

Note that if you do both, the one that comes further down the file structure will be the one that actually works.

For example... If you have:

.someclassname { height: 100px; }

.someclassname { height: 150px; }

Then in this situation the height will be 150px.

EDIT:

To answer your secondary question from your edit, probably need overflow: hidden; or overflow: visible; . You could also do this:

<div class="span12">
    <div style="height:100px;">
        asdfashdjkfhaskjdf
    </div>
</div>

git: How to diff changed files versus previous versions after a pull?

I like to use:

git diff HEAD^

Or if I only want to diff a specific file:

git diff HEAD^ -- /foo/bar/baz.txt

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

How to test if JSON object is empty in Java

Object getResult = obj.get("dps"); 
if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
    handleEmptyDps(); 
} 
else {
    handleResult(getResult); 
}

Javascript string replace with regex to strip off illegal characters

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

How to document a method with parameter(s)?

Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.

One example:

Parameters
----------
x : type
    Description of parameter `x`.

Preprocessing in scikit learn - single sample - Depreciation warning

.values.reshape(-1,1) will be accepted without alerts/warnings

.reshape(-1,1) will be accepted, but with deprecation war

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

How do I add a Font Awesome icon to input field?

.fa-file-o {
    position: absolute;
    left: 50px;
    top: 15px;
    color: #ffffff
}

<div>
 <span class="fa fa-file-o"></span>
 <input type="button" name="" value="IMPORT FILE"/>
</div>

Triangle Draw Method

You should try using the Shapes API.

Take a look at JPanel repaint from another class which is all about drawing triangles, look to the getPath method for some ideas

You should also read up on GeneralPath & Drawing Arbitrary Shapes.

This method is much easy to apply AffineTransformations to

How to read user input into a variable in Bash?

Yep, you'll want to do something like this:

echo -n "Enter Fullname: " 
read fullname

Another option would be to have them supply this information on the command line. Getopts is your best bet there.

Using getopts in bash shell script to get long and short command line options

how to make twitter bootstrap submenu to open on the left side?

If you're using LESS CSS, I wrote a little mixin to move the dropdown with the connecting arrow:

.dropdown-menu-shift( @num-pixels, @arrow-position: 10px ) {  // mixin to shift the dropdown menu
    left: @num-pixels;
    &:before { left: -@num-pixels + @arrow-position; }        // triangle outline
    &:after  { left: -@num-pixels + @arrow-position + 1px; }  // triangle internal
}

Then to move a .dropdown-menu with an id of dropdown-menu-x for example, you can do:

#dropdown-menu-x {
    .dropdown-menu-shift( -100px );
}

html/css buttons that scroll down to different div sections on a webpage

HTML

<a href="#top">Top</a>
<a href="#middle">Middle</a>
<a href="#bottom">Bottom</a>
<div id="top"><a href="top"></a>Top</div>
<div id="middle"><a href="middle"></a>Middle</div>
<div id="bottom"><a href="bottom"></a>Bottom</div>

CSS

#top,#middle,#bottom{
    height: 600px;
    width: 300px;
    background: green; 
}

Example http://jsfiddle.net/x4wDk/

How to do case insensitive string comparison?

For better browser compatibility you can rely on a regular expression. This will work in all web browsers released in the last 20 years:

String.prototype.equalsci = function(s) {
    var regexp = RegExp("^"+this.replace(/[.\\+*?\[\^\]$(){}=!<>|:-]/g, "\\$&")+"$", "i");
    return regexp.test(s);
}

"PERSON@Ü.EXAMPLE.COM".equalsci("person@ü.example.com")// returns true

This is different from the other answers found here because it takes into account that not all users are using modern web browsers.

Note: If you need to support unusual cases like the Turkish language you will need to use localeCompare because i and I are not the same letter in Turkish.

"I".localeCompare("i", undefined, { sensitivity:"accent"})===0// returns true
"I".localeCompare("i", "tr", { sensitivity:"accent"})===0// returns false

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

How do I concatenate or merge arrays in Swift?

Swift 3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

calculate the mean for each column of a matrix in R

class(mtcars)
my.mean <- unlist(lapply(mtcars, mean)); my.mean



   mpg        cyl       disp         hp       drat         wt       qsec         vs 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750   0.437500 
        am       gear       carb 
  0.406250   3.687500   2.812500 

Send Outlook Email Via Python?

Other than win32, if your company had set up you web outlook, you can also try PYTHON REST API, which is officially made by Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)

Git reset --hard and push to remote repository

If forcing a push doesn't help ("git push --force origin" or "git push --force origin master" should be enough), it might mean that the remote server is refusing non fast-forward pushes either via receive.denyNonFastForwards config variable (see git config manpage for description), or via update / pre-receive hook.

With older Git you can work around that restriction by deleting "git push origin :master" (see the ':' before branch name) and then re-creating "git push origin master" given branch.

If you can't change this, then the only solution would be instead of rewriting history to create a commit reverting changes in D-E-F:

A-B-C-D-E-F-[(D-E-F)^-1]   master

A-B-C-D-E-F                             origin/master

How to swap two variables in JavaScript

Destructing assignment is the best way to solve your problem.

_x000D_
_x000D_
var a = 1;
var b = 2;

[a, b] = [b, a];

console.log("After swap a =", a, " and b =", b);
_x000D_
_x000D_
_x000D_

Cast IList to List

Try

List<SubProduct> subProducts = new List<SubProduct>(Model.subproduct);

or

List<SubProduct> subProducts = Model.subproducts as List<SubProduct>;

What's the difference between UTF-8 and UTF-8 without BOM?

The other excellent answers already answered that:

  • There is no official difference between UTF-8 and BOM-ed UTF-8
  • A BOM-ed UTF-8 string will start with the three following bytes. EF BB BF
  • Those bytes, if present, must be ignored when extracting the string from the file/stream.

But, as additional information to this, the BOM for UTF-8 could be a good way to "smell" if a string was encoded in UTF-8... Or it could be a legitimate string in any other encoding...

For example, the data [EF BB BF 41 42 43] could either be:

  • The legitimate ISO-8859-1 string "ABC"
  • The legitimate UTF-8 string "ABC"

So while it can be cool to recognize the encoding of a file content by looking at the first bytes, you should not rely on this, as show by the example above

Encodings should be known, not divined.

How to initialize log4j properly?

What are you developing in? Are you using Apache Tomcat?

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} [[%5p] %c{1} [%t]] %m%n

I have a properties like this in a Java app of mine.

AppSettings get value from .config file

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"

CODE WILL BE GENERATED AUTOMATICALLY

    <configuration>
      <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... >
          <section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... />
        </sectionGroup>
      </configSections>
      <applicationSettings>
        <XX....Properties.Settings>
          <setting name="name" serializeAs="String">
            <value>value</value>
          </setting>
          <setting name="name2" serializeAs="String">
            <value>value2</value>
          </setting>
       </XX....Properties.Settings>
      </applicationSettings>
    </configuration>

To get a value

Properties.Settings.Default.Name

OR

Properties.Settings.Default["name"]

jquery ajax function not working

you need to prevent the default behavior of your form when submitting

by adding this:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

Do a "git export" (like "svn export")?

enter image description here

A special case answer if the repository is hosted on GitHub.

Just use svn export.

As far as I know Github does not allow archive --remote. Although GitHub is svn compatible and they do have all git repos svn accessible so you could just use svn export like you normally would with a few adjustments to your GitHub url.

For example to export an entire repository, notice how trunk in the URL replaces master (or whatever the project's HEAD branch is set to):

svn export https://github.com/username/repo-name/trunk/

And you can export a single file or even a certain path or folder:

svn export https://github.com/username/repo-name/trunk/src/lib/folder

Example with jQuery JavaScript Library

The HEAD branch or master branch will be available using trunk:

svn ls https://github.com/jquery/jquery/trunk

The non-HEAD branches will be accessible under /branches/:

svn ls https://github.com/jquery/jquery/branches/2.1-stable

All tags under /tags/ in the same fashion:

svn ls https://github.com/jquery/jquery/tags/2.1.3

Python Git Module experiences?

Maybe it helps, but Bazaar and Mercurial are both using dulwich for their Git interoperability.

Dulwich is probably different than the other in the sense that's it's a reimplementation of git in python. The other might just be a wrapper around Git's commands (so it could be simpler to use from a high level point of view: commit/add/delete), it probably means their API is very close to git's command line so you'll need to gain experience with Git.