Programs & Examples On #Nmock 2.1

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

This error message can also be caused by SELinux. Check if SELinux is enabled with getenforce

You need to adjust SELinux to use your port and restart.

I.E.

semanage port -a -t http_port_t -p tcp 9080 2>/dev/null || semanage port -m -t http_port_t -p tcp 9080

Sending HTTP POST Request In Java

simplest way to send parameters with the post request:

String postURL = "http://www.example.com/page.php";

HttpPost post = new HttpPost(postURL);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));

UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);

HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);

You have done. now you can use responsePOST. Get response content as string:

BufferedReader reader = new BufferedReader(new  InputStreamReader(responsePOST.getEntity().getContent()), 2048);

if (responsePOST != null) {
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(" line : " + line);
        sb.append(line);
    }
    String getResponseString = "";
    getResponseString = sb.toString();
//use server output getResponseString as string value.
}

How can I add a variable to console.log?

When using ES6 you can also do this:

var name = prompt("what is your name?");
console.log(`story ${name} story`);

Note: You need to use backticks `` instead of "" or '' to do it like this.

ECMAScript 6 arrow function that returns an object

ES6 Arrow Function returns an Object

the right ways

  1. normal function return an object

const getUser = user => {return { name: user.name, age: user.age };};

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

  1. (js expressions )

const getUser = user => ({ name: user.name, age: user.age });

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

explain

image

refs

https://github.com/lydiahallie/javascript-questions/issues/220

https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript

How can I set the 'backend' in matplotlib in Python?

I hit this when trying to compile python, numpy, scipy, matplotlib in my own VIRTUAL_ENV

Before installing matplotlib you have to build and install: pygobject pycairo pygtk

And then do it with matplotlib: Before building matplotlib check with 'python ./setup.py build --help' if 'gtkagg' backend is enabled. Then build and install

Before export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig

PowerShell To Set Folder Permissions

Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:

$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl

How to verify if a file exists in a batch file?

You can use IF EXIST to check for a file:

IF EXIST "filename" (
  REM Do one thing
) ELSE (
  REM Do another thing
)

If you do not need an "else", you can do something like this:

set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=

Here's a working example of searching for a file or a folder:

REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file    

IF EXIST "filename" (
  ECHO file filename exists
) ELSE (
  ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
  ECHO file filename2.txt exists
) ELSE (
  ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash    

REM finds folder

IF EXIST "foldername\" (
  ECHO folder foldername exists
) ELSE (
  ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
  ECHO folder filename exists
) ELSE (
  ECHO folder filename does not exist
)

.htaccess deny from all

You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

How to list AD group membership for AD users using input list?

Everything in one line:

get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof  -join ";"  } } | export-csv membership.csv

Response.Redirect to new window

HTML

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" />

Javascript:

function SetTarget() {
 document.forms[0].target = "_blank";}

AND codebehind:

Response.Redirect(URL); 

Array of an unknown length in C#

Use List<> to build up an 'array' of unknown length.

Use List<>.ToArray() to return a real array, and not a List.

var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();

String to HashMap JAVA

try

 String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
    HashMap<String,Integer> hm =new HashMap<String,Integer>();
    for(String s1:s.split(",")){
       String[] s2 = s1.split(":");
        hm.put(s2[0], Integer.parseInt(s2[1]));
    }

How to set background color of a button in Java GUI?

Check out JButton documentation. Take special attention to setBackground and setForeground methods inherited from JComponent.

Something like:

for(int i=1;i<=9;i++)
{
    JButton btn = new JButton(String.valueOf(i));
    btn.setBackground(Color.BLACK);
    btn.setForeground(Color.GRAY);
    p3.add(btn);
}

How to get the full url in Express?

You can use this function in the route like this

app.get('/one/two', function (req, res) {
    const url = getFullUrl(req);
}

/**
 * Gets the self full URL from the request
 * 
 * @param {object} req Request
 * @returns {string} URL
 */
const getFullUrl = (req) => `${req.protocol}://${req.headers.host}${req.originalUrl}`;

req.protocol will give you http or https, req.headers.host will give you the full host name like www.google.com, req.originalUrl will give the rest pathName(in your case /one/two)

Change column type in pandas

How about this?

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]: 
  one  two three
0   a  1.2   4.2
1   b   70  0.03
2   x    5     0

df.dtypes
Out[17]: 
one      object
two      object
three    object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes
Out[19]: 
one       object
two      float64
three    float64

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had this issue after migrating from spring-boot-starter-data-jpa ver. 1.5.7 to 2.0.2 (from old hibernate to hibernate 5.2). In my @Configuration class I injected entityManagerFactory and transactionManager.

//I've got my data source defined in application.yml config file, 
//so there is no need to configure it from java.
@Autowired
DataSource dataSource;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    //JpaVendorAdapteradapter can be autowired as well if it's configured in application properties.
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(false);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    //Add package to scan for entities.
    factory.setPackagesToScan("com.company.domain");
    factory.setDataSource(dataSource);
    return factory;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory);
    return txManager;
}

Also remember to add hibernate-entitymanager dependency to pom.xml otherwise EntityManagerFactory won't be found on classpath:

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.0.12.Final</version>
</dependency>

Can you do a For Each Row loop using MySQL?

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

How do I perform a Perl substitution on a string while keeping the original?

I hate foo and bar .. who dreamed up these non descriptive terms in programming anyway?

my $oldstring = "replace donotreplace replace donotreplace replace donotreplace";

my $newstring = $oldstring;
$newstring =~ s/replace/newword/g; # inplace replacement

print $newstring;
%: newword donotreplace newword donotreplace newword donotreplace

Plot multiple columns on the same graph in R

Using tidyverse

df %>% tidyr::gather("id", "value", 1:4) %>% 
  ggplot(., aes(Xax, value))+
  geom_point()+
  geom_smooth(method = "lm", se=FALSE, color="black")+
  facet_wrap(~id)

DATA

df<- read.table(text =c("
A       B       C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23"), header = T)

Bulk Insert Correctly Quoted CSV File in SQL Server

I had the same problem, however, it worked for me with the following settings:

bulk insert schema.table
from '\\your\data\source.csv'
with (
datafiletype = 'char'
,format = 'CSV'
,firstrow = 2
,fieldterminator = '|'
,rowterminator = '\n'
,tablock
)

My CSV-File looks like this:

"col1"|"col2"
"val1"|"val2"
"val3"|"val4"

My problem was, I had rowterminator set to '0x0a' before, it did not work. Once I changed it to '\n', it started working...

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Just use:TextBox1.Clear() It will work fine.

Creating a comma separated list from IList<string> or IEnumerable<string>

Something a bit fugly, but it works:

string divisionsCSV = String.Join(",", ((List<IDivisionView>)divisions).ConvertAll<string>(d => d.DivisionID.ToString("b")).ToArray());

Gives you a CSV from a List after you give it the convertor (in this case d => d.DivisionID.ToString("b")).

Hacky but works - could be made into an extension method perhaps?

Can a PDF file's print dialog be opened with Javascript?

Just figured out how to do this within the PDF itself - if you have acrobat pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose "run a javascript". Then in the javascript window, type this:

this.print({bUI: false, bSilent: true, bShrinkToFit: true});

This will print your document without a dialogue to the default printer on your machine. If you want the print dialog, just change bUI to true, bSilent to false, and optionally, remove the shrink to fit parameter.

Auto-printing PDF!

How to change the Text color of Menu item in Android?

You can change the color of the MenuItem text easily by using SpannableString instead of String.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.your_menu, menu);

    int positionOfMenuItem = 0; // or whatever...
    MenuItem item = menu.getItem(positionOfMenuItem);
    SpannableString s = new SpannableString("My red MenuItem");
    s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0);
    item.setTitle(s);
}

Google Maps V3 marker with label

Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.

You can now create your label marker like this:

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(result.latitude, result.longitude), 
  icon: markerIcon,
  label: {
    text: 'A'
  }
});

If you would like to see the 1 character restriction removed, please vote for this issue.

Update October 2016:

This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.

SQL Server copy all rows from one table into another i.e duplicate table

Don't have sql server around to test but I think it's just:

insert into newtable select * from oldtable;

How do I create a HTTP Client Request with a cookie?

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

To perform a request with a cookie attached just do the following:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

This originally answered a supplemental question about the wisdom of downloading jQuery versus accessing it via a CDN, which is no longer present...

To answer the thing about Google. I have moved over to accessing JQuery and most other of these sorts of libraries via the corresponding CDN in my sites.

As more people do this means that it's more likely to be cached on user's machines, so my vote goes for good idea.

In the five years since I first offered this, it has become common wisdom.

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

How to Convert the value in DataTable into a string array in c#

    private string[] GetPrimaryKeysofTable(string TableName)
    {
        string stsqlCommand = "SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
                              "WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1" +
                              "AND table_name = '" +TableName+ "'";
        SqlCommand command = new SqlCommand(stsqlCommand, Connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        adapter.Fill(table);

        string[] result = new string[table.Rows.Count];
        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            result[i++] = dr[0].ToString();
        }

        return result;
    }

Returning Arrays in Java

As Luiggi mentioned you need to change your main to:

import java.util.Arrays;

public class trial1{

    public static void main(String[] args){
        int[] A = numbers();
        System.out.println(Arrays.toString(A)); //Might require import of util.Arrays
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}

Checking for a null object in C++

  • What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
  • Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)

No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.

  • Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?

If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:

int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
  /* Take up to three ints and return the sum of any supplied values.

  Pass null pointers for "not supplied".

  This is NOT an example of good code.
  */
  if (!pa && (pb || pc)) return silly_sum(pb, pc);
  if (!pb && pc) return silly_sum(pa, pc);
  if (pc) return silly_sum(pa, pb) + *pc;
  if (pa && pb) return *pa + *pb;
  if (pa) return *pa;
  if (pb) return *pb;
  return 0;
}

int main() {
  int a = 1, b = 2, c = 3;
  cout << silly_sum(&a, &b, &c) << '\n';
  cout << silly_sum(&a, &b) << '\n';
  cout << silly_sum(&a) << '\n';
  cout << silly_sum(0, &b, &c) << '\n';
  cout << silly_sum(&a, 0, &c) << '\n';
  cout << silly_sum(0, 0, &c) << '\n';
  return 0;
}

If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.

You can use something like boost::optional.

jQuery: get the file name selected from <input type="file" />

I had used following which worked correctly.

$('#fileAttached').attr('value', $('#attachment').val())

ORDER BY the IN value list

To do this, I think you should probably have an additional "ORDER" table which defines the mapping of IDs to order (effectively doing what your response to your own question said), which you can then use as an additional column on your select which you can then sort on.

In that way, you explicitly describe the ordering you desire in the database, where it should be.

Calculating frames per second in a game

In (c++ like) pseudocode these two are what I used in industrial image processing applications that had to process images from a set of externally triggered camera's. Variations in "frame rate" had a different source (slower or faster production on the belt) but the problem is the same. (I assume that you have a simple timer.peek() call that gives you something like the nr of msec (nsec?) since application start or the last call)

Solution 1: fast but not updated every frame

do while (1)
{
    ProcessImage(frame)
    if (frame.framenumber%poll_interval==0)
    {
        new_time=timer.peek()
        framerate=poll_interval/(new_time - last_time)
        last_time=new_time
    }
}

Solution 2: updated every frame, requires more memory and CPU

do while (1)
{
   ProcessImage(frame)
   new_time=timer.peek()
   delta=new_time - last_time
   last_time = new_time
   total_time += delta
   delta_history.push(delta)
   framerate= delta_history.length() / total_time
   while (delta_history.length() > avg_interval)
   {
      oldest_delta = delta_history.pop()
      total_time -= oldest_delta
   }
} 

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Using regular expression in css?

You can manage selecting those elements without any form of regex as the previous answers show, but to answer the question directly, yes you can use a form of regex in selectors:

#sections div[id^='s'] {
    color: red;  
}

That says select any div elements inside the #sections div that have an ID starting with the letter 's'.

See fiddle here.

W3 CSS selector docs here.

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

I am using Chrome version 75.

add the muted property to video tag

<video id="myvid" muted>

then play it using javascript and set muted to false

var myvideo = document.getElementById("myvid");
myvideo.play();
myvideo.muted = false;

edit: need user interaction (at least click anywhere in the page to work)

Xcode Debugger: view value of variable

You can print values onto console window at run-time. Below are steps :

  1. Place a break-point for which you want to get values
  2. Now perform step-by-step debug.
  3. Place a cursor on variable/delegate whose value is to be checked at run-time.
  4. Now this will show description of variable/delegate
  5. Clicking on "i" will show detailed description
  6. This will also print details onto console window.

Screenshot for printing details on console window

Returning multiple objects in an R function

You could use for() with assign() to create many objects. See the example from assign():

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
    nam <- paste("r", i, sep = ".")
    assign(nam, 1:i)

Looking the new objects

ls(pattern = "^r..$")

Use of var keyword in C#

"The only thing you can really say about my taste is that it is old fashioned, and in time yours will be too." -Tolkien.

EditText, clear focus on touch outside

For Me Below things Worked -

1.Adding android:clickable="true" and android:focusableInTouchMode="true" to the parentLayout of EditTexti.e android.support.design.widget.TextInputLayout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusableInTouchMode="true">
<EditText
    android:id="@+id/employeeID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number"
    android:hint="Employee ID"
    tools:layout_editor_absoluteX="-62dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_marginTop="42dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="36dp"
    android:layout_marginEnd="36dp" />
    </android.support.design.widget.TextInputLayout>

2.Overriding dispatchTouchEvent in Activity class and inserting hideKeyboard() function

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null && view instanceof EditText) {
                Rect r = new Rect();
                view.getGlobalVisibleRect(r);
                int rawX = (int)ev.getRawX();
                int rawY = (int)ev.getRawY();
                if (!r.contains(rawX, rawY)) {
                    view.clearFocus();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

3.Adding setOnFocusChangeListener for EditText

EmployeeId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });

How to turn NaN from parseInt into 0 for an empty string?

For people who are not restricted to parseInt, you can use the bitwise OR operator (which implicitly calls ToInt32 to its operands).

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

Note: ToInt32 is different from parseInt. (i.e. parseInt('33Ab') === 33)

AngularJS: Can't I set a variable value on ng-click?

You can use some thing like this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
    <p>_x000D_
      <input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
    </p>_x000D_
    <p>_x000D_
      <button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
    </p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What does '--set-upstream' do?

When you push to a remote and you use the --set-upstream flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.

Adding a remote tracking branch means that git then knows what you want to do when you git fetch, git pull or git push in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.

You could achieve the same thing with git branch --set-upstream-to or git checkout --track. See the git help pages on tracking branches for more information.

TransactionRequiredException Executing an update/delete query

I am not sure if this will help your situation (that is if it stills exists), however, after scouring the web for a similar issue.

I was creating a native query from a persistence EntityManager to perform an update.

Query query = entityManager.createNativeQuery(queryString);

I was receiving the following error:

caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query

Many solutions suggest adding @Transactional to your method. Just doing this did not change the error.

Some solutions suggest asking the EntityManager for a EntityTransaction so that you can call begin and commit yourself. This throws another error:

caused by: java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead

I then tried a method which most sites say is for use application managed entity managers and not container managed (which I believe Spring is) and that was joinTransaction().

Having @Transactional decorating the method and then calling joinTransaction() on EntityManager object just prior to calling query.executeUpdate() and my native query update worked.

I hope this helps someone else experiencing this issue.

How do I convert a byte array to Base64 in Java?

Use:

byte[] data = Base64.encode(base64str);

Encoding converts to Base64

You would need to reference commons codec from your project in order for that code to work.

For java8:

import java.util.Base64

How do I Merge two Arrays in VBA?

Unfortunately, the Array type in VB6 didn't have all that many razzmatazz features. You are pretty much going to have to just iterate through the arrays and insert them manually into the third

Assuming both arrays are of the same length

Dim arr1() As Variant
Dim arr2() As Variant
Dim arr3() As Variant

arr1() = Array("A", 1, "B", 2)
arr2() = Array("C", 3, "D", 4)

ReDim arr3(UBound(arr1) + UBound(arr2) + 1)

Dim i As Integer
For i = 0 To UBound(arr1)
    arr3(i * 2) = arr1(i)
    arr3(i * 2 + 1) = arr2(i)
Next i

Updated: Fixed the code. Sorry about the previous buggy version. Took me a few minutes to get access to a VB6 compiler to check it.

How to convert between bytes and strings in Python 3?

This is a Python 101 type question,

It's a simple question but one where the answer is not so simple.


In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.

To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.

Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.

If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.

print(bytesThing)

Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.

Spring RestTemplate timeout

For Spring Boot >= 1.4

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
    {
        return restTemplateBuilder
           .setConnectTimeout(...)
           .setReadTimeout(...)
           .build();
    }
}

For Spring Boot <= 1.3

@Configuration
public class AppConfig
{
    @Bean
    @ConfigurationProperties(prefix = "custom.rest.connection")
    public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() 
    {
        return new HttpComponentsClientHttpRequestFactory();
    }

    @Bean
    public RestTemplate customRestTemplate()
    {
        return new RestTemplate(customHttpRequestFactory());
    }
}

then in your application.properties

custom.rest.connection.connection-request-timeout=...
custom.rest.connection.connect-timeout=...
custom.rest.connection.read-timeout=...

This works because HttpComponentsClientHttpRequestFactory has public setters connectionRequestTimeout, connectTimeout, and readTimeout and @ConfigurationProperties sets them for you.


For Spring 4.1 or Spring 5 without Spring Boot using @Configuration instead of XML

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate customRestTemplate()
    {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(...);
        httpRequestFactory.setConnectTimeout(...);
        httpRequestFactory.setReadTimeout(...);

        return new RestTemplate(httpRequestFactory);
    }
}

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

How to remove line breaks from a file in Java?

You need to set text to the results of text.replace():

String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

This is necessary because Strings are immutable -- calling replace doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text, then that new String is lost and garbage collected.

As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator").

Why do I need to explicitly push a new branch?

At first check

Step-1: git remote -v
//if found git initialize then remove or skip step-2

Step-2: git remote rm origin
//Then configure your email address globally git

Step-3: git config --global user.email "[email protected]"

Step-4: git initial

Step-5: git commit -m "Initial Project"
//If already add project repo then skip step-6

Step-6: git remote add origin %repo link from bitbucket.org%

Step-7: git push -u origin master

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

Selenium Webdriver: Entering text into text field

Agree with Subir Kumar Sao and Faiz.

element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);

How to implement endless list with RecyclerView?

Thanks to @Kushal and this is how I implemented it

private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (dy > 0) { //check for scroll down
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading) {
                if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                    loading = false;
                    Log.v("...", "Last Item Wow !");
                    // Do pagination.. i.e. fetch new data

                    loading = true;
                }
            }
        }
    }
});

Don't forget to add

LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

I am not sure about this tutorial but I had the same problem when I forgot to include the file into grunt/gulp minimization process.

grunt.initConfig({
  uglify: {
    my_target: {
      files: {
        'dest/output.min.js': ['src/input1.js', 'src/missing_controller.js']
      }
    }
  }
});

Hope that helps.

Working with time DURATION, not time of day

Highlight the cell(s)/column which you want as Duration, right click on the mouse to "Format Cells". Go to "Custom" and look for "h:mm" if you want to input duration in hour and minutes format. If you want to include seconds as well, click on "h:mm:ss". You can even add up the total duration after that.

Hope this helps.

How to negate a method reference predicate

In this case u could use the org.apache.commons.lang3.StringUtilsand do

int nonEmptyStrings = s.filter(StringUtils::isNotEmpty).count();

Convert ascii char[] to hexadecimal char[] in C

replace this

printf("%c",word[i]);

by

printf("%02X",word[i]);

How to get the current time as datetime

Update for Swift 3:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

What is the main difference between PATCH and PUT request?

There are limitations in PUT over PATCH while making updates. Using PUT requires us to specify all attributes even if we want to change only one attribute. But if we use the PATCH method we can update only the fields we need and there is no need to mention all the fields. PATCH does not allow us to modify a value in an array, or remove an attribute or array entry.

Can (domain name) subdomains have an underscore "_" in it?

No, you can't use underscore in subdomain but hypen (dash). i.e my-subdomain.agahost.com is acceptable and my_subdomain.agahost.com would not be acceptable.

How to uninstall Golang?

For Windows 10:

  1. Go to Apps in the Settings App.
  2. Look for Go Programming Language * in the list and uninstall it.
  3. Remove C:\Go\bin from your PATH environment variable (only if you don't plan on installing another version of golang)

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

In my case this was caused by an integer overflow. I had a UInt16, and was doubling the value to put into an Int. The faulty code was

let result = Int(myUInt16 * 2)

However, this multiplies as a UInt16, then converts to Int. So if myUInt16 contains a value over 32767 then an overflow occurs.

All was well once I corrected the code to

let result = Int(myUint16) * 2

Copy tables from one database to another in SQL Server

If it’s one table only then all you need to do is

  • Script table definition
  • Create new table in another database
  • Update rules, indexes, permissions and such
  • Import data (several insert into examples are already shown above)

One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.

Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.

Sass Variable in CSS calc() function

you can use your verbal #{your verbal}

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

Do I need a content-type header for HTTP GET requests?

According to the RFC 7231 section 3.1.5.5:

A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender. If a Content-Type header field is not present, the recipient MAY either assume a media type of "application/octet-stream" ([RFC2046], Section 4.5.1) or examine the data to determine its type.

It means that the Content-Type HTTP header should be set only for PUT and POST requests.

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

No, but you should be careful when using IF...ELSE...END IF in stored procs. If your code blocks are radically different, you may suffer from poor performance because the procedure plan will need to be re-cached each time. If it's a high-performance system, you may want to compile separate stored procs for each code block, and have your application decide which proc to call at the appropriate time.

How do I plot list of tuples in Python?

You could also use zip

import matplotlib.pyplot as plt

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x, y = zip(*l)

plt.plot(x, y)

How can I use a local image as the base image with a dockerfile?

Remember to put not only the tag but also the repository in which that tag is, this way:

docker images
REPOSITORY                                TAG                       IMAGE ID            CREATED             SIZE
elixir                                    1.7-centos7_3             e15e6bf57262        20 hours ago        925MB

You should reference it this way:

elixir:1.7-centos7_3

How to view UTF-8 Characters in VIM or Gvim

Did you try

:set encoding=utf-8
:set fileencoding=utf-8

?

Sort Go map values by keys

In reply to James Craig Burley's answer. In order to make a clean and re-usable design, one might choose for a more object oriented approach. This way methods can be safely bound to the types of the specified map. To me this approach feels cleaner and organized.

Example:

package main

import (
    "fmt"
    "sort"
)

type myIntMap map[int]string

func (m myIntMap) sort() (index []int) {
    for k, _ := range m {
        index = append(index, k)
    }
    sort.Ints(index)
    return
}

func main() {
    m := myIntMap{
        1:  "one",
        11: "eleven",
        3:  "three",
    }
    for _, k := range m.sort() {
        fmt.Println(m[k])
    }
}

Extended playground example with multiple map types.

Important note

In all cases, the map and the sorted slice are decoupled from the moment the for loop over the map range is finished. Meaning that, if the map gets modified after the sorting logic, but before you use it, you can get into trouble. (Not thread / Go routine safe). If there is a change of parallel Map write access, you'll need to use a mutex around the writes and the sorted for loop.

mutex.Lock()
for _, k := range m.sort() {
    fmt.Println(m[k])
}
mutex.Unlock()

Is there a WebSocket client implemented for Python?

http://pypi.python.org/pypi/websocket-client/

Ridiculously easy to use.

 sudo pip install websocket-client

Sample client code:

#!/usr/bin/python

from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result =  ws.recv()
print "Received '%s'" % result
ws.close()

Sample server code:

#!/usr/bin/python
import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(30000):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

Check if url contains string with JQuery

use href with indexof

<script type="text/javascript">
 $(document).ready(function () {
   if(window.location.href.indexOf("added-to-cart=555") > -1) {
   alert("your url contains the added-to-cart=555");
  }
});
</script>

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

How to format a number 0..9 to display with 2 digits (it's NOT a date)

In android resources it's rather simple

<string name="smth">%1$02d</string>

How do you calculate log base 2 in Java for integers?

To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :

public static int ceilbinlog(int number) // returns 0 for bits=0
{
    int log = 0;
    int bits = number;
    if ((bits & 0xffff0000) != 0) {
        bits >>>= 16;
        log = 16;
    }
    if (bits >= 256) {
        bits >>>= 8;
        log += 8;
    }
    if (bits >= 16) {
        bits >>>= 4;
        log += 4;
    }
    if (bits >= 4) {
        bits >>>= 2;
        log += 2;
    }
    if (1 << log < number)
        log++;
    return log + (bits >>> 1);
}

Getting the difference between two sets

You can use CollectionUtils.disjunction to get all differences or CollectionUtils.subtract to get the difference in the first collection.

Here is an example of how to do that:

    var collection1 = List.of(1, 2, 3, 4, 5);
    var collection2 = List.of(2, 3, 5, 6);
    System.out.println(StringUtils.join(collection1, " , "));
    System.out.println(StringUtils.join(collection2, " , "));
    System.out.println(StringUtils.join(CollectionUtils.subtract(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.retainAll(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.collate(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.disjunction(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.intersection(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.union(collection1, collection2), " , "));

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Comment shortcut Android Studio

In spanish keyboard without changing anything I can make a comment with the keys:

cmd + -

OR

cmd + alt + -

This works because in english keyboard / is located at the same place than - on a spanish keyboard

Prevent HTML5 video from being downloaded (right-click saved)?

Simple answer,

YOU CAN'T

If they are watching your video, they have it already

You can slow them down but can't stop them.

Android SQLite: Update Statement

It's all in the tutorial how to do that:

    ContentValues args = new ContentValues();
    args.put(columnName, newValue);
    db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);

Use ContentValues to set the updated columns and than the update() method in which you have to specifiy, the table and a criteria to only update the rows you want to update.

How do I close a single buffer (out of many) in Vim?

Rather than browse the ouput of the :ls command and delete (unload, wipe..) a buffer by specifying its number, I find that using file names is often more effective.

For instance, after I opened a couple of .txt file to refresh my memories of some fine point.. copy and paste a few lines of text to use as a template of sorts.. etc. I would type the following:

:bd txt <Tab>

Note that the matching string does not have to be at the start of the file name.

The above displays the list of file names that match 'txt' at the bottom of the screen and keeps the :bd command I initially typed untouched, ready to be completed.

Here's an example:

doc1.txt doc2.txt
:bd txt 

I could backspace over the 'txt' bit and type in the file name I wish to delete, but where this becomes really convenient is that I don't have to: if I hit the Tab key a second time, Vim automatically completes my command with the first match:

:bd doc1.txt

If I want to get rid of this particular buffer I just need to hit Enter.

And if the buffer I want to delete happens to be the second (third.. etc.) match, I only need to keep hitting the Tab key to make my :bd command cycle through the list of matches.

Naturally, this method can also be used to switch to a given buffer via such commands as :b.. :sb.. etc.

This approach is particularly useful when the 'hidden' Vim option is set, because the buffer list can quickly become quite large, covering several screens, and making it difficult to spot the particular buffer I am looking for.

To make the most of this feature, it's probably best to read the following Vim help file and tweak the behavior of Tab command-line completion accordingly so that it best suits your workflow:

:help wildmode

The behavior I described above results from the following setting, which I chose for consistency's sake in order to emulate bash completion:

:set wildmode=list:longest,full

As opposed to using buffer numbers, the merit of this approach is that I usually remember at least part of a given file name letting me target the buffer directly rather than having to first look up its number via the :ls command.

How to create a zip file in Java

public static void zipFromTxt(String zipFilePath, String txtFilePath) {
    Assert.notNull(zipFilePath, "Zip file path is required");
    Assert.notNull(txtFilePath, "Txt file path is required");
    zipFromTxt(new File(zipFilePath), new File(txtFilePath));
}

public static void zipFromTxt(File zipFile, File txtFile) {
    ZipOutputStream out = null;
    FileInputStream in = null;
    try {
        Assert.notNull(zipFile, "Zip file is required");
        Assert.notNull(txtFile, "Txt file is required");
        out = new ZipOutputStream(new FileOutputStream(zipFile));
        in = new FileInputStream(txtFile);
        out.putNextEntry(new ZipEntry(txtFile.getName()));
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
    } catch (Exception e) {
        log.info("Zip from txt occur error,Detail message:{}", e.toString());
    } finally {
        try {
            if (in != null) in.close();
            if (out != null) {
                out.closeEntry();
                out.close();
            }
        } catch (Exception e) {
            log.info("Zip from txt close error,Detail message:{}", e.toString());
        }
    }
}

Create a Date with a set timezone without using a string representation

any mileage in

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

Make git automatically remove trailing whitespace before committing

Those settings (core.whitespace and apply.whitespace) are not there to remove trailing whitespace but to:

  • core.whitespace: detect them, and raise errors
  • apply.whitespace: and strip them, but only during patch, not "always automatically"

I believe the git hook pre-commit would do a better job for that (includes removing trailing whitespace)


Note that at any given time you can choose to not run the pre-commit hook:

  • temporarily: git commit --no-verify .
  • permanently: cd .git/hooks/ ; chmod -x pre-commit

Warning: by default, a pre-commit script (like this one), has not a "remove trailing" feature", but a "warning" feature like:

if (/\s$/) {
    bad_line("trailing whitespace", $_);
}

You could however build a better pre-commit hook, especially when you consider that:

Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.


For instance, oldman proposes in another answer a pre-commit hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md (markdown) files!

How to get access token from FB.login method in javascript SDK

You can get access token using FB.getAuthResponse()['accessToken']:

FB.login(function(response) {
   if (response.authResponse) {
     var access_token =   FB.getAuthResponse()['accessToken'];
     console.log('Access Token = '+ access_token);
     FB.api('/me', function(response) {
     console.log('Good to see you, ' + response.name + '.');
     });
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 }, {scope: ''});

Edit: Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse(); If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:

if (typeof(console) == "undefined") { console = {}; } 
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }

Subscript out of range error in this Excel VBA script

This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.

Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")

Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:

sh1.Range("A69").Paste
sh1.Range("A69").Select

The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

This worked for me:

sudo add-apt-repository ppa:sun-java-community-team/sun-java6

sudo apt-get update

sudo apt-get install sun-java6-jre sun-java6-jdk

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

Error inflating class android.support.design.widget.NavigationView

I also had same error. In my case some of the resources were in drawable-v21 only. Copy those resources to drawable folder also. This solved the issue for me.

Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0 

This is the main problem.

Best place to insert the Google Analytics code

Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

JavaFX and OpenJDK

As a quick solution you can copy the JavaFX runtime JAR file and those referenced from Oracle JRE(JDK) or any self-contained application that uses JavaFX(e.g. JavaFX Scene Builder 2.0):

cp <JRE_WITH_JAVAFX_HOME>/lib/ext/jfxrt.jar     <JRE_HOME>/lib/ext/
cp <JRE_WITH_JAVAFX_HOME>/lib/javafx.properties <JRE_HOME>/lib/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libprism_*  <JRE_HOME>/lib/amd64/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libglass.so <JRE_HOME>/lib/amd64/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libjavafx_* <JRE_HOME>/lib/amd64/

just make sure you have the gtk 2.18 or higher

How do I compare two DateTime objects in PHP 5.2.8?

You can also compare epoch seconds :

$d1->format('U') < $d2->format('U')

Source : http://laughingmeme.org/2007/02/27/looking-at-php5s-datetime-and-datetimezone/ (quite interesting article about DateTime)

What's the equivalent of Java's Thread.sleep() in JavaScript?

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

CORS with POSTMAN

As @Musa comments it, it seems that the reason is that:

Postman doesn't care about SOP, it's a dev tool not a browser

By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).

Check here if you want to learn more about Cross-Origin and why it's working for extensions.

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

console.log not working in Angular2 Component (Typescript)

It's not working because console.log() it's not in a "executable area" of the class "App".

A class is a structure composed by attributes and methods.

The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()

_x000D_
_x000D_
console.log('It works here')_x000D_
_x000D_
@Component({..)_x000D_
export class App {_x000D_
 s: string = "Hello2";_x000D_
            _x000D_
  constructor() {_x000D_
    console.log(this.s)            _x000D_
  }            _x000D_
}
_x000D_
_x000D_
_x000D_

Think of class like a plain javascript object.

Would it make sense to expect this to work?

_x000D_
_x000D_
class:  {_x000D_
  s: string,_x000D_
  console.log(s)_x000D_
 }
_x000D_
_x000D_
_x000D_

If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.

https://www.typescriptlang.org/play/index.html

"No rule to make target 'install'"... But Makefile exists

I also came across the same error. Here is the fix: If you are using Cmake-GUI:

  1. Clean the cache of the loaded libraries in Cmake-GUI File menu.
  2. Configure the libraries.
  3. Generate the Unix file.

If you missed the 3rd step:

*** No rule to make target `install'. Stop.

error will occur.

How to Disable landscape mode in Android?

A lot of the answers here are suggesting to use "portrait" in your AndroidManifest.xml file. This might seem like a good solution - but as noted in the documentation, you are singling out devices that may only have landscape. You are also forcing certain devices (that work best in landscape) to go into portrait, not getting the proper orientation.

My suggestion is to use "nosensor" instead. This will leave the device to use its default preferred orientation, will not block any purchases/downloads on Google Play, and will ensure the sensor doesn't mess up your (NDK, in my case) game.

gcc makefile error: "No rule to make target ..."

In my case the path is not set in VPATH, after added the error gone.

ERROR: Google Maps API error: MissingKeyMapError

you must create a project and collect the key in this way:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;language=en&key=()"></script>

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

Difference between PCDATA and CDATA in DTD

CDATA (Character DATA): It is similarly to a comment but it is part of document. i.e. CDATA is a data, it is part of the document but the data can not parsed in XML.
Note: XML comment omits while parsing an XML but CDATA shows as it is.

PCDATA (Parsed Character DATA) :By default, everything is PCDATA. PCDATA is a data, it can be parsed in XML.

Facebook key hash does not match any stored key hashes

I encountered a similar problem. The solution is surprisingly simple.

The error message looks like this:

07-05 ...... Invalid key hash. The key hash sL1***************VY= does not match any stored key hashes. Configure your app key hashes at http://developers.facebook.com/apps/150*******778
07-05 ......     at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:191)

Simply log into https://developers.facebook.com , select the "Settings" tab, and add the key hash "sL1***************VY=" to the list of saved Key hashes in the Android panel.

Keyboard shortcuts with jQuery

    <script type="text/javascript">
        $(document).ready(function(){
            $("#test").keypress(function(e){
                if (e.which == 103) 
                {
                    alert('g'); 
                };
            });
        });
    </script>

    <input type="text" id="test" />

this site says 71 = g but the jQuery code above thought otherwise

Capital G = 71, lowercase is 103

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

Get all Attributes from a HTML element with Javascript/jQuery

Imagine you've got an HTML element like below:

<a class="toc-item"
   href="/books/n/ukhta2333/s5/"
   id="book-link-29"
>
   Chapter 5. Conclusions and recommendations
</a>

One way you can get all attributes of it is to convert them into an array:

const el = document.getElementById("book-link-29")
const attrArray = Array.from(el.attributes)

// Now you can iterate all the attributes and do whatever you need.
const attributes = attrArray.reduce((attrs, attr) => {
    attrs !== '' && (attrs += ' ')
    attrs += `${attr.nodeName}="${attr.nodeValue}"`
    return attrs
}, '')
console.log(attributes)

And below is the string that what you'll get (from the example), which includes all attributes:

class="toc-item" href="/books/n/ukhta2333/s5/" id="book-link-29"

Creating layout constraints programmatically

Swift version

Updated for Swift 3

This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:

Width and Height

enter image description here

Center in Container

enter image description here

Boilerplate code

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here (choose one of the methods below)
    // ...
}

Method 1: Anchor Style

// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true

// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true

// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • See also the Programmatically Creating Constraints documentation.
  • See this answer for a similar example of adding a pinning constraint.

Reactjs - setting inline styles correctly

You need to do this:

var scope = {
     splitterStyle: {
         height: 100
     }
};

And then apply this styling to the required elements:

<div id="horizontal" style={splitterStyle}>

In your code you are doing this (which is incorrect):

<div id="horizontal" style={height}>

Where height = 100.

How would I find the second largest salary from the employee table?

Maybe you should use DENSE_RANK.

SELECT *
FROM (
       SELECT
         [Salary],
         (DENSE_RANK()
         OVER
         (
           ORDER BY [Salary] DESC)) AS rnk
       FROM [Table1]
       GROUP BY [Num]
     ) AS A
WHERE A.rnk = 2

Angular 2: import external js file into component

Here is a simple way i did it in my project.

lets say you need to use clipboard.min.js and for the sake of the example lets say that inside clipboard.min.js there is a function that called test2().

in order to use test2() function you need:

  1. make a reference to the .js file inside you index.html.
  2. import clipboard.min.js to your component.
  3. declare a variable that will use you to call the function.

here are only the relevant parts from my project (see the comments):

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>


    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>

    <!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
    <script src="app/txtzone/clipboard.min.js"></script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

app.component.ts:

import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],
})



export class TxtZoneComponent implements AfterViewInit {

    // call test2
    callTest2()
    {   
        new test2(); // the javascript function will execute
    }

}

Best way to show a loading/progress indicator?

Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".

Currently the recommended method is to use a DialogFragment :

public class MySpinnerDialog extends DialogFragment {

    public MySpinnerDialog() {
        // use empty constructors. If something is needed use onCreate's
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        _dialog = new ProgressDialog(getActivity());
        this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
        _dialog.setMessage("Spinning.."); // set your messages if not inflated from XML

        _dialog.setCancelable(false);  

        return _dialog;
    }
}

Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:

FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");

Once your server has responded complete you will dismiss it:

myInstance.dismiss()

Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

How can I detect the touch event of an UIImageView?

Add gesture on that view. Add an image into that view, and then it would be detecting a gesture on the image too. You could try with the delegate method of the touch event. Then in that case it also might be detecting.

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

Dynamically set value of a file input

I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

In Java, how do I call a base class's method from the overriding method in a derived class?

Answer is as follows:

super.Mymethod();
super();                // calls base class Superclass constructor.
super(parameter list);          // calls base class parameterized constructor.
super.method();         // calls base class method.

What does the Java assert keyword do, and when should it be used?

An assertion allows for detecting defects in the code. You can turn on assertions for testing and debugging while leaving them off when your program is in production.

Why assert something when you know it is true? It is only true when everything is working properly. If the program has a defect, it might not actually be true. Detecting this earlier in the process lets you know something is wrong.

An assert statement contains this statement along with an optional String message.

The syntax for an assert statement has two forms:

assert boolean_expression;
assert boolean_expression: error_message;

Here are some basic rules which govern where assertions should be used and where they should not be used. Assertions should be used for:

  1. Validating input parameters of a private method. NOT for public methods. public methods should throw regular exceptions when passed bad parameters.

  2. Anywhere in the program to ensure the validity of a fact which is almost certainly true.

For example, if you are sure that it will only be either 1 or 2, you can use an assertion like this:

...
if (i == 1)    {
    ...
}
else if (i == 2)    {
    ...
} else {
    assert false : "cannot happen. i is " + i;
}
...
  1. Validating post conditions at the end of any method. This means, after executing the business logic, you can use assertions to ensure that the internal state of your variables or results is consistent with what you expect. For example, a method that opens a socket or a file can use an assertion at the end to ensure that the socket or the file is indeed opened.

Assertions should not be used for:

  1. Validating input parameters of a public method. Since assertions may not always be executed, the regular exception mechanism should be used.

  2. Validating constraints on something that is input by the user. Same as above.

  3. Should not be used for side effects.

For example this is not a proper use because here the assertion is used for its side effect of calling of the doSomething() method.

public boolean doSomething() {
...    
}
public void someMethod() {       
assert doSomething(); 
}

The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code:   

boolean enabled = false;    
assert enabled = true;    
if (enabled) {
    System.out.println("Assertions are enabled");
} else {
    System.out.println("Assertions are disabled");
}

Using the "start" command with parameters passed to the started program

have you tried:

start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" "-pc MY-PC -launch"

?

Update TextView Every Second

Extending @endian 's answer, you could use a thread and call a method to update the TextView. Below is some code I made up on the spot.

java.util.Date noteTS;
String time, date;
TextView tvTime, tvDate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.deskclock);

    tvTime = (TextView) findViewById(R.id.tvTime);
    tvDate = (TextView) findViewById(R.id.tvDate);

    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateTextView();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
}

private void updateTextView() {
    noteTS = Calendar.getInstance().getTime();

    String time = "hh:mm"; // 12:00
    tvTime.setText(DateFormat.format(time, noteTS));

    String date = "dd MMMMM yyyy"; // 01 January 2013
    tvDate.setText(DateFormat.format(date, noteTS));
}

NGinx Default public www location?

Alpine Linux does not have any default location at all. The file /etc/nginx/conf.d/default.conf says:

# Everything is a 404
location / {
    return 404;
}

# You may need this to prevent return 404 recursion.
location = /404.html {
    internal;
}

Replace those with a line like root /var/www/localhost/htdocs to point to the directory you want. Then sudo service nginx restart to restart.

Removing All Items From A ComboBox?

The simplest way:

Combobox1.RowSource = ""  'Clear the list
Combobox1.Clear           'Clear the selected text

Dynamic type languages versus static type languages

There are lots of different things about static and dynamic languages. For me, the main difference is that in dynamic languages the variables don't have fixed types; instead, the types are tied to values. Because of this, the exact code that gets executed is undetermined until runtime.

In early or naïve implementations this is a huge performance drag, but modern JITs get tantalizingly close to the best you can get with optimizing static compilers. (in some fringe cases, even better than that).

How to add a default "Select" option to this ASP.NET DropDownList control?

If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.

How to load up CSS files using Javascript?

Here's a way with jQuery's element creation method (my preference) and with callback onLoad:

var css = $("<link>", {
  "rel" : "stylesheet",
  "type" :  "text/css",
  "href" : "style.css"
})[0];

css.onload = function(){
  console.log("CSS IN IFRAME LOADED");
};

document
  .getElementsByTagName("head")[0]
  .appendChild(css);

ReactJS: Maximum update depth exceeded error

You should pass the event object when calling the function :

{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}

If you don't need to handle onClick event you can also type :

{<td><span onClick={(e) => this.toggle()}>Details</span></td>}

Now you can also add your parameters within the function.

Use space as a delimiter with cut command

To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:

Two distinct mechanisms come into play here:

  • (a) whether cut itself requires the delimiter (space, in this case) passed to the -d option to be a separate argument or whether it's acceptable to append it directly to -d.

  • (b) how the shell generally parses arguments before passing them to the command being invoked.

(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)

If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.

In other words: In this case, because -d's option-argument is mandatory, you can choose whether to specify the delimiter as:

  • (s) EITHER: a separate argument
  • (d) OR: as a value directly attached to -d.

Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:

  • With approach (s), all of the following forms are EQUIVALENT:

    • -d ' '
    • -d " "
    • -d \<space> # <space> used to represent an actual space for technical reasons
  • With approach (d), all of the following forms are EQUIVALENT:

    • -d' '
    • -d" "
    • "-d "
    • '-d '
    • d\<space>

The equivalence is explained by the shell's string-literal processing:

All solutions above result in the exact same string (in each group) by the time cut sees them:

  • (s): cut sees -d, as its own argument, followed by a separate argument that contains a space char - without quotes or \ prefix!.

  • (d): cut sees -d plus a space char - without quotes or \ prefix! - as part of the same argument.

The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:

  • The shell allows literal to be specified as is through a mechanism called quoting, which can take several forms:
    • single-quoted strings: the contents inside '...' is taken literally and forms a single argument
    • double-quoted strings: the contents inside "..." also forms a single argument, but is subject to interpolation (expands variable references such as $var, command substitutions ($(...) or `...`), or arithmetic expansions ($(( ... ))).
    • \-quoting of individual characters: a \ preceding a single character causes that character to be interpreted as a literal.
  • Quoting is complemented by quote removal, which means that once the shell has parsed a command line, it removes the quote characters from the arguments (enclosing '...' or "..." or \ instances) - thus, the command being invoked never sees the quote characters.

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

Download a file by jQuery.Ajax

The simple way to make the browser downloads a file is to make the request like that:

 function downloadFile(urlToSend) {
     var req = new XMLHttpRequest();
     req.open("GET", urlToSend, true);
     req.responseType = "blob";
     req.onload = function (event) {
         var blob = req.response;
         var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
         var link=document.createElement('a');
         link.href=window.URL.createObjectURL(blob);
         link.download=fileName;
         link.click();
     };

     req.send();
 }

This opens the browser download pop up.

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

  • Tap on Windows-Pause to open the System Control Panel applet. You can alternatively open the control panel manual to go there if you prefer it that way. Click on advanced system settings on the left.
  • Select environmental variables here.
  • Click on new under System Variables.
  • Enter '_JAVA_OPTIONS' as the variable name.
  • Enter '-Xmx1024M' as the variable value.
  • Click ok twice.

Can't draw Histogram, 'x' must be numeric

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

and now you can do

 hist(we)

and other numeric operations.

Why can't decimal numbers be represented exactly in binary?

I'm surprised no one has stated this yet: use continued fractions. Any rational number can be represented finitely in binary this way.

Some examples:

1/3 (0.3333...)

0; 3

5/9 (0.5555...)

0; 1, 1, 4

10/43 (0.232558139534883720930...)

0; 4, 3, 3

9093/18478 (0.49209871198181621387596060179673...)

0; 2, 31, 7, 8, 5

From here, there are a variety of known ways to store a sequence of integers in memory.

In addition to storing your number with perfect accuracy, continued fractions also have some other benefits, such as best rational approximation. If you decide to terminate the sequence of numbers in a continued fraction early, the remaining digits (when recombined to a fraction) will give you the best possible fraction. This is how approximations to pi are found:

Pi's continued fraction:

3; 7, 15, 1, 292 ...

Terminating the sequence at 1, this gives the fraction:

355/113

which is an excellent rational approximation.

Add image in pdf using jspdf

I had the same issue with Base64 not being defined. I went to an online encoder and then saved the output into a variable. This probably is not ideal for many images, but for my needs it was sufficient.

function makePDF(){
    var doc = new jsPDF();
    var image = "data:image/png;base64,iVBORw0KGgoAA..";
    doc.addImage(image, 'JPEG', 15, 40, 180, 160);
    doc.save('title');
}

How to convert a multipart file to File?

You can get the content of a MultipartFile by using the getBytes method and you can write to the file using Files.newOutputStream():

public void write(MultipartFile file, Path dir) {
    Path filepath = Paths.get(dir.toString(), file.getOriginalFilename());

    try (OutputStream os = Files.newOutputStream(filepath)) {
        os.write(file.getBytes());
    }
}

You can also use the transferTo method:

public void multipartFileToFile(
    MultipartFile multipart, 
    Path dir
) throws IOException {
    Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename());
    multipart.transferTo(filepath);
}

Data truncated for column?

However I get an error which doesn't make sense seeing as the column's data type was properly modified?

| Level | Code | Msg | Warn | 12 | Data truncated for column 'incoming_Cid' at row 1

You can often get this message when you are doing something like the following:

REPLACE INTO table2 (SELECT * FROM table1);

Resulted in our case in the following error:

SQL Exception: Data truncated for column 'level' at row 1

The problem turned out to be column misalignment that resulted in a tinyint trying to be stored in a datetime field or vice versa.

Things possible in IntelliJ that aren't possible in Eclipse?

I not have coded a lot with IntellijIdea, but in IntellijIdea you can see where a block of code between brackets (if, try/catch, cycle, etc) begins and where finish.

In Eclipse (I code in Eclipse 3.2) you can identify the block only manually.

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

How to remove an element slowly with jQuery?

$target.hide('slow');

or

$target.hide('slow', function(){ $target.remove(); });

to run the animation, then remove it from DOM

How to download all dependencies and packages to directory

The aptitude --download-only ... approach only works if you have a debian distro with internet connection in your hands.

If you don't, I think it is better to run the following script on the disconnected debian machine:

apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list

move the downloads.list file into a connected linux (or non linux) machine, and run:

wget --input-file myurilist

this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.

credits: http://www.tuxradar.com/answers/517

PS I basically copied the blog post because it was not very readable, and in case the post will disappear.

How do I import material design library to Android Studio?

First, add the Material Design dependency.

implementation 'com.google.android.material:material:<version>'

To get the latest material design library version. check the official website github repository.

Current version is 1.2.0.

So, you have to add,

implementation 'com.google.android.material:material:1.2.0'

Then, you need to change the app theme to material theme by adding,

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

in your style.xml. Dont forget to set the same theme in your application theme in your manifest file.

In VBA get rid of the case sensitivity when comparing words?

If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.

If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Git ignore local file changes

You probably need to do a git stash before you git pull, this is because it is reading your old config file. So do:

git stash
git pull
git commit -am <"say first commit">
git push

Also see git-stash(1) Manual Page.

Why use String.Format?

String.Format adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.

For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format (as well as xxx.WriteLine and other methods that support composite formatting) over normal concatenation operators.

How can I generate a unique ID in Python?

You might want Python's UUID functions:

21.15. uuid — UUID objects according to RFC 4122

eg:

import uuid
print uuid.uuid4()

7d529dd4-548b-4258-aa8e-23e34dc8d43d

How do you parse and process HTML/XML in PHP?

QueryPath is good, but be careful of "tracking state" cause if you didn't realise what it means, it can mean you waste a lot of debugging time trying to find out what happened and why the code doesn't work.

What it means is that each call on the result set modifies the result set in the object, it's not chainable like in jquery where each link is a new set, you have a single set which is the results from your query and each function call modifies that single set.

in order to get jquery-like behaviour, you need to branch before you do a filter/modify like operation, that means it'll mirror what happens in jquery much more closely.

$results = qp("div p");
$forename = $results->find("input[name='forename']");

$results now contains the result set for input[name='forename'] NOT the original query "div p" this tripped me up a lot, what I found was that QueryPath tracks the filters and finds and everything which modifies your results and stores them in the object. you need to do this instead

$forename = $results->branch()->find("input[name='forname']")

then $results won't be modified and you can reuse the result set again and again, perhaps somebody with much more knowledge can clear this up a bit, but it's basically like this from what I've found.

How do I clone a single branch in Git?

You can do it by using the below command:

git clone -b branch_name --single-branch project_url local_folder_to_clone_in

Insert an item into sorted list in Python

This is the best way to append the list and insert values to sorted list:

 a = [] num = int(input('How many numbers: ')) for n in range(num):
     numbers = int(input('Enter values:'))
     a.append(numbers)

 b = sorted(a) print(b) c = int(input("enter value:")) for i in
 range(len(b)):
     if b[i] > c:
         index = i
         break d = b[:i] + [c] + b[i:] print(d)`

How to test code dependent on environment variables using JUnit?

I don't think this has been mentioned yet, but you could also use Powermockito:

Given:

package com.foo.service.impl;

public class FooServiceImpl {

    public void doSomeFooStuff() {
        System.getenv("FOO_VAR_1");
        System.getenv("FOO_VAR_2");
        System.getenv("FOO_VAR_3");

        // Do the other Foo stuff
    }
}

You could do the following:

package com.foo.service.impl;

import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;

import org.junit.Beforea;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(FooServiceImpl.class)
public class FooServiceImpTest {

    @InjectMocks
    private FooServiceImpl service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        mockStatic(System.class);  // Powermock can mock static and private methods

        when(System.getenv("FOO_VAR_1")).thenReturn("test-foo-var-1");
        when(System.getenv("FOO_VAR_2")).thenReturn("test-foo-var-2");
        when(System.getenv("FOO_VAR_3")).thenReturn("test-foo-var-3");
    }

    @Test
    public void testSomeFooStuff() {        
        // Test
        service.doSomeFooStuff();

        verifyStatic();
        System.getenv("FOO_VAR_1");
        verifyStatic();
        System.getenv("FOO_VAR_2");
        verifyStatic();
        System.getenv("FOO_VAR_3");
    }
}

Context.startForegroundService() did not then call Service.startForeground()

Even after calling the startForeground in Service, It crashes on some devices if we call stopService just before onCreate is called. So, I fixed this issue by Starting the service with an additional flag:

Intent intent = new Intent(context, YourService.class);
intent.putExtra("request_stop", true);
context.startService(intent);

and added a check in onStartCommand to see if it was started to stop:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //call startForeground first
    if (intent != null) {
        boolean stopService = intent.getBooleanExtra("request_stop", false);
        if (stopService) {
            stopSelf();
        }
    }

    //Continue with the background task
    return START_STICKY;
}

P.S. If the service were not running, it would start the service first, which is an overhead.

How to set bootstrap navbar active class with Angular JS?

This did the trick for me:

  var domain = '{{ DOMAIN }}'; // www.example.com or dev.example.com
  var domain_index =  window.location.href.indexOf(domain);
  var long_app_name = window.location.href.slice(domain_index+domain.length+1); 
  // this turns http://www.example.com/whatever/whatever to whatever/whatever
  app_name = long_app_name.slice(0, long_app_name.indexOf('/')); 
  //now you are left off with just the first whatever which is usually your app name

then you use jquery(works with angular too) to add class active

$('nav a[href*="' + app_name+'"]').closest('li').addClass('active');

and of course the css:

.active{background:red;}

this works if you have your html like this:

<ul><li><a href="/ee">ee</a></li><li><a href="/dd">dd</a></li></ul>

this will atumatically add class active using the page url and color your background to red if your in www.somesite.com/ee thaen ee is the 'app' and it will be active

How do you set the startup page for debugging in an ASP.NET MVC application?

Go to your project's properties and set the start page property.

  1. Go to the project's Properties
  2. Go to the Web tab
  3. Select the Specific Page radio button
  4. Type in the desired url in the Specific Page text box

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

How to make the python interpreter correctly handle non-ASCII characters in string operations?

Python 2 uses ascii as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses utf-8 as the default encoding for source files, so this is less of an issue.

See: http://docs.python.org/tutorial/interpreter.html#source-code-encoding

To enable utf-8 source encoding, this would go in one of the top two lines:

# -*- coding: utf-8 -*-

The above is in the docs, but this also works:

# coding: utf-8

Additional considerations:

  • The source file must be saved using the correct encoding in your text editor as well.

  • In Python 2, the unicode literal must have a u before it, as in s.replace(u"Â ", u"") But in Python 3, just use quotes. In Python 2, you can from __future__ import unicode_literals to obtain the Python 3 behavior, but be aware this affects the entire current module.

  • s.replace(u"Â ", u"") will also fail if s is not a unicode string.

  • string.replace returns a new string and does not edit in place, so make sure you're using the return value as well

How to write log base(2) in c/c++

Improved version of what Ustaman Sangat did

static inline uint64_t
log2(uint64_t n)
{
    uint64_t val;
    for (val = 0; n > 1; val++, n >>= 1);

    return val;
}

Difference between npx and npm?

Here's an example of NPX in action: npx cowsay hello

If you type that into your bash terminal you'll see the result. The benefit of this is that npx has temporarily installed cowsay. There is no package pollution since cowsay is not permanently installed. This is great for one off packages where you want to avoid package pollution.

As mentioned in other answers, npx is also very useful in cases where (with npm) the package needs to be installed then configured before running. E.g. instead of using npm to install and then configure the json.package file and then call the configured run command just use npx instead. A real example: npx create-react-app my-app

How to center an element in the middle of the browser window?

div#wrapper {
    position: absolute;
    top:  50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

How to fix "unable to write 'random state' " in openssl

Fragment pressing back button

you can use this one in onCreateView, you can use transaction or replace

 OnBackPressedCallback callback = new OnBackPressedCallback(true) {
                @Override
                public void handleOnBackPressed() {
                    //what you want to do 
                }
            };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

Vim and Ctags tips and tricks

The command I am using most is C-] which jumps to the definition of the function under the cursor. You can use it more often to follow more calls. After that, C-o will bring you back one level, C-i goes deeper again.

Get data from php array - AJAX - jQuery

When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

You might actually need

echo json_encode($array);

This should get you what you want.

EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I faced a similar problem, here's how I solved in my case. I verify if the task already is RUNNING or FINISHED because an task can run only once. Below you will see a partial and adapted code from my solution.

public class MyActivity... {
    private MyTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // your code
       task = new MyTask();
       setList();
    }

    private void setList() {
    if (task != null)
        if (task.getStatus().equals(AsyncTask.Status.RUNNING)){
            task.cancel(true);
            task = new MyTask();
            task.execute();         
        } else if (task.getStatus().equals(AsyncTask.Status.FINISHED)) {
            task = new MyTask();
            task.execute();
        } else 
            task.execute();
    }

    class MyTask extends AsyncTask<Void, Item, Void>{
       List<Item> Itens;

       @Override
       protected void onPreExecute() {

        //your code

        list.setVisibility(View.GONE);
        adapterItem= new MyListAdapter(MyActivity.this, R.layout.item, new ArrayList<Item>());
        list.setAdapter(adapterItem);

        adapterItem.notifyDataSetChanged();
    }

    @Override
    protected Void doInBackground(Void... params) {

        Itens = getItens();
        for (Item item : Itens) {
            publishProgress(item );
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Item ... item ) {           
        adapterItem.add(item[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        //your code
        adapterItem.notifyDataSetChanged();     
        list.setVisibility(View.VISIBLE);
    }

}

}

could not access the package manager. is the system running while installing android application

You can avoid the error by setting default device before launching application. Launch the AVD before starting the app.

how to change a selections options based on another select option selected?

you can use data-tag in html5 and do this using this code:

_x000D_
_x000D_
<script>_x000D_
 $('#mainCat').on('change', function() {_x000D_
  var selected = $(this).val();_x000D_
  $("#expertCat option").each(function(item){_x000D_
   console.log(selected) ;  _x000D_
   var element =  $(this) ; _x000D_
   console.log(element.data("tag")) ; _x000D_
   if (element.data("tag") != selected){_x000D_
    element.hide() ; _x000D_
   }else{_x000D_
    element.show();_x000D_
   }_x000D_
  }) ; _x000D_
  _x000D_
  $("#expertCat").val($("#expertCat option:visible:first").val());_x000D_
  _x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<select id="mainCat">_x000D_
   <option value = '1'>navid</option>_x000D_
   <option value = '2'>javad</option>_x000D_
   <option value = '3'>mamal</option>_x000D_
  </select>_x000D_
  _x000D_
  <select id="expertCat">_x000D_
   <option  value = '1' data-tag='2'>UI</option>_x000D_
   <option  value = '2' data-tag='2'>Java Android</option>_x000D_
   <option  value = '3' data-tag='1'>Web</option>_x000D_
   <option  value = '3' data-tag='1'>Server</option>_x000D_
   <option  value = '3' data-tag='3'>Back End</option>_x000D_
   <option  value = '3' data-tag='3'>.net</option>_x000D_
  </select>
_x000D_
_x000D_
_x000D_

How to change icon on Google map marker

var marker = new google.maps.Marker({
                position: new google.maps.LatLng(23.016427,72.571156),
                map: map,
                icon: 'images/map_marker_icon.png',
                title: 'Hi..!'
            });

apply local path on icon only

Redirect to a page/URL after alert button is pressed

Like that, both of the sentences will be executed even before the page has finished loading.

Here is your error, you are missing a ';' Change:

       echo 'alert("review your answer")'; 
       echo 'window.location= "index.php"';

To:

       echo 'alert("review your answer");';
       echo 'window.location= "index.php";';

Then a suggestion: You really should trigger that logic after some event. So, for instance:

           document.getElementById("myBtn").onclick=function(){
                 alert("review your answer");
                 window.location= "index.php";
           };

Another suggestion, use jQuery

setBackground vs setBackgroundDrawable (Android)

Now you can use either of those options. And it is going to work in any case. Your color can be a HEX code, like this:

myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));

A color resource, like this:

myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));

Or a custom xml resource, like so:

myView.setBackgroundResource(R.drawable.my_custom_background);

Hope it helps!

How to filter in NaN (pandas)?

This doesn't work because NaN isn't equal to anything, including NaN. Use pd.isnull(df.var2) instead.

How to write and read a file with a HashMap?

You can write an object to a file using writeObject in ObjectOutputStream

ObjectOutputStream

A child container failed during start java.util.concurrent.ExecutionException

Faced the same issue. Changed the JRE to the correct 1.8 version and do a maven clean and build resolve the issue. You may need to change the Project Facet and verify the correct path.

How to find the unclosed div tag

I know that there have already been some good answers, but I came across this question with a Google Search and I wish someone would have pointed out this online checking tool...

http://www.tormus.com/tools/div_checker

You just throw in a URL and it will show you the entire map of the page. Very useful for a quick debug like I needed.

In LINQ, select all values of property X where X != null

You can use the OfType operator. It ignores null values in the source sequence. Just use the same type as MyProperty and it won't filter out anything else.

// given:
// public T MyProperty { get; }
var nonNullItems = list.Select(x => x.MyProperty).OfType<T>();

I would advise against this though. If you want to pick non-null values, what can be more explicit than saying you want "the MyProperties from the list that are not null"?

How can I dismiss the on screen keyboard?

You can use unfocus() method from FocusNode class.

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();
  FocusNode _focusNode = new FocusNode(); //1 - declare and initialize variable

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.send),
        onPressed: () {
            _focusNode.unfocus(); //3 - call this method here
        },
      ),
      body: new Container(
        alignment: FractionalOffset.center,
        padding: new EdgeInsets.all(20.0),
        child: new TextFormField(
          controller: _controller,
          focusNode: _focusNode, //2 - assign it to your TextFormField
          decoration: new InputDecoration(labelText: 'Example Text'),
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

void main() {
  runApp(new MyApp());
}

How to find Control in TemplateField of GridView?

I have done it accessing the controls inside the cell control. Find in all control collections.

 ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;

 Label lbCod = (Label)cc[1];

Don't reload application when orientation changes

just use : android:configChanges="keyboardHidden|orientation"

How do I find out what is hammering my SQL Server?

Run either of these a few second apart. You'll detect the high CPU connection. Or: stored CPU in a local variable, WAITFOR DELAY, compare stored and current CPU values

select * from master..sysprocesses
where status = 'runnable' --comment this out
order by CPU
desc

select * from master..sysprocesses
order by CPU
desc

May not be the most elegant but it'd effective and quick.

RuntimeWarning: DateTimeField received a naive datetime

If you are trying to transform a naive datetime into a datetime with timezone in django, here is my solution:

>>> import datetime
>>> from django.utils import timezone
>>> t1 = datetime.datetime.strptime("2019-07-16 22:24:00", "%Y-%m-%d %H:%M:%S")
>>> t1
    datetime.datetime(2019, 7, 16, 22, 24)
>>> current_tz = timezone.get_current_timezone()
>>> t2 = current_tz.localize(t1)
>>> t2
    datetime.datetime(2019, 7, 16, 22, 24, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
>>>

t1 is a naive datetime and t2 is a datetime with timezone in django's settings.

Base64 encoding in SQL Server 2005 T-SQL

Here is the code for the functions that will do the work

-- To Base64 string
CREATE FUNCTION [dbo].[fn_str_TO_BASE64]
(
    @STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    RETURN (
        SELECT
            CAST(N'' AS XML).value(
                  'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
                , 'NVARCHAR(MAX)'
            )   Base64Encoding
        FROM (
            SELECT CAST(@STRING AS VARBINARY(MAX)) AS bin
        ) AS bin_sql_server_temp
    )
END
GO

-- From Base64 string
CREATE FUNCTION [dbo].[fn_str_FROM_BASE64]
(
    @BASE64_STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    RETURN (
        SELECT 
            CAST(
                CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@BASE64_STRING"))', 'VARBINARY(MAX)') 
            AS NVARCHAR(MAX)
            )   UTF8Encoding
    )
END

Example of usage:

DECLARE @CHAR NVARCHAR(256) = N'e.g., ???? ????? or ? ??????'
SELECT [dbo].[fn_str_FROM_BASE64]([dbo].[fn_str_TO_BASE64](@CHAR)) as converted

enter image description here

HTML table needs spacing between columns, not rows

The better approach uses Shredder's css rule: padding: 0 15px 0 15px only instead of inline css, define a css rule that applies to all tds. Do This by using a style tag in your page:

<style type="text/css">
td
{
    padding:0 15px;
}
</style>

or give the table a class like "paddingBetweenCols" and in the site css use

.paddingBetweenCols td
{
    padding:0 15px;
}

The site css approach defines a central rule that can be reused by all pages.

If your doing to use the site css approach, it would be best to define a class like above and apply the padding to the class...unless you want all td's on the entire site to have the same rule applied.

Fiddle for using style tag

Fiddle for using site css

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}