Programs & Examples On #Directx

DirectX is a collection of APIs for handling tasks related to multimedia, especially 3D graphics and game programming and video, on Microsoft platforms.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I've had the same problem twice already and the easiest and most concise solution that I found is located here (in MSDN Blogs -> Games for Windows and the DirectX SDK). However, just in case that page goes down, here's the method:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
    
  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB 2565063 with a security fix.

Note: This issue does not affect earlier version of the DirectX SDK which deploy the VS 2005 / VS 2008 CRT REDIST and do not deploy the VS 2010 CRT REDIST. This issue does not affect the DirectX End-User Runtime web or stand-alone installer as those packages do not deploy any version of the VC++ CRT.

File Checksum Integrity Verifier: This of course assumes you actually have an uncorrupted copy of the DirectX SDK setup package. The best way to validate this it to run

fciv -sha1 DXSDK_Jun10.exe

and verify you get

8fe98c00fde0f524760bb9021f438bd7d9304a69 dxsdk_jun10.exe

How do I restart my C# WinForm Application?

for using As logout you need to terminate all app from Ram Cache so close The Application first and then Rerun it

//on clicking Logout Button

foreach(Form frm in Application.OpenForms.Cast<Form>().ToList())
        {
            frm.Close();
        }
System.Diagnostics.Process.Start(Application.ExecutablePath);

Text not wrapping in p tag

Word wrapping only occurs when there is a word break.

If you have a "word" that is as long as that, then there is no place for it to break.

The proper solution is to write real content and not nonsense strings of characters. If you are using user generated content, then add a check for exceptionally long words and disallow them (or cut out part of them for URLs while keeping the whole thing in a link).

Alternatively, you can use the word-break CSS property to tell the browser to line break in the middle of words.

p { word-break: break-all }

(Note browser support).

Alternatively, you can use overflow to truncate the text if it won't fit in the container.

Python DNS module import error

I have faced similar issue when importing on mac.i have python 3.7.3 installed Following steps helped me resolve it:

  1. pip3 uninstall dnspython
  2. sudo -H pip3 install dnspython

Import dns

Import dns.resolver

Call a React component method from outside

class AppProvider extends Component {
  constructor() {
    super();

    window.alertMessage = this.alertMessage.bind(this);
  }

  alertMessage() {
    console.log('Hello World');
 }
}

You can call this method from the window by using window.alertMessage().

How to format strings in Java

Java 15

There is a new instance method called String::formatted(Object... args) as of Java 15.

The internal implementation is same to String::format(String format, Object... args).

Formats using this string as the format string, and the supplied arguments.

String step1 = "one";
String step2 = "two";

// results in "Step one of two"
String string = "Step %s of %s".formatted(step1, step2);     

Advantage: The difference is that the method is not static and the formatting pattern is a string itself from which a new one is created based on the args. This allows chaining to build the format itself first.

Disadvantage: There is no overloaded method with Locale, therefore uses the default one. If you need to use a custom Locale, you have to stick with String::format(Locale l,String format,Object... args).

Deserializing JSON Object Array with Json.net

Slight modification to what was stated above. My Json format, which validates was

{
    mycollection:{[
           {   
               property0:value,
               property1:value,
             },
             {   
               property0:value,
               property1:value,
             }
           ]

         }
       }

Using AlexDev's response, I did this Looping each child, creating reader from it

 public partial class myModel
{
    public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}

 public class myModelList {
    [JsonConverter(typeof(myModelConverter))]
    public List<myModel> model { get; set; }

}

class myModelConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Children())  //mod here
        {
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(child.CreateReader(), newObject); //mod here
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();

}

How can I override Bootstrap CSS styles?

See https://bootstrap.themes.guide/how-to-customize-bootstrap.html

  1. For simple CSS Overrides, you can add a custom.css below the bootstrap.css

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    
  2. For more extensive changes, SASS is the recommended method.

    • create your own custom.scss
    • import Bootstrap after the changes in custom.scss
    • For example, let’s change the body background-color to light-gray #eeeeee, and change the blue primary contextual color to Bootstrap's $purple variable...

      /* custom.scss */    
      
      /* import the necessary Bootstrap files */
      @import "bootstrap/functions";
      @import "bootstrap/variables";
      
      /* -------begin customization-------- */   
      
      /* simply assign the value */ 
      $body-bg: #eeeeee;
      
      /* or, use an existing variable */
      $theme-colors: (
        primary: $purple
      );
      /* -------end customization-------- */  
      
      /* finally, import Bootstrap to set the changes! */
      @import "bootstrap";
      

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

How to set selected value from Combobox?

A possible solution:

cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;

Make WPF Application Fullscreen (Cover startmenu)

<Window x:Class="HTA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" 
    ResizeMode="NoResize"
    WindowStartupLocation="CenterScreen" 
    Width="1024" Height="768"
    WindowState="Maximized" WindowStyle="None">

Window state to Maximized and window style to None

Batch Files - Error Handling

Python Unittest, Bat process Error Codes:

if __name__ == "__main__":
   test_suite = unittest.TestSuite()
   test_suite.addTest(RunTestCases("test_aggregationCount_001"))
   runner = unittest.TextTestRunner()
   result = runner.run(test_suite)
   # result = unittest.TextTestRunner().run(test_suite)
   if result.wasSuccessful():
       print("############### Test Successful! ###############")
       sys.exit(1)
   else:
       print("############### Test Failed! ###############")
       sys.exit()

Bat codes:

@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
  echo Error found. Waiting here...
  pause
) || (
  echo This time of test is ok.
)
)

Select where count of one field is greater than one

SELECT username, numb from(
Select username, count(username) as numb from customers GROUP BY username ) as my_table
WHERE numb > 3

Docker can't connect to docker daemon

If you are running on OS X using Docker tool, follow this.

Restart the daemon and configure your environment:

docker-machine restart

And then

docker-machine env

Finally,

eval $(docker-machine env)

To test the daemon is running:

docker ps -a or docker-machine ls. This will list all containers.

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Extract a substring according to a pattern

If you are using data.table then tstrsplit() is a natural choice:

tstrsplit(string, ":")[[2]]
[1] "E001" "E002" "E003"

Run a JAR file from the command line and specify classpath

You can do a Runtime.getRuntime.exec(command) to relaunch the jar including classpath with args.

How to add external JS scripts to VueJS Components

Simplest solution is to add the script in the index.html file of your vue-project

index.html:

 <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>vue-webpack</title>
      </head>
      <body>
        <div id="app"></div>
        <!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
    0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
    for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
    MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
    mixpanel.init("xyz");</script><!-- end Mixpanel -->
        <script src="/dist/build.js"></script>
      </body>
    </html>

What is tail call optimization?

Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.

Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization, so here are two examples of the factorial function in Scheme:

(define (fact x)
  (if (= x 0) 1
      (* x (fact (- x 1)))))

(define (fact x)
  (define (fact-tail x accum)
    (if (= x 0) accum
        (fact-tail (- x 1) (* x accum))))
  (fact-tail x 1))

The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:

(fact 3)
(* 3 (fact 2))
(* 3 (* 2 (fact 1)))
(* 3 (* 2 (* 1 (fact 0))))
(* 3 (* 2 (* 1 1)))
(* 3 (* 2 1))
(* 3 2)
6

In contrast, the stack trace for the tail recursive factorial looks as follows:

(fact 3)
(fact-tail 3 1)
(fact-tail 2 3)
(fact-tail 1 6)
(fact-tail 0 6)
6

As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.

Output in a table format in Java's System.out

Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/

An example of the TableBuilder and sample output

How to upgrade Git on Windows to the latest version?

If you look at the most recent update on Git's website in the "git via git" section you will see an option to update your older version.

Here is the command that git has on their site:

git clone https://github.com/git/git

It worked for my version of git which was a 2.13.0.windows.1.

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month! e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.

Create Table from View

INSERT INTO table 2
SELECT * FROM table1/view1

Empty responseText from XMLHttpRequest

Is http://api.xxx.com/ part of your domain? If not, you are being blocked by the same origin policy.

You may want to check out the following Stack Overflow post for a few possible workarounds:

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

For an alternative cryptography library, have a look at Bouncy Castle. It has AES and a lot of added functionality. It's a liberal open source library. You will have to use the lightweight, proprietary Bouncy Castle API for this to work though.

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

How do I fill arrays in Java?

An array can be initialized by using the new Object {} syntax.

For example, an array of String can be declared by either:

String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};

Primitives can also be similarly initialized either by:

int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};

Or an array of some Object:

Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};

All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.

How to connect to a MySQL Data Source in Visual Studio

unfortunately this is not supported in the builtin tools in visual studio. however, you can create your own data provider using mysql connector but still have to integrate it from code

What is "loose coupling?" Please provide examples

Some long answers here. The principle is very simple though. I submit the opening statement from wikipedia:

"Loose coupling describes a resilient relationship between two or more systems or organizations with some kind of exchange relationship.

Each end of the transaction makes its requirements explicit and makes few assumptions about the other end."

Multipart File upload Spring Boot

   @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("5120MB");
        factory.setMaxRequestSize("5120MB");
        return factory.createMultipartConfig();
    }

put it in class where you are defining beans

Entity Framework Code First - two Foreign Keys from same table

You can try this too:

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int? HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int? GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.

In my case, this simple modification solve the problem.

How to get table list in database, using MS SQL 2008?

Answering the question in your title, you can query sys.tables or sys.objects where type = 'U' to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:

IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
    CREATE TABLE dbo.My_Table (...)
END

You can do the same for databases with DB_ID():

IF (DB_ID('My_Database') IS NULL)
BEGIN
    CREATE DATABASE My_Database
END

If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO statements. In an application it's easy enough to send across a new command after the database is created.

The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.

If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:

CREATE DATABASE Test_DB2

IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
    EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END

EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.

How to change the background color of a UIButton while it's highlighted?

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect(origin: CGPoint.zero, size: size))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(colorImage, for: forState)
    }

}

Swift 5 , thanks @Maverick

/usr/bin/codesign failed with exit code 1

I just came across this error and it was because I was trying to write the build file to a network drive that was not working. Tried again from my desktop and it worked just fine. (You may have to "Clean" the build after you move it. Just choose "Clean all Targets" from the "Build" drop-down menu).

Tobias is correct though, dig into the details on the code by right-clicking it to see what your specific problem is.

How to get UTF-8 working in Java webapps?

Some time you can solve problem through MySQL Administrator wizard. In

Startup variables > Advanced >

and set Def. char Set:utf8

Maybe this config need restart MySQL.

Java - Getting Data from MySQL database

Here you go :

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");

Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) { 
 int id = rs.getInt("first_column_name"); 
 String str1 = rs.getString("second_column_name");
}

con.close();

In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.

UPDATE : rs.next

boolean next() throws SQLException

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set

reference

Animation fade in and out

we can simply use:

public void animStart(View view) {
    if(count==0){
        Log.d("count", String.valueOf(count));
        i1.animate().alpha(0f).setDuration(2000);
        i2.animate().alpha(1f).setDuration(2000);
        count =1;
    }
    else if(count==1){
        Log.d("count", String.valueOf(count));
        count =0;
        i2.animate().alpha(0f).setDuration(2000);
        i1.animate().alpha(1f).setDuration(2000);
    }
}

where i1 and i2 are defined in the onCreateView() as:

    i1 = (ImageView)findViewById(R.id.firstImage);
    i2 = (ImageView)findViewById(R.id.secondImage);

count is a class variable initilaized to 0.

The XML file is :

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <ImageView
            android:id="@+id/secondImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="animStart"
            android:src="@drawable/second" />
      <ImageView
          android:id="@+id/firstImage"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"

          android:onClick="animStart"
          android:src="@drawable/first" />
    </RelativeLayout>

@drawable/first and @drawable/second are the images in the drawable folder in res.

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

This part of code worked fine for me:

        WebRequest request = WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
        CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
        request.PreAuthenticate = true;
        request.Credentials = myCredentialCache;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }

How to add colored border on cardview?

I think this solution may not be efficient but it serves the purpose and adds flexibility with the border width.

 <android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="40dp"
    android:layout_gravity="center"
    card_view:cardBackgroundColor="@color/some_color"
    card_view:cardCornerRadius="20dp"
    card_view:contentPadding="5dp"> <!-- Change it to customize the border width -->

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        card_view:cardCornerRadius="20dp"
        card_view:contentPadding="5dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

         <!-- Add your UI elements -->

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

SQL Inner Join On Null Values

I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)

Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null

Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null


select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid

select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)


select * from #test2 t2
join #test1 t1 on 
 t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )


select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2  where qid is null

$(this).attr("id") not working

Change

var ID = $(this).attr("id");

to

var ID = $(obj).attr("id");

Also you can change it to use jQuery event handler:

$('#race').change(function() {
    var select = $(this);
    var id = select.attr('id');
    if(select.val() == 'other') {
        select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
    } else {
        select.hide();
    }
});

Need a good hex editor for Linux

Personally, I use Emacs with hexl-mod.

Emacs is able to work with really huge files. You can use search/replace value easily. Finally, you can use 'ediff' to do some diffs.

How to change options of <select> with jQuery?

If for example your html code contain this code:

<select id="selectId"><option>Test1</option><option>Test2</option></select>

In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.

var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").html(option);

in this example above i change the old list of option by only one new option.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Quickest possible solution (just 1 step)

Use git checkout -

You will see Switched to branch <branch_name>. Confirm it's the branch you want.


Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.


Mnemonic: this approach is a lot like using cd - to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).


More methodical solution (2-steps, but memorable)

The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.

1. Pick the branch you need

Use git branch -v

You see a list of existing local branches. Grab the branch name that suits your needs.

2. Move HEAD to it

Use git checkout <branch_name>

You will see Switched to branch <branch_name>. Success!


Outcomes

With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>.

Note that both git checkout - and git checkout <branch_name> will give additional instructions if you have committed changes while HEAD was detached.

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config

change LISTEN:80 to what ever you want you can choose any value of 4 digit like 1311,8000,9999 etc

How to make several plots on a single page using matplotlib?

To answer your main question, you want to use the subplot command. I think changing plt.figure(i) to plt.subplot(4,4,i+1) should work.

Jquery - animate height toggle

Very late but I apologize. Sorry if this is "inefficient" but if you found all the above not working, do try this. Works for above 1.10 also

<script>
  $(document).ready(function() {
    var position='expanded';

    $("#topbar").click(function() {
      if (position=='expanded') {
        $(this).animate({height:'200px'});
        position='collapsed';
      } else {
        $(this).animate({height:'400px'});
        position='expanded';
      }
    });
   });
</script>

Executing periodic actions in Python

Here's a simple single threaded sleep based version that drifts, but tries to auto-correct when it detects drift.

NOTE: This will only work if the following 3 reasonable assumptions are met:

  1. The time period is much larger than the execution time of the function being executed
  2. The function being executed takes approximately the same amount of time on each call
  3. The amount of drift between calls is less than a second

-

from datetime import timedelta
from datetime import datetime

def exec_every_n_seconds(n,f):
    first_called=datetime.now()
    f()
    num_calls=1
    drift=timedelta()
    time_period=timedelta(seconds=n)
    while 1:
        time.sleep(n-drift.microseconds/1000000.0)
        current_time = datetime.now()
        f()
        num_calls += 1
        difference = current_time - first_called
        drift = difference - time_period* num_calls
        print "drift=",drift

How to end a session in ExpressJS

Never mind, it's req.session.destroy();

How to get the connection String from a database

Open SQL Server Management Studio and run following query. You will get connection string:

select
    'data source=' + @@servername +
    ';initial catalog=' + db_name() +
    case type_desc
        when 'WINDOWS_LOGIN' 
            then ';trusted_connection=true'
        else
            ';user id=' + suser_name() + ';password=<<YourPassword>>'
    end
    as ConnectionString
from sys.server_principals
where name = suser_name()

Centering the pagination in bootstrap

bootstrap 4 :

<!-- Default (left-aligned) -->
<ul class="pagination" style="margin:20px 0">
  <li class="page-item">...</li>
</ul>

<!-- Center-aligned -->
<ul class="pagination justify-content-center" style="margin:20px 0">
  <li class="page-item">...</li>
</ul>

<!-- Right-aligned -->
<ul class="pagination justify-content-end" style="margin:20px 0">
  <li class="page-item">...</li>
</ul> 

SELECT CASE WHEN THEN (SELECT)

For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).

How to draw a line in android

You can make a drawable like circle, line, rectangle etc through shapes in xml as follow:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="line" >

    <solid android:color="#00000000" />

    <stroke
        android:width="2dp"
        android:color="#808080" />

</shape>

Rounded Corners Image in Flutter

Output:

enter image description here

Using BoxDecoration

Container(
              margin: EdgeInsets.all(8),
              width: 86,
              height: 86,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                    image: NetworkImage('https://i.stack.imgur.com/0VpX0.png'),
                    fit: BoxFit.cover
                ),
              ), 
           ),

How to solve error: "Clock skew detected"?

please try to do

make clean

(instead of make), then

make

again.

How do I get currency exchange rates via an API such as Google Finance?

For all newbie guys searching for some hint about currency conversion, take a look at this link. Datavoila

It helped med a lot regarding my own project in C#. Just in case the site disappears, I'll add the code below. Just add the below steps to your own project. Sorry about the formatting.

const string fromCurrency = "USD";
const string toCurrency = "EUR";
const double amount = 49.95;
// For other currency symbols see http://finance.yahoo.com/currency-converter/
// Clear the output editor //optional use, AFAIK
Output.Clear();

// Construct URL to query the Yahoo! Finance API
const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
string url = String.Format(urlPattern, fromCurrency, toCurrency);

// Get response as string
string response = new WebClient().DownloadString(url);

// Convert string to number
double exchangeRate =
    double.Parse(response, System.Globalization.CultureInfo.InvariantCulture);

// Output the result
Output.Text = String.Format("{0} {1} = {2} {3}",
                            amount, fromCurrency,
                            amount * exchangeRate, toCurrency);

Python Variable Declaration

Okay, first things first.

There is no such thing as "variable declaration" or "variable initialization" in Python.

There is simply what we call "assignment", but should probably just call "naming".

Assignment means "this name on the left-hand side now refers to the result of evaluating the right-hand side, regardless of what it referred to before (if anything)".

foo = 'bar' # the name 'foo' is now a name for the string 'bar'
foo = 2 * 3 # the name 'foo' stops being a name for the string 'bar',
# and starts being a name for the integer 6, resulting from the multiplication

As such, Python's names (a better term than "variables", arguably) don't have associated types; the values do. You can re-apply the same name to anything regardless of its type, but the thing still has behaviour that's dependent upon its type. The name is simply a way to refer to the value (object). This answers your second question: You don't create variables to hold a custom type. You don't create variables to hold any particular type. You don't "create" variables at all. You give names to objects.

Second point: Python follows a very simple rule when it comes to classes, that is actually much more consistent than what languages like Java, C++ and C# do: everything declared inside the class block is part of the class. So, functions (def) written here are methods, i.e. part of the class object (not stored on a per-instance basis), just like in Java, C++ and C#; but other names here are also part of the class. Again, the names are just names, and they don't have associated types, and functions are objects too in Python. Thus:

class Example:
    data = 42
    def method(self): pass

Classes are objects too, in Python.

So now we have created an object named Example, which represents the class of all things that are Examples. This object has two user-supplied attributes (In C++, "members"; in C#, "fields or properties or methods"; in Java, "fields or methods"). One of them is named data, and it stores the integer value 42. The other is named method, and it stores a function object. (There are several more attributes that Python adds automatically.)

These attributes still aren't really part of the object, though. Fundamentally, an object is just a bundle of more names (the attribute names), until you get down to things that can't be divided up any more. Thus, values can be shared between different instances of a class, or even between objects of different classes, if you deliberately set that up.

Let's create an instance:

x = Example()

Now we have a separate object named x, which is an instance of Example. The data and method are not actually part of the object, but we can still look them up via x because of some magic that Python does behind the scenes. When we look up method, in particular, we will instead get a "bound method" (when we call it, x gets passed automatically as the self parameter, which cannot happen if we look up Example.method directly).

What happens when we try to use x.data?

When we examine it, it's looked up in the object first. If it's not found in the object, Python looks in the class.

However, when we assign to x.data, Python will create an attribute on the object. It will not replace the class' attribute.

This allows us to do object initialization. Python will automatically call the class' __init__ method on new instances when they are created, if present. In this method, we can simply assign to attributes to set initial values for that attribute on each object:

class Example:
    name = "Ignored"
    def __init__(self, name):
        self.name = name
    # rest as before

Now we must specify a name when we create an Example, and each instance has its own name. Python will ignore the class attribute Example.name whenever we look up the .name of an instance, because the instance's attribute will be found first.

One last caveat: modification (mutation) and assignment are different things!

In Python, strings are immutable. They cannot be modified. When you do:

a = 'hi '
b = a
a += 'mom'

You do not change the original 'hi ' string. That is impossible in Python. Instead, you create a new string 'hi mom', and cause a to stop being a name for 'hi ', and start being a name for 'hi mom' instead. We made b a name for 'hi ' as well, and after re-applying the a name, b is still a name for 'hi ', because 'hi ' still exists and has not been changed.

But lists can be changed:

a = [1, 2, 3]
b = a
a += [4]

Now b is [1, 2, 3, 4] as well, because we made b a name for the same thing that a named, and then we changed that thing. We did not create a new list for a to name, because Python simply treats += differently for lists.

This matters for objects because if you had a list as a class attribute, and used an instance to modify the list, then the change would be "seen" in all other instances. This is because (a) the data is actually part of the class object, and not any instance object; (b) because you were modifying the list and not doing a simple assignment, you did not create a new instance attribute hiding the class attribute.

window.close() doesn't work - Scripts may close only the windows that were opened by it

The below code worked for me :)

window.open('your current page URL', '_self', '');
window.close();

How to Get JSON Array Within JSON Object?

JSONObject jsonObject =new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length;i++){
    JSONObject json = jsonArray.getJSONObject(i);
    String id = json.getString("id");
    String name=json.getString("name");
    JSONArray ingArray = json.getJSONArray("Ingredients") // here you are going   to get ingredients
    for(int j=0;j<ingArray.length;j++){
        JSONObject ingredObject= ingArray.getJSONObject(j);
        String ingName = ingredObject.getString("name");//so you are going to get   ingredient name
        Log.e("name",ingName); // you will get 
   }
}

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

Center text in div?

Add to the selector containing the text

margin:auto;

iOS: set font size of UILabel Programmatically

Swift 3.0 / Swift 4.2 / Swift 5.0

labelName.font = labelName.font.withSize(15)

Using Spring 3 autowire in a standalone Java application

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

OS X Bash, 'watch' command

It may be that "watch" is not what you want. You probably want to ask for help in solving your problem, not in implementing your solution! :)

If your real goal is to trigger actions based on what's seen from the tail command, then you can do that as part of the tail itself. Instead of running "periodically", which is what watch does, you can run your code on demand.

#!/bin/sh

tail -F /var/log/somelogfile | while read line; do
  if echo "$line" | grep -q '[Ss]ome.regex'; then
    # do your stuff
  fi
done

Note that tail -F will continue to follow a log file even if it gets rotated by newsyslog or logrotate. You want to use this instead of the lower-case tail -f. Check man tail for details.

That said, if you really do want to run a command periodically, the other answers provided can be turned into a short shell script:

#!/bin/sh
if [ -z "$2" ]; then
  echo "Usage: $0 SECONDS COMMAND" >&2
  exit 1
fi

SECONDS=$1
shift 1
while sleep $SECONDS; do
  clear
  $*
done

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Before and BeforeClass in JUnit

The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.

Similarly function with @After annotation will be executed after each of test function in the class having @Test annotation but the function with @AfterClass will be execute only one time after all the test functions in the class.

SampleClass

public class SampleClass {
    public String initializeData(){
        return "Initialize";
    }

    public String processDate(){
        return "Process";
    }
 }

SampleTest

public class SampleTest {

    private SampleClass sampleClass;

    @BeforeClass
    public static void beforeClassFunction(){
        System.out.println("Before Class");
    }

    @Before
    public void beforeFunction(){
        sampleClass=new SampleClass();
        System.out.println("Before Function");
    }

    @After
    public void afterFunction(){
        System.out.println("After Function");
    }

    @AfterClass
    public static void afterClassFunction(){
        System.out.println("After Class");
    }

    @Test
    public void initializeTest(){
        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
    }

    @Test
    public void processTest(){
        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
    }

}

Output

Before Class
Before Function
After Function
Before Function
After Function
After Class

In Junit 5

@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll

Common Header / Footer with static HTML

Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed or m4 and sending the result over to your server, no, you'd need at least SSI.

Why is it string.join(list) instead of list.join(string)?

Why is it string.join(list) instead of list.join(string)?

This is because join is a "string" method! It creates a string from any iterable. If we stuck the method on lists, what about when we have iterables that aren't lists?

What if you have a tuple of strings? If this were a list method, you would have to cast every such iterator of strings as a list before you could join the elements into a single string! For example:

some_strings = ('foo', 'bar', 'baz')

Let's roll our own list join method:

class OurList(list): 
    def join(self, s):
        return s.join(self)

And to use it, note that we have to first create a list from each iterable to join the strings in that iterable, wasting both memory and processing power:

>>> l = OurList(some_strings) # step 1, create our list
>>> l.join(', ') # step 2, use our list join method!
'foo, bar, baz'

So we see we have to add an extra step to use our list method, instead of just using the builtin string method:

>>> ' | '.join(some_strings) # a single step!
'foo | bar | baz'

Performance Caveat for Generators

The algorithm Python uses to create the final string with str.join actually has to pass over the iterable twice, so if you provide it a generator expression, it has to materialize it into a list first before it can create the final string.

Thus, while passing around generators is usually better than list comprehensions, str.join is an exception:

>>> import timeit
>>> min(timeit.repeat(lambda: ''.join(str(i) for i in range(10) if i)))
3.839168446022086
>>> min(timeit.repeat(lambda: ''.join([str(i) for i in range(10) if i])))
3.339879313018173

Nevertheless, the str.join operation is still semantically a "string" operation, so it still makes sense to have it on the str object than on miscellaneous iterables.

How to print last two columns using awk

using gawk exhibits the problem:

 gawk '{ print $NF-1, $NF}' filename
1 2
2 3
-1 one
-1 three
# cat filename
1 2
2 3
one
one two three

I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html

There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

What worked for me was simply to do the following:

open the php.ini file.

Under the DYNAMIC EXTENSIONS heading, comment out the following line as

;extension=php_java.dll

Restarted Apache and all was fine

Why do we need to install gulp globally and locally?

Technically you don't need to install it globally if the node_modules folder in your local installation is in your PATH. Generally this isn't a good idea.

Alternatively if npm test references gulp then you can just type npm test and it'll run the local gulp.

I've never installed gulp globally -- I think it's bad form.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

Best way to remove an event handler in jQuery?

Best way to remove inline onclick event is $(element).prop('onclick', null);

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

How to handle ListView click in Android

First, the class must implements the click listenener :

implements OnItemClickListener

Then set a listener to the ListView

yourList.setOnItemclickListener(this);

And finally, create the clic method:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +countries[+ position], Toast.LENGTH_SHORT).show();
}

you can take a look and download code here

How To Change DataType of a DataColumn in a DataTable?

You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.

DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

Align DIV to bottom of the page

Try position:fixed; bottom:0;. This will make your div to stay fixed at the bottom.

WORKING DEMO

The HTML:

<div id="bottom-stuff">
  <div id="search"> MY DIV </div>
</div>
<div id="bottom"> MY DIV </div>

The CSS:

#bottom-stuff {

    position: relative;
}

#bottom{

    position: fixed; 
    background:gray; 
    width:100%;
    bottom:0;
}

#search{height:5000px; overflow-y:scroll;}

Hope this helps.

How can I set the opacity or transparency of a Panel in WinForms?

This does work for me. In below example, Alpha range can be a value between 0 to 255. Previously, I made a mistake by thinking that it must be a value of percentage.

Dim x as integer = 230 Panel1.BackColor = Color.FromArgb(x, Color.Blue)

Difference between os.getenv and os.environ.get

In Python 2.7 with iPython:

>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default."""
    return environ.get(key, default)
File:      ~/venv/lib/python2.7/os.py
Type:      function

So we can conclude os.getenv is just a simple wrapper around os.environ.get.

Change private static final field using Java reflection

A little curiosity from the Java Language Specification, chapter 17, section 17.5.4 "Write-protected Fields":

Normally, a field that is final and static may not be modified. However, System.in, System.out, and System.err are static final fields that, for legacy reasons, must be allowed to be changed by the methods System.setIn, System.setOut, and System.setErr. We refer to these fields as being write-protected to distinguish them from ordinary final fields.

Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.4

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

Cannot stop or restart a docker container

in my case, i couldn't delete container created with nomad jobs, there's no output for the docker logs <ContainerID> and, in general, it looks like frozen.

until now the solution is: sudo service docker restart, may someone suggest better one?

For..In loops in JavaScript - key value pairs

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is " + target[k]);
    }
}

hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

It just checks that k is not a method (as if target is array you'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

Ternary operator in AngularJS templates

While you can use the condition && if-true-part || if-false-part-syntax in older versions of angular, the usual ternary operator condition ? true-part : false-part is available in Angular 1.1.5 and later.

Rails 4 Authenticity Token

When you define you own html form then you have to include authentication token string ,that should be sent to controller for security reasons. If you use rails form helper to generate the authenticity token is added to form as follow.

<form accept-charset="UTF-8" action="/login/signin" method="post">
  <div style="display:none">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden" value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
  </div>
    ...
</form>

So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then compromising security etc.

PHP function use variable from outside

Add second parameter

You need to pass additional parameter to your function:

function parts($site_url, $part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
}

In case of closures

If you'd rather use closures then you can import variable to the current scope (the use keyword):

$parts = function($part) use ($site_url) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
};

global - a bad practice

This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

For the completeness sake here is the solution using global:

function parts($part) { 
    global $site_url;
    $structure = 'http://' . $site_url . 'content/'; 
    echo($structure . $part . '.php'); 
}

It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).

Suggested reading:

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

Replace text inside td using jQuery having td containing other elements

$('#demoTable td').contents().each(function() {
    if (this.nodeType === 3) {
        this.textContent
        ? this.textContent = 'The text has been '
        : this.innerText  = 'The text has been '
    } else {
        this.innerHTML = 'changed';
        return false;
    }
})

http://jsfiddle.net/YSAjU/

cell format round and display 2 decimal places

Another way is to use FIXED function, you can specify the number of decimal places but it defaults to 2 if the places aren't specified, i.e.

=FIXED(E5,2)

or just

=FIXED(E5)

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

My 2cents is that they should be avoided in two cases:

1) When you have a variable that is used in many rows and you increase/decrease it on the first statement that uses it (or last, or, even worse, in the middle):

// It's Java, but applies to Js too
vi = list.get ( ++i );
vi1 = list.get ( i + 1 )
out.println ( "Processing values: " + vi + ", " + vi1 )
if ( i < list.size () - 1 ) ...

In examples like this, you can easily miss that the variable is auto-incremented/decremented or even remove the first statement. In other words, use it only in very short blocks or where the variable appears in the block on just a couple of close statements.

2) In case of multiple ++ and -- about the same variable in the same statement. It's very hard to remember what happens in cases like this:

result = ( ++x - --x ) * x++;

Exams and professional tests asks about examples like above and indeed I've stumbled upon this question while looking for documentation about one of them, but in real life one shouldn't be forced to think so much about a single line of code.

Execution failed for task ':app:compileDebugAidl': aidl is missing

Check if you actually have installed the buildVersionTools you are using. In my case I tried 25.0.1 whilst I only had 25.0.2.

To check it go to the SDK Manager, clicking the icon:

enter image description here

Then click Launch Standalone SDK Manager at the bottom:

enter image description here

Now check whatever you need and install packages.

enter image description here

Hope it helps!

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Answer replaced (and turned Community Wiki) due to numerous updates and notes from various others in this thread:

  • ICOs and PNGs both allow full alpha channel based transparency
  • ICO allows for backwards compatibility to older browsers (e.g. IE6)
  • PNG probably has broader tooling support for transparency, but you can find tools to create alpha-channel ICOs as well, such as the Dynamic Drive tool and Photoshop plugin mentioned by @mercator.

Feel free to consult the other answers here for more details.

How to select rows with no matching entry in another table?

SELECT * FROM First_table MINUS SELECT * FROM another

I want to multiply two columns in a pandas DataFrame and add the result into a new column

Since this question came up again, I think a good clean approach is using assign.

The code is quite expressive and self-describing:

df = df.assign(Value = lambda x: x.Prices * x.Amount * x.Action.replace({'Buy' : 1, 'Sell' : -1}))

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

Jackson how to transform JsonNode to ArrayNode without casting?

Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode to use. Here's an example:

JSON:

{
    "objects" : ["One", "Two", "Three"]
}

Code:

final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";

final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
    for (final JsonNode objNode : arrNode) {
        System.out.println(objNode);
    }
}

Output:

"One"
"Two"
"Three"

Note the use of isArray to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

This is worked for me, Hope to help someone (Using my own button not FB login button )

CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_sign_in_user);



     LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        Log.i("RESAULTS : ", object.getString("email"));
                    }catch (Exception e){

                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Log.i("RESAULTS : ", error.getMessage());
        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}


boolean isEmailValid(CharSequence email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

public void signupwith_facebook(View view) {

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}

Local and global temporary tables in SQL Server

Local temporary tables: if you create local temporary tables and then open another connection and try the query , you will get the following error.

the temporary tables are only accessible within the session that created them.

Global temporary tables: Sometimes, you may want to create a temporary table that is accessible other connections. In this case, you can use global temporary tables.

Global temporary tables are only destroyed when all the sessions referring to it are closed.

Adb Devices can't find my phone

I did the following to get my Mac to see the devices again:

  • Run android update adb
  • Run adb kill-server
  • Run adb start-server

At this point, calling adb devices started returning devices again. Now run or debug your project to test it on your device.

Update UI from Thread in Android

If you use Handler (I see you do and hopefully you created its instance on the UI thread), then don't use runOnUiThread() inside of your runnable. runOnUiThread() is used when you do smth from a non-UI thread, however Handler will already execute your runnable on UI thread.

Try to do smth like this:

private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gameone);
    res = getResources();
    // pB.setProgressDrawable(getResources().getDrawable(R.drawable.green)); **//Works**
    mHandler.postDelayed(runnable, 1);
}

private Runnable runnable = new Runnable() {
    public void run() {
        pB.setProgressDrawable(getResources().getDrawable(R.drawable.green));
        pB.invalidate(); // maybe this will even not needed - try to comment out
    }
};

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

Accessing a class' member variables in Python?

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

To set a class variable (a.k.a. static member), use

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

Using an image caption in Markdown Jekyll

For Kramdown, you can use {:refdef: style="text-align: center;"} to align center

{:refdef: style="text-align: center;"}
![example](https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg){: width="50%" .shadow}
{: refdef}
{:refdef: style="text-align: center;"}
*Fig.1: This is an example image. [Source](https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg)*
{: refdef}

library not found for -lPods

If Xcode complains when linking, e.g. Library not found for -lPods, it doesn't detect the implicit dependencies.

Go to Product > Edit Scheme Click on Build Add the Pods static library, and make sure it's at the top of the list Clean and build again If that doesn't work, verify that the source for the spec you are trying to include has been pulled from github. Do this by looking in /Pods/. If it is empty (it should not be), verify that the ~/.cocoapods/master//.podspec has the correct git hub url in it. If still doesn't work, check your XCode build locations settings. Go to Preferences -> Locations -> Derived Data -> Advanced and set build location to “Relative to Workspace”.

http://docs.cocoapods.org/guides/getting_started.html

Regex empty string or email

The answers above work ($ for empty), but I just tried this and it also works to just leave empty like so:

/\A(INTENSE_EMAIL_REGEX|)\z/i

Same thing in reverse order

/\A(|INTENSE_EMAIL_REGEX)\z/i

jQuery Mobile Page refresh mechanism

function refreshPage()
{
    jQuery.mobile.changePage(window.location.href, {
        allowSamePageTransition: true,
        transition: 'none',
        reloadPage: true
    });
}

Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0

Rounding numbers to 2 digits after comma

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);

How to get a List<string> collection of values from app.config in WPF?

Had the same problem, but solved it in a different way. It might not be the best solution, but its a solution.

in app.config:

<add key="errorMailFirst" value="[email protected]"/>
<add key="errorMailSeond" value="[email protected]"/>

Then in my configuration wrapper class, I add a method to search keys.

        public List<string> SearchKeys(string searchTerm)
        {
            var keys = ConfigurationManager.AppSettings.Keys;
            return keys.Cast<object>()
                       .Where(key => key.ToString().ToLower()
                       .Contains(searchTerm.ToLower()))
                       .Select(key => ConfigurationManager.AppSettings.Get(key.ToString())).ToList();
        }

For anyone reading this, i agree that creating your own custom configuration section is cleaner, and more secure, but for small projects, where you need something quick, this might solve it.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

The only way that worked for me was with the JRockit JVM. I have MyEclipse 8.6.

The JVM's heap stores all the objects generated by a running Java program. Java uses the new operator to create objects, and memory for new objects is allocated on the heap at run time. Garbage collection is the mechanism of automatically freeing up the memory contained by the objects that are no longer referenced by the program.

How can I escape a single quote?

If for some reason you cannot escape the apostrophe character and you can't change it into a HTML entity (as it was in my case for a specific Vue.js property) you can use replace to change it into different apostrophe character from the UTF8 characters set, for instance:

' - U+02BC
’ - U+2019

How to install python-dateutil on Windows?

Just run command prompt as administrator and type this in.

easy_install python-dateutil

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

Recently I had this same problem on windows 10 - after installing Hyper-V & other windows features like:

Windows Projected File System, Windows Sandbox, Windows Subsystem for Linux, Work Folders Client,

And it stopped working for me;(

  1. Step uninstall Hyper-V -check if ti stared to work for you - no in my case
  2. Step uninstall other windows features mentioned above! - I worked for me;) enter image description here

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

Batch / Find And Edit Lines in TXT file

You can do like this:

rename %CURR_DIR%\ftp\mywish1.txt text.txt
for /f %%a in (%CURR_DIR%\ftp\text.txt) do (
if "%%a" EQU "ex3" ( 
echo ex5 >> %CURR_DIR%\ftp\mywish1.txt
) else (
echo %%a >> %CURR_DIR%\ftp\mywish1.txt
)
)
del %CURR_DIR%\ftp\text.txt

How to display my application's errors in JSF?

FacesContext.addMessage(String, FacesMessage) requires the component's clientId, not it's id. If you're wondering why, think about having a control as a child of a dataTable, stamping out different values with the same control for each row - it would be possible to have a different message printed for each row. The id is always the same; the clientId is unique per row.

So "myform:mybutton" is the correct value, but hard-coding this is ill-advised. A lookup would create less coupling between the view and the business logic and would be an approach that works in more restrictive environments like portlets.

<f:view>
  <h:form>
    <h:commandButton id="mybutton" value="click"
      binding="#{showMessageAction.mybutton}"
      action="#{showMessageAction.validatePassword}" />
    <h:message for="mybutton" />
  </h:form>
</f:view>

Managed bean logic:

/** Must be request scope for binding */
public class ShowMessageAction {

    private UIComponent mybutton;

    private boolean isOK = false;

    public String validatePassword() {
        if (isOK) {
            return "ok";
        }
        else {
            // invalid
            FacesMessage message = new FacesMessage("Invalid password length");
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(mybutton.getClientId(context), message);
        }
        return null;
    }

    public void setMybutton(UIComponent mybutton) {
        this.mybutton = mybutton;
    }

    public UIComponent getMybutton() {
        return mybutton;
    }
}

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

in my case i was using compile sdk 23 and build tools 25.0.0 just changed compile sdk to 25 and done..

Set Google Chrome as the debugging browser in Visual Studio

Click on the arrow near by start button there you will get list of browser. Select the browser you want your application to be run with and click on "Set as Default" Click ok and you are done with this.

Convert int to a bit array in .NET

To convert the int 'x'

int x = 3;

One way, by manipulation on the int :

string s = Convert.ToString(x, 2); //Convert to binary in a string

int[] bits= s.PadLeft(8, '0') // Add 0's from left
             .Select(c => int.Parse(c.ToString())) // convert each char to int
             .ToArray(); // Convert IEnumerable from select to Array

Alternatively, by using the BitArray class-

BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Check if file is already open

On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using

fileIsLocked = !file.renameTo(file)

most useful, as it avoids false positives when processing write protected (or readonly) files.

How to print a stack trace in Node.js?

Try Error.captureStackTrace(targetObject[, constructorOpt]).

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

The function a and b are captured in error stack and stored in myObj.

node.js execute system command synchronously

This is the easiest way I found:

exec-Sync: https://github.com/jeremyfa/node-exec-sync
(Not to be confused with execSync.)
Execute shell command synchronously. Use this for migration scripts, cli programs, but not for regular server code.

Example:

var execSync = require('exec-sync');   
var user = execSync('echo $USER');
console.log(user);

test attribute in JSTL <c:if> tag

<%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string

Is there a way to @Autowire a bean that requires constructor arguments?

I like Zakaria's answer, but if you're in a project where your team doesn't want to use that approach, and you're stuck trying to construct something with a String, integer, float, or primative type from a property file into the constructor, then you can use Spring's @Value annotation on the parameter in the constructor.

For example, I had an issue where I was trying to pull a string property into my constructor for a class annotated with @Service. My approach works for @Service, but I think this approach should work with any spring java class, if it has an annotation (such as @Service, @Component, etc.) which indicate that Spring will be the one constructing instances of the class.

Let's say in some yaml file (or whatever configuration you're using), you have something like this:

some:
    custom:
        envProperty: "property-for-dev-environment"

and you've got a constructor:

@Service // I think this should work for @Component, or any annotation saying Spring is the one calling the constructor.
class MyClass {
...
    MyClass(String property){
    ...
    }
...
}

This won't run as Spring won't be able to find the string envProperty. So, this is one way you can get that value:

class MyDynamoTable
import org.springframework.beans.factory.annotation.Value;
...
    MyDynamoTable(@Value("${some.custom.envProperty}) String property){
    ...
    }
...

In the above constructor, Spring will call the class and know to use the String "property-for-dev-environment" pulled from my yaml configuration when calling it.

NOTE: this I believe @Value annotation is for strings, intergers, and I believe primative types. If you're trying to pass custom classes (beans), then approaches in answers defined above work.

How to change default JRE for all Eclipse workspaces?

In eclipse go to

Window-> Java -> Installed JREs

You can remove your current installed jre and add the jdk by specifying the path to where the jdk is installed.

enter image description here

Can I mask an input text in a bat file?

make a batch file that calls the one needed for invisible characters then make a shortcut for the batch file being called.

right click

properties

colors

text==black

background == black

apply

ok

hope thus helps you!!!!!!!!

How to git clone a specific tag

Use --single-branch option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.

git clone <repo_url> --branch <tag_name> --single-branch

Regular expression to match DNS hostname or IP Address?

This works for valid IP addresses:

regex = '^([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])$'

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.

I would check your application servers SSL settings and make sure that the certification is configured correctly.

Xamarin.Forms ListView: Set the highlight color of a tapped item

I have a similar process, completely cross platform, however I track the selection status myself and I have done this in XAML.

<ListView x:Name="ListView" ItemsSource="{Binding ListSource}" RowHeight="50">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <ViewCell.View>
          <ContentView Padding="10" BackgroundColor="{Binding BackgroundColor}">
            <Label Text="{Binding Name}" HorizontalOptions="Center" TextColor="White" />
          </ContentView>
        </ViewCell.View>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

Then in the ItemTapped Event

ListView.ItemTapped += async (s, e) =>
{
    var list = ListSource;
    var listItem = list.First(c => c.Id == ((ListItem)e.Item).Id);
    listItem.Selected = !listItem.Selected;
    SelectListSource = list;
    ListView.SelectedItem = null;
};

As you can see I just set the ListView.SelectedItem to null to remove any of the platform specific selection styles that come into play.

In my model I have

private Boolean _selected;

public Boolean Selected
{
    get => _selected;
    set
    {
        _selected = value;
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("BackgroundColor"));
    }
}

public Color BackgroundColor
{
    get => Selected ? Color.Black : Color.Blue;
}

Getting files by creation date in .NET

This returns the last modified date and its age.

DateTime.Now.Subtract(System.IO.File.GetLastWriteTime(FilePathwithName).Date)

How to use Git Revert

The question is quite old but revert is still confusing people (like me)

As a beginner, after some trial and error (more errors than trials) I've got an important point:

  • git revert requires the id of the commit you want to remove keeping it into your history

  • git reset requires the commit you want to keep, and will consequentially remove anything after that from history.

That is, if you use revert with the first commit id, you'll find yourself into an empty directory and an additional commit in history, while with reset your directory will be.. reverted back to the initial commit and your history will get as if the last commit(s) never happened.

To be even more clear, with a log like this:

# git log --oneline

cb76ee4 wrong
01b56c6 test
2e407ce first commit

Using git revert cb76ee4 will by default bring your files back to 01b56c6 and will add a further commit to your history:

8d4406b Revert "wrong"
cb76ee4 wrong
01b56c6 test
2e407ce first commit

git reset 01b56c6 will instead bring your files back to 01b56c6 and will clean up any other commit after that from your history :

01b56c6 test
2e407ce first commit

I know these are "the basis" but it was quite confusing for me, by running revert on first id ('first commit') I was expecting to find my initial files, it taken a while to understand, that if you need your files back as 'first commit' you need to use the next id.

How can I trim leading and trailing white space?

As of R 3.2.0 a new function was introduced for removing leading/trailing white spaces:

trimws()

See: Remove Leading/Trailing Whitespace

Error 1022 - Can't write; duplicate key in table

This can also arise in connection with a bug in certain versions of Percona Toolkit's online-schema-change tool. To mutate a large table, pt-osc first creates a duplicate table and copies all the records into it. Under some circumstances, some versions of pt-osc 2.2.x will try to give the constraints on the new table the same names as the constraints on the old table.

A fix was released in 2.3.0.

See https://bugs.launchpad.net/percona-toolkit/+bug/1498128 for more details.

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Lazy Loading vs Eager Loading

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();
    }
}

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

PHP Warning: Unknown: failed to open stream

It happened to me today with /home/user/public_html/index.php and the solution was to do chmod o+x /home/user as this directory has to have the X as otherwise the apache server can't list files (i.e. do ls)

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

Iterate through string array in Java

    String[] nameArray= {"John", "Paul", "Ringo", "George"};
    int numberOfItems = nameArray.length;
    for (int i=0; i<numberOfItems; i++)
    {
        String name = nameArray[i];
        System.out.println("Hello " + name);
    }

How to return a string value from a Bash function

#Implement a generic return stack for functions:

STACK=()
push() {
  STACK+=( "${1}" )
}
pop() {
  export $1="${STACK[${#STACK[@]}-1]}"
  unset 'STACK[${#STACK[@]}-1]';
}

#Usage:

my_func() {
  push "Hello world!"
  push "Hello world2!"
}
my_func ; pop MESSAGE2 ; pop MESSAGE1
echo ${MESSAGE1} ${MESSAGE2}

How to check the extension of a filename in a bash script?

You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

file -ib "$file"

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

cleanup php session files

You can create script /etc/cron.hourly/php and put there:

#!/bin/bash

max=24
tmpdir=/tmp

nice find ${tmpdir} -type f -name 'sess_*' -mmin +${max} -delete

Then make the script executable (chmod +x).

Now every hour will be deleted all session files with data modified more than 24 minutes ago.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.

This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!

  • The Video shows you the JavaFx Sdk download
  • How to set it as a Global Library
  • Set the module-info.java (i prefer the bottom one)

module thisIsTheNameOfYourProject {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens sample;
}

The entire thing took me only 5mins !!!

Detecting request type in PHP (GET, POST, PUT or DELETE)

By using

$_SERVER['REQUEST_METHOD']

Example

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // The request is using the POST method
}

For more details please see the documentation for the $_SERVER variable.

Python pip install module is not found. How to link python to pip location?

No other solutions were working for me, so I tried:

pip uninstall <module> && pip install <module>

And that resolved it for me. Your mileage may vary.

Error when deploying an artifact in Nexus

Cause of problem for me was -source.jars was getting uploaded twice (with maven-source-plugin) as mentioned as one of the cause in accepted answer. Redirecting to answer that I referred: Maven release plugin fails : source artifacts getting deployed twice

wget/curl large file from google drive

The default behavior of google drive is to scan files for viruses if the file is to big it will prompte the user and notifies him that the file could not be scanned.

At the moment the only workaround I found is to share the file with the web and create a web resource.

Quote from the google drive help page:

With Drive, you can make web resources — like HTML, CSS, and Javascript files — viewable as a website.

To host a webpage with Drive:

  1. Open Drive at drive.google.com and select a file.
  2. Click the Share button at the top of the page.
  3. Click Advanced in the bottom right corner of the sharing box.
  4. Click Change....
  5. Choose On - Public on the web and click Save.
  6. Before closing the sharing box, copy the document ID from the URL in the field below "Link to share". The document ID is a string of uppercase and lowercase letters and numbers between slashes in the URL.
  7. Share the URL that looks like "www.googledrive.com/host/[doc id] where [doc id] is replaced by the document ID you copied in step 6.
    Anyone can now view your webpage.

Found here: https://support.google.com/drive/answer/2881970?hl=en

So for example when you share a file on google drive publicly the sharelink looks like this:

https://drive.google.com/file/d/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U/view?usp=sharing

Then you copy the file id and create a googledrive.com linke that look like this:

https://www.googledrive.com/host/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U

How to find path of active app.config file?

The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

Problem solved

I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.

When do you use map vs flatMap in RxJava?

The question is When do you use map vs flatMap in RxJava?. And I think a simple demo is more specific.

When you want to convert item emitted to another type , in your case converting file to String, map and flatMap can both work. But I prefer map operator because it's more clearly.

However in some place, flatMap can do magic work but map can't. For example, I want to get a user's info but I have to first get his id when user login in. Obviously I need two requests and they are in order.

Let's begin.

Observable<LoginResponse> login(String email, String password);

Observable<UserInfo> fetchUserInfo(String userId);

Here are two methods, one for login returned Response, and another for fetching user info.

login(email, password)
        .flatMap(response ->
                fetchUserInfo(response.id))
        .subscribe(userInfo -> {
            // get user info and you update ui now
        });

As you see, in function flatMap applies, at first I get user id from Response then fetch user info. When two requests are finished, we can do our job such as updating UI or save data into database.

However if you use map you can't write such nice code. In a word, flatMap can help us serialize requests.

Find Number of CPUs and Cores per CPU using Command Prompt

In order to check the absence of physical sockets run:

wmic cpu get SocketDesignation

How to check the multiple permission at single request in Android M?

First initialize permission request code

public  static final int PERMISSIONS_MULTIPLE_REQUEST = 123;

Check android version

 private void checkAndroidVersion() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkPermission();

    } else {
        // write your logic here
    }

}

check multiple permission code

 private void checkPermission() {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
            .checkSelfPermission(getActivity(),
                    Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale
                (getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                ActivityCompat.shouldShowRequestPermissionRationale
                        (getActivity(), Manifest.permission.CAMERA)) {

      Snackbar.make(getActivity().findViewById(android.R.id.content),
                    "Please Grant Permissions to upload profile photo",
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            requestPermissions(
                                    new String[]{Manifest.permission
                                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                    PERMISSIONS_MULTIPLE_REQUEST);
                        }
                    }).show();
        } else {
            requestPermissions(
                    new String[]{Manifest.permission
                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                    PERMISSIONS_MULTIPLE_REQUEST);
        }
    } else {
        // write your logic code if permission already granted
    }
}

call back method after grant permission by user

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case PERMISSIONS_MULTIPLE_REQUEST:
            if (grantResults.length > 0) {
               boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
               boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                if(cameraPermission && readExternalFile)
                {
                    // write your logic here 
                } else {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                        "Please Grant Permissions to upload profile photo",
                        Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestPermissions(
                                        new String[]{Manifest.permission
                                                .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                        PERMISSIONS_MULTIPLE_REQUEST);
                            }
                        }).show();
                }
           }
           break;
    }
}

How does a Linux/Unix Bash script know its own PID?

The variable '$$' contains the PID.

How to get UTC+0 date in Java 8?

tl;dr

Instant.now()

java.time

The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Instant

An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds.

Instant instant = Instant.now();

The toString method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.

String output = instant.toString();  

2016-06-27T19:15:25.864Z

The Instant class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.

OffsetDateTime

But Instant has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant to OffsetDateTime. Specify an offset-from-UTC. In java.time that means a ZoneOffset object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

2016-06-27T19:15:25.864Z

Or skip the Instant class.

OffsetDateTime.now( ZoneOffset.UTC )

Now with an OffsetDateTime object in hand, you can use DateTimeFormatter to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter.

ZonedDateTime

When you want to display wall-clock time for some particular time zone, apply a ZoneId to get a ZonedDateTime.

In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00. So note how the time-of-day is four hours earlier in the output, 15 instead of 19 hours. Instant and the ZonedDateTime both represent the very same simultaneous moment, just viewed through two different lenses.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

2016-06-27T15:15:25.864-04:00[America/Montreal]

Converting

While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant ) and java.util.Date::toInstant.

java.util.Date utilDate = java.util.Date.from( instant );

And going the other direction.

Instant instant= utilDate.toInstant();

Similarly, look for new methods added to GregorianCalendar (subclass of Calendar) to convert to and from java.time.ZonedDateTime.

Table of types of date-time classes in modern java.time versus legacy.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

How do I run Java .class files?

To run Java class file from the command line, the syntax is:

java -classpath /path/to/jars <packageName>.<MainClassName>

where packageName (usually starts with either com or org) is the folder name where your class file is present.

For example if your main class name is App and Java package name of your app is com.foo.app, then your class file needs to be in com/foo/app folder (separate folder for each dot), so you run your app as:

$ java com.foo.app.App

Note: $ is indicating shell prompt, ignore it when typing

If your class doesn't have any package name defined, simply run as: java App.

If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp/-classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.).


Practical example

Given we've created sample project using Maven as:

$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

and we've compiled our project by mvn compile in our my-app/ dir, it'll generate our class file is in target/classes/com/foo/app/App.class.

To run it, we can either specify class path via -cp or going to it directly, check examples below:

$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!

To double check your class and package name, you can use Java class file disassembler tool, e.g.:

$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
  public com.foo.app.App();
  public static void main(java.lang.String[]);
}

Note: javap won't work if the compiled file has been obfuscated.

Split string into string array of single characters

You can just use String.ToCharArray() and then treat each char as a string in your code.

Here's an example:

    foreach (char c in s.ToCharArray())
        Debug.Log("one character ... " +c);

iptables block access to port 8000 except from IP address

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.  

REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

Convert and format a Date in JSP

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.Locale"%>

<html>
<head>
<title>Date Format</title>
</head>
<body>
<%
String stringDate = "Fri May 13 2011 19:59:09 GMT 0530";
Date stringDate1 = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.ENGLISH).parse(stringDate);
String stringDate2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stringDate1);

out.println(stringDate2);
%>
</body>
</html>

How to detect when a UIScrollView has finished scrolling

If you're into Rx, you can extend UIScrollView like this:

import RxSwift
import RxCocoa

extension Reactive where Base: UIScrollView {
    public var didEndScrolling: ControlEvent<Void> {
        let source = Observable
            .merge([base.rx.didEndDragging.map { !$0 },
                    base.rx.didEndDecelerating.mapTo(true)])
            .filter { $0 }
            .mapTo(())
        return ControlEvent(events: source)
    }
}

which will allow you to just do like this:

scrollView.rx.didEndScrolling.subscribe(onNext: {
    // Do what needs to be done here
})

This will take into account both dragging and deceleration.

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

Converting camel case to underscore case in ruby

Receiver converted to snake case: http://rubydoc.info/gems/extlib/0.9.15/String#snake_case-instance_method

This is the Support library for DataMapper and Merb. (http://rubygems.org/gems/extlib)

def snake_case
  return downcase if match(/\A[A-Z]+\z/)
  gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
  gsub(/([a-z])([A-Z])/, '\1_\2').
  downcase
end

"FooBar".snake_case           #=> "foo_bar"
"HeadlineCNNNews".snake_case  #=> "headline_cnn_news"
"CNN".snake_case              #=> "cnn"

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Your server's response allows the request to include three specific non-simple headers:

Access-Control-Allow-Headers:origin, x-requested-with, content-type

but your request has a header not allowed by the server's response:

Access-Control-Request-Headers:access-control-allow-origin, content-type

All non-simple headers sent in a CORS request must be explicitly allowed by the Access-Control-Allow-Headers response header. The unnecessary Access-Control-Allow-Origin header sent in your request is not allowed by the server's CORS response. This is exactly what the "...not allowed by Access-Control-Allow-Headers" error message was trying to tell you.

There is no reason for the request to have this header: it does nothing, because Access-Control-Allow-Origin is a response header, not a request header.

Solution: Remove the setRequestHeader call that adds a Access-Control-Allow-Origin header to your request.

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

RSA: Get exponent and modulus given a public key

It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.

Command-line / OpenSSL

If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----

Then, the commands would be:

PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`

Then, you can look into the ASN.1 structure:

echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i

This should give you something like this:

    0:d=0  hl=4 l= 290 cons: SEQUENCE          
    4:d=1  hl=2 l=  13 cons:  SEQUENCE          
    6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
   17:d=2  hl=2 l=   0 prim:   NULL              
   19:d=1  hl=4 l= 271 prim:  BIT STRING 

The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse:

 echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19

This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim:  INTEGER           :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
  265:d=1  hl=2 l=   3 prim:  INTEGER           :010001

That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.

Alternatively (and this might be easier to put into a script),

openssl rsa -pubin -inform PEM -text -noout < public.key

will return this:

Modulus (2048 bit):
    00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
    0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
    bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
    69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
    d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
    88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
    ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
    1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
    a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
    e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
    67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
    67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
    70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
    cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
    64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
    da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
    f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
    21:1d
Exponent: 65537 (0x10001)

Java

It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.

If it's in the format as above, you might want to use BouncyCastle and its PEMReader to read it. I haven't tried the following code, but this would look more or less like this:

PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
   // Just in case your file contains in fact an X.509 certificate,
   // useless otherwise.
   obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
   // ... use the getters to get the BigIntegers.
}

(You can use BouncyCastle similarly in C# too.)

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Have a look at ImmutableMap JavaDoc: doc

There is information about that there:

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

c# replace \" characters

In .NET Framework 4 and MVC this is the only representation that worked:

Replace(@"""","")

Using a backslash in whatever combination did not work...

Display last git commit comment

To start with git log -1 --pretty='%s'

But the below one covers all the cases,

git log --pretty='format:%Creset%s' --no-merges -1

  • No unwanted white spaces
  • Discards merge commits
  • No commit id, date, Displays only the messages.

Paste & see for yourself

How to force maven update?

I've got the error in an other context. So my solution might be useful to others who stumple upon the question:

The problem: I've copied the local repository to another computer, which has no connection to a special repository. So maven tried to check the artifacts against the invalid repository.

My solution: Remove the _maven.repositories files.

How to write log to file

I'm writing logs to the files, which are generate on daily basis (per day one log file is getting generated). This approach is working fine for me :

var (
    serverLogger *log.Logger
)

func init() {
    // set location of log file
    date := time.Now().Format("2006-01-02")
    var logpath = os.Getenv(constant.XDirectoryPath) + constant.LogFilePath + date + constant.LogFileExtension
    os.MkdirAll(os.Getenv(constant.XDirectoryPath)+constant.LogFilePath, os.ModePerm)
    flag.Parse()
    var file, err1 = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

    if err1 != nil {
        panic(err1)
    }
    mw := io.MultiWriter(os.Stdout, file)
    serverLogger = log.New(mw, constant.Empty, log.LstdFlags)
    serverLogger.Println("LogFile : " + logpath)
}

// LogServer logs to server's log file
func LogServer(logLevel enum.LogLevel, message string) {
    _, file, no, ok := runtime.Caller(1)
    logLineData := "logger_server.go"
    if ok {
        file = shortenFilePath(file)
        logLineData = fmt.Sprintf(file + constant.ColonWithSpace + strconv.Itoa(no) + constant.HyphenWithSpace)
    }
    serverLogger.Println(logLineData + logLevel.String() + constant.HyphenWithSpace + message)
}

// ShortenFilePath Shortens file path to a/b/c/d.go tp d.go
func shortenFilePath(file string) string {
    short := file
    for i := len(file) - 1; i > 0; i-- {
        if file[i] == constant.ForwardSlash {
            short = file[i+1:]
            break
        }
    }
    file = short
    return file
}

"shortenFilePath()" method used to get the name of the file from full path of file. and "LogServer()" method is used to create a formatted log statement (contains : filename, line number, log level, error statement etc...)

Difference between attr_accessor and attr_accessible

A quick & concise difference overview :

attr_accessor is an easy way to create read and write accessors in your class. It is used when you do not have a column in your database, but still want to show a field in your forms. This field is a “virtual attribute” in a Rails model.

virtual attribute – an attribute not corresponding to a column in the database.

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.

Convert DOS line endings to Linux line endings in Vim

With the following command:

:%s/^M$//g

To get the ^M to appear, type CtrlV and then CtrlM. CtrlV tells Vim to take the next character entered literally.

Is there something like Codecademy for Java

Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

To get rid of the error, roll back the last (erroneous) transaction after you've fixed your code:

from django.db import transaction
transaction.rollback()

You can use try-except to prevent the error from occurring:

from django.db import transaction, DatabaseError
try:
    a.save()
except DatabaseError:
    transaction.rollback()

Refer : Django documentation

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

How to change the name of an iOS app?

Using Javier's approach to rename my app works perfectly. There is just one small bit missing in the end that I wanted add.

I still ended up getting a Mach-O Linker Error after a Clean and Rebuild. To resolve this; select yourProject(in the Project Navigator) > under Targets select yourProjectTests(the test target) > under the General tab, update the Host Application's value to the newly renamed project.

How to rebuild docker container in docker-compose.yml?

This should fix your problem:

docker-compose ps # lists all services (id, name)
docker-compose stop <id/name> #this will stop only the selected container
docker-compose rm <id/name> # this will remove the docker container permanently 
docker-compose up # builds/rebuilds all not already built container 

Efficient way to rotate a list in python

For a list X = ['a', 'b', 'c', 'd', 'e', 'f'] and a desired shift value of shift less than list length, we can define the function list_shift() as below

def list_shift(my_list, shift):
    assert shift < len(my_list)
    return my_list[shift:] + my_list[:shift]

Examples,

list_shift(X,1) returns ['b', 'c', 'd', 'e', 'f', 'a'] list_shift(X,3) returns ['d', 'e', 'f', 'a', 'b', 'c']

Toad for Oracle..How to execute multiple statements?

If you have Multiple Insert Statements then Toad has a simple Way to execute all the Insert Statements.

Right Click On the Highlighted Insert Statements --> Select Execute Menu --> Execute Script

This will automatically start running the Insert Statements

How to use a servlet filter in Java to change an incoming servlet request url?

You could use the ready to use Url Rewrite Filter with a rule like this one:

<rule>
  <from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
  <to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>

Check the Examples for more... examples.

How to log request and response body with Retrofit-Android?

I hope this code will help you to logging .
you just need to add interceptor in your Build.Gradle then make RetrofitClient .

First Step

Add this line to your build.gradle

 implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1' 

Second Step

Make your Retrofit Client


   public class RetrofitClient {

    private Retrofit retrofit;
    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();
    private static RetrofitClient instance = null;
    private static ApiServices service = null;
    private static HttpLoggingInterceptor logging =
            new HttpLoggingInterceptor();

    private RetrofitClient(final Context context) {
        httpClient.interceptors().add(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder builder = originalRequest.newBuilder().
                        method(originalRequest.method(), originalRequest.body());
                okhttp3.Response response = chain.proceed(builder.build());
                /*
                Do what you want
                 */
                return response;
            }
        });

        if (BuildConfig.DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            // add logging as last interceptor
            httpClient.addInterceptor(logging);
        }

        retrofit = new Retrofit.Builder().client(httpClient.build()).
                baseUrl(Constants.BASE_URL).
                addConverterFactory(GsonConverterFactory.create()).build();
        service = retrofit.create(ApiServices.class);
    }


    public static RetrofitClient getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitClient(context);
        }
        return instance;
    }

    public ApiServices getApiService() {
        return service;
    }
}

Calling

RetrofitClient.getInstance(context).getApiService().yourRequestCall(); 

Is there a <meta> tag to turn off caching in all browsers?

This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.

http://securityevaluators.com/knowledge/case_studies/caching/

In summary, according to this article, only Cache-Control: no-store is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.

How do I import a specific version of a package using go get?

Nowadays you can just use go get for it. You can fetch your dependency by the version tag, branch or even the commit.

go get github.com/someone/some_module@master
go get github.com/someone/[email protected]
go get github.com/someone/some_module@commit_hash

more details here - How to point Go module dependency in go.mod to a latest commit in a repo?

Go get will also install the binary, like it says in the documentation -

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

(from https://golang.org/cmd/go/)

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

Read HttpContent in WebApi controller

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.

The first read in your case is being done when Web API is binding your model, after that the Request.Content will not return anything.

You can remove the contact from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):

[HttpPut]
public HttpResponseMessage Put(int accountId)
{
    HttpContent requestContent = Request.Content;
    string jsonContent = requestContent.ReadAsStringAsync().Result;
    CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
    ...
}

That should do the trick (assuming that accountId is URL parameter so it will not be treated as content read).

JPA Query selecting only specific columns without using Criteria Query?

Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10. The result of the query will be a List of array of Object. The first element in each array is the value of i.foo and the second element is the value i.bar. See the relevant section of JPQL reference.

Traverse a list in reverse order in Python

Assuming task is to find last element that satisfies some condition in a list (i.e. first when looking backwards), I'm getting following numbers:

>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.6937971115112305
>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.809093952178955
>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n    if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
4.931743860244751
>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n    if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
5.548468112945557
>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n    if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))
6.286104917526245
>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n    i -= 1\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
8.384078979492188

So, the ugliest option xrange(len(xs)-1,-1,-1) is the fastest.

Format of the initialization string does not conform to specification starting at index 0

I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.

Changed from this

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />

To

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />

How to check version of python modules?

Quick python program to list all packges (you can copy it to requirements.txt)

from pip._internal.utils.misc import get_installed_distributions
print_log = ''
for module in sorted(get_installed_distributions(), key=lambda x: x.key): 
    print_log +=  module.key + '~=' + module.version  + '\n'
print(print_log)

The output would look like:

asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98

FFmpeg: How to split video efficiently?

Didn't test ist, but this looks promising:

Basic stream segmenter

It is obviously splitting AVI into segments of same size, which implies these chunks don't loose quality or increase memory or must be recalculated.

It also uses the codec copy - does that mean it can handle very large streams ? Because this is my problem, i want to break down my avi so i could use a filter to get rid of the distorsion. But a whole avi runs for hours.