Programs & Examples On #Mde

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Make sure these two are the same version in your app level build.gradle file

    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:design:27.1.1'

I think that should solve the problem

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Android Studio 3.0 Execution failed for task: unable to merge dex

To remove this Dex issue just implement one dependency. This issue occur when we are using multiple different service from the same server. Suppose we are using ads and Firestore in a project and both have a repository maven. so we need to call different data with on repository we need dex dependency to implement. The new update Dependency:-

 implementation 'com.android.support:multidex:1.0.3'

I'm sure it will resolve your issue permanent

Unable to merge dex

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xyz.name"
        minSdkVersion 14
        targetSdkVersion 27
        versionCode 7
        versionName "1.6"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.wang.avi:library:2.1.3'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'de.hdodenhof:circleimageview:2.1.0'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.0'
    implementation 'com.loopj.android:android-async-http:1.4.9'
    implementation 'com.google.firebase:firebase-messaging:11.8.0'
    implementation 'com.felipecsl.asymmetricgridview:library:2.0.1'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    implementation 'com.github.darsh2:MultipleImageSelect:3474549'
    implementation 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
    implementation 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'

Note: update your all support library to 27.1.0 like above and remove duplicates

How to change the integrated terminal in visual studio code or VSCode

If you want to change the external terminal to the new windows terminal, here's how.

How do I select which GPU to run a job on?

The problem was caused by not setting the CUDA_VISIBLE_DEVICES variable within the shell correctly.

To specify CUDA device 1 for example, you would set the CUDA_VISIBLE_DEVICES using

export CUDA_VISIBLE_DEVICES=1

or

CUDA_VISIBLE_DEVICES=1 ./cuda_executable

The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.

If you want to specify more than one device, use

export CUDA_VISIBLE_DEVICES=0,1

or

CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable

ImportError: No module named google.protobuf

I encountered the same situation. And I find out it is because the pip should be updated. It may be the same reason for your problem.

IE and Edge fix for object-fit: cover;

I achieved satisfying results with:

min-height: 100%;
min-width: 100%;

this way you always maintain the aspect ratio.

The complete css for an image that will replace "object-fit: cover;":

width: auto;
height: auto;
min-width: 100%;
min-height: 100%;
position: absolute;
right: 50%;
transform: translate(50%, 0);

android : Error converting byte to dex

Please add this block inside android in build.gradle

dexOptions { preDexLibraries = false }

npm install -g less does not work: EACCES: permission denied

I have tried all the suggested solutions but nothing worked.

I am using macOS Catalina 10.15.3

Go to /usr/local/

Select bin folder > Get Info

Add your user to Sharing & Permissions. Read & Write Permissions. enter image description here

And go to terminal and run npm install -g @ionic/cli

It has helped me.

Recyclerview inside ScrollView not scrolling smoothly

Try doing:

RecyclerView v = (RecyclerView) findViewById(...);
v.setNestedScrollingEnabled(false);

As an alternative, you can modify your layout using the support design library. I guess your current layout is something like:

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with custom layoutmanager -->

   </LinearLayout >
</ScrollView >

You can modify that to:

<CoordinatorLayout >

    <AppBarLayout >
        <CollapsingToolbarLayout >
             <!-- with your content, and layout_scrollFlags="scroll" -->
        </CollapsingToolbarLayout >
    </AppBarLayout >

    <RecyclerView > <!-- with standard layoutManager -->

</CoordinatorLayout >

However this is a longer road to take, and if you are OK with the custom linear layout manager, then just disable nested scrolling on the recycler view.

Edit (4/3/2016)

The v 23.2 release of the support libraries now includes a factory “wrap content” feature in all default LayoutManagers. I didn’t test it, but you should probably prefer it to that library you were using.

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with wrap_content -->

   </LinearLayout >
</ScrollView >

LocalDate to java.util.Date and vice versa simplest conversion?

Date -> LocalDate:

LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate -> Date:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

Error 405 (Method Not Allowed) Laravel 5

When use method delete in form then must have to set route delete

Route::delete("empresas/eliminar/{id}", "CompaniesController@delete");

How can a divider line be added in an Android RecyclerView?

Try this simple single line code

recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL)); 

Hadoop cluster setup - java.net.ConnectException: Connection refused

From the netstat output you can see the process is listening on address 127.0.0.1

tcp        0      0 127.0.0.1:9000          0.0.0.0:*  ...

from the exception message you can see that it tries to connect to address 127.0.1.1

java.net.ConnectException: Call From marta-komputer/127.0.1.1 to localhost:9000 failed ...

further in the exception it's mentionend

For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

on this page you find

Check that there isn't an entry for your hostname mapped to 127.0.0.1 or 127.0.1.1 in /etc/hosts (Ubuntu is notorious for this)

so the conclusion is to remove this line in your /etc/hosts

127.0.1.1       marta-komputer

Why can I not create a wheel in python?

Update your pip first:

pip install --upgrade pip

for Python 3:

pip3 install --upgrade pip

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

Alternatively if you want to persist in using the DocumentType class. Then you could just add the following annotation on top of your DocumentType class.

    @XmlRootElement(name="document")

Note: the String value "document" refers to the name of the root tag of the xml message.

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

Using msbuild to execute a File System Publish Profile

First check the Visual studio version of the developer PC which can publish the solution(project). as shown is for VS 2013

 /p:VisualStudioVersion=12.0

add the above command line to specify what kind of a visual studio version should build the project. As previous answers, this might happen when we are trying to publish only one project, not the whole solution.

So the complete code would be something like this

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" "C:\Program Files (x86)\Jenkins\workspace\Jenkinssecondsample\MVCSampleJenkins\MVCSampleJenkins.csproj" /T:Build;Package /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG" /p:DeployIisAppPath="Default Web Site/jenkinsdemoapp" /p:VisualStudioVersion=12.0

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

Android + Pair devices via bluetooth programmatically

The Best way is do not use any pairing code. Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.

or see this link for better understanding

Below is code for the same:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);

      // **add this 2 line code** 
       Intent myIntent = new Intent(view.getContext(), Connect.class);
        startActivityForResult(myIntent, 0);

        finish();
    }
};

Connect.java file is :

public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
 private InputStream in;
 byte[] arrayOfByte = new byte[4096];
 int bytes;


  public BluetoothDevice mDevice;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);



              try {
                setup();
            } catch (ZeoMessageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ZeoMessageParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

 private void setup() throws ZeoMessageException, ZeoMessageParseException  {
    // TODO Auto-generated method stub

        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                    getRemoteDevice("**:**:**:**:**:**");// add device mac adress

            try {
                sock = zee.createRfcommSocketToServiceRecord(
                         UUID.fromString("*******************")); // use unique UUID
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d(TAG, "++++ Connecting");
            try {
                sock.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.d(TAG, "++++ Connected");


            try {
                in = sock.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

              Log.d(TAG, "++++ Listening...");

              while (true) {

                  try {
                      bytes = in.read(arrayOfByte);
                      Log.d(TAG, "++++ Read "+ bytes +" bytes");  
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                        Log.d(TAG, "++++ Done: test()"); 

                        }} 




 private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.d("ZeoReceiver", paramAnonymousIntent.toString());
            Bundle extras = paramAnonymousIntent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeoReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }


    };

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
 }

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

Why can I ping a server but not connect via SSH?

Find out two pieces of information

  • Whats the hostname or IP of the target ssh server
  • What port is the ssh daemon listening on (default is port 22)

$> telnet <hostname or ip> <port>

Assuming the daemon is up and running and listening on that port it should etablish a telnet session. Likely causes:

  • The ssh daemon is not running
  • The host is blocking the target port with its software firewall
  • Some intermediate network device is blocking or filtering the target port
  • The ssh daemon is listening on a non standard port
  • A TCP wrapper is configured and is filtering out your source host

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

configure: error: C compiler cannot create executables

Make sure there are no spaces in your Xcode application name (can happen if you keep older versions around - for example renaming it 'Xcode 4.app'); build tools will be referenced within the Xcode bundle paths, and many scripts can't handle references with spaces properly.

Download file inside WebView

If you don't want to use a download manager then you can use this code

webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition
                    , String mimetype, long contentLength) {

                String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);

                try {
                    String address = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
                            + Environment.DIRECTORY_DOWNLOADS + "/" +
                            fileName;
                    File file = new File(address);
                    boolean a = file.createNewFile();

                    URL link = new URL(url);
                    downloadFile(link, address);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

 public void downloadFile(URL url, String outputFileName) throws IOException {

        try (InputStream in = url.openStream();
             ReadableByteChannel rbc = Channels.newChannel(in);
             FileOutputStream fos = new FileOutputStream(outputFileName)) {
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }
           // do your work here

    }

This will download files in the downloads folder in phone storage. You can use threads if you want to download that in the background (use thread.alive() and timer class to know the download is complete or not). This is useful when we download small files, as you can do the next task just after the download.

Working with Enums in android

According to this Video if you use the ProGuard you don't need even think about Enums performance issues!!

Proguard can in many situations optimize Enums to INT values on your behalf so really don't need to think about it or do any work.

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

How to pass html string to webview on android

I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.

String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");

Find details on WebView

C# Iterate through Class properties

// the index of each item in fieldNames must correspond to 
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};

for (int e = 0; e < fieldNames.Length - 1; e++)
{
    newRecord
       .GetType()
       .GetProperty(fieldNames[e])
       .SetValue(newRecord, resultItems[e]);
}

Configuring ObjectMapper in Spring

To configure a message converter in plain spring-web, in this case to enable the Java 8 JSR-310 JavaTimeModule, you first need to implement WebMvcConfigurer in your @Configuration class and then override the configureMessageConverters method:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(new JavaTimeModule(), new Jdk8Module()).build()
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}

Like this you can register any custom defined ObjectMapper in a Java-based Spring configuration.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key.

USE [YourDatabaseName]
GO

Alter table  [dbo].[YourTableNname]
Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID);
GO

JAXB :Need Namespace Prefix to all the elements

Another way is to tell the marshaller to always use a certain prefix

marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
             @Override
            public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
                return "ns1";
            }
        });'

Checking if a variable is initialized

Depending on your applications (and especially if you're already using boost), you might want to look into boost::optional.

(UPDATE: As of C++17, optional is now part of the standard library, as std::optional)

It has the property you are looking for, tracking whether the slot actually holds a value or not. By default it is constructed to not hold a value and evaluate to false, but if it evaluates to true you are allowed to dereference it and get the wrapped value.

class MyClass
{
    void SomeMethod();

    optional<char> mCharacter;
    optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with *mCharacter.
        // (note you must use the dereference operator)
    }

    if ( ! mDecimal )
    {
        // call mDecimal.reset(expression)
        // (this is how you assign an optional)
    }
}

More examples are in the Boost documentation.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Google Gson - deserialize list<class> object? (generic type)

Another way is to use an array as a type, e.g.:

MyClass[] mcArray = gson.fromJson(jsonString, MyClass[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

List<MyClass> mcList = Arrays.asList(mcArray);

IMHO this is much more readable.

And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

List<MyClass> mcList = new ArrayList<>(Arrays.asList(mcArray));

javac error: Class names are only accepted if annotation processing is explicitly requested

You at least need to add the .java extension to the file name in this line:

javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices

From the official faq:

Class names, 'HelloWorldApp', are only accepted if annotation processing is explicitly requested

If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp.

Also, in your second javac-example, (in which you actually included .java) you need to include the all required .jar-files needed for compilation.

Arithmetic operation resulted in an overflow. (Adding integers)

2055786000 + 93552000 = 2149338000, which is greater than 2^31. So if you're using signed integers coded on 4 bytes, the result of the operation doesn't fit and you get an overflow exception.

How to simulate a button click using code?

there is a better way.

View.performClick();

http://developer.android.com/reference/android/view/View.html#performClick()

this should answer all your problems. every View inherits this function, including Button, Spinner, etc.

Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call

View.performClick();

Instead, do something like:

View myView = findViewById(R.id.myview);
myView.performClick();

Get Enum from Description attribute

The solution works good except if you have a Web Service.

You would need to do the Following as the Description Attribute is not serializable.

[DataContract]
public enum ControlSelectionType
{
    [EnumMember(Value = "Not Applicable")]
    NotApplicable = 1,
    [EnumMember(Value = "Single Select Radio Buttons")]
    SingleSelectRadioButtons = 2,
    [EnumMember(Value = "Completely Different Display Text")]
    SingleSelectDropDownList = 3,
}

public static string GetDescriptionFromEnumValue(Enum value)
{
        EnumMemberAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
            .SingleOrDefault() as EnumMemberAttribute;
        return attribute == null ? value.ToString() : attribute.Value;
}

What exactly is OAuth (Open Authorization)?

OAuth is an open standard for authorization, commonly used as a way for Internet users to log into third party websites using their Microsoft, Google, Facebook or Twitter accounts without exposing their password.

Passing arguments to AsyncTask, and returning results

I sort of agree with leander on this one.

call:

new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));

task:

public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
        @Override
        protected ArrayList<String> doInBackground(String... args) {
           ...
        }

        @Override
        protected void onPostExecute(ArrayList<String> result) {
           ... //do something with the result list here
        }
}

Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);

public class calc_stanica extends AsyncTask<String, Void, Boolean> {
        private List<String> resultList;

        @Override
        protected boolean doInBackground(String... args) {
           ...
        }

        @Override
        protected void onPostExecute(boolean success) {
           ... //if successfull, do something with the result list here
        }
}

Simple conversion between java.util.Date and XMLGregorianCalendar

I had to make some changes to make it work, as some things seem to have changed in the meantime:

  • xjc would complain that my adapter does not extend XmlAdapter
  • some bizarre and unneeded imports were drawn in (org.w3._2001.xmlschema)
  • the parsing methods must not be static when extending the XmlAdapter, obviously

Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):

import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;

public class DateAdapter extends XmlAdapter<Object, Object> {
    @Override
    public Object marshal(Object dt) throws Exception {
        return new DateTime((Date) dt).toString("YYYY-MM-dd");
    }

    @Override
        public Object unmarshal(Object s) throws Exception {
        return DatatypeConverter.parseDate((String) s).getTime();
    }
}

In the xsd, I have followed the excellent references given above, so I have included this xml annotation:

<xsd:appinfo>
    <jaxb:schemaBindings>
        <jaxb:package name="at.mycomp.xml" />
    </jaxb:schemaBindings>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:date"
              parseMethod="at.mycomp.xml.DateAdapter.unmarshal"
          printMethod="at.mycomp.xml.DateAdapter.marshal" />
    </jaxb:globalBindings>
</xsd:appinfo>

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Custom Drawable for ProgressBar/ProgressDialog

Your style should look like this:

<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
    <item name="android:indeterminateDrawable">@anim/mp3</item>
</style>

How to get C# Enum description from value?

int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);

The default underlying data type for an enum in C# is an int, you can just cast it.

The remote server returned an error: (407) Proxy Authentication Required

Check with your firewall expert. They open the firewall for PROD servers so there is no need to use the Proxy.

Thanks your tip helped me solve my problem:

Had to to set the Credentials in two locations to get past the 407 error:

HttpWebRequest webRequest = WebRequest.Create(uirTradeStream) as HttpWebRequest;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Credentials = new NetworkCredential("user", "password", "domain");
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");

and voila!

Android TextView Text not getting wrapped

I used android:ems="23" to solve my problem. Just replace 23 with the best value in your case.

<TextView
        android:id="@+id/msg"
        android:ems="23"
        android:text="ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab "
        android:textColor="@color/white"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

How to make a smooth image rotation in Android?

I had this problem as well, and tried to set the linear interpolator in xml without success. The solution that worked for me was to create the animation as a RotateAnimation in code.

RotateAnimation rotate = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(5000);
rotate.setInterpolator(new LinearInterpolator());

ImageView image= (ImageView) findViewById(R.id.imageView);

image.startAnimation(rotate);

What does elementFormDefault do in XSD?

New, detailed answer and explanation to an old, frequently asked question...

Short answer: If you don't add elementFormDefault="qualified" to xsd:schema, then the default unqualified value means that locally declared elements are in no namespace.

There's a lot of confusion regarding what elementFormDefault does, but this can be quickly clarified with a short example...

Streamlined version of your XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:target="http://www.levijackson.net/web340/ns"
        targetNamespace="http://www.levijackson.net/web340/ns">
  <element name="assignments">
    <complexType>
      <sequence>
        <element name="assignment" type="target:assignmentInfo" 
                 minOccurs="1" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>
  <complexType name="assignmentInfo">
    <sequence>
      <element name="name" type="string"/>
    </sequence>
    <attribute name="id" type="string" use="required"/>
  </complexType>
</schema>

Key points:

  • The assignment element is locally defined.
  • Elements locally defined in XSD are in no namespace by default.
    • This is because the default value for elementFormDefault is unqualified.
    • This arguably is a design mistake by the creators of XSD.
    • Standard practice is to always use elementFormDefault="qualified" so that assignment is in the target namespace as one would expect.
  • It is a rarely used form attribute on xs:element declarations for which elementFormDefault establishes default values.

Seemingly Valid XML

This XML looks like it should be valid according to the above XSD:

<assignments xmlns="http://www.levijackson.net/web340/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
  <assignment id="a1">
    <name>John</name>
  </assignment>
</assignments>

Notice:

  • The default namespace on assignments places assignments and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns).

Perplexing Validation Error

Despite looking valid, the above XML yields the following confusing validation error:

[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.

Notes:

  • You would not be the first developer to curse this diagnostic that seems to say that the content is invalid because it expected to find an assignment element but it actually found an assignment element. (WTF)
  • What this really means: The { and } around assignment means that validation was expecting assignment in no namespace here. Unfortunately, when it says that it found an assignment element, it doesn't mention that it found it in a default namespace which differs from no namespace.

Solution

  • Vast majority of the time: Add elementFormDefault="qualified" to the xsd:schema element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.
  • Tiny minority of the time: Change the XML to comply with the XSD's requirement that assignment be in no namespace. This can be achieved, for example, by adding xmlns="" to the assignment element.

Credits: Thanks to Michael Kay for helpful feedback on this answer.

Java substring: 'string index out of range'

if (itemdescription != null && itemdescription.length() > 0) {
    pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38))); 
} else { 
    pstmt2.setString(3, "_"); 
}

Is it possible to specify proxy credentials in your web.config?

You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:

1 In Web.config

<system.net>    
<defaultProxy enabled="true" useDefaultCredentials="true">      
<proxy usesystemdefault="True" />      
</defaultProxy>    
</system.net>
  1. In Credential Manager >> Add a Generic Credential

Internet or network address: your proxy address
User name: your user name
Password: you pass

This configuration worked for me, without change the code.

React: Expected an assignment or function call and instead saw an expression

Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.

// eslint-disable-next-line @typescript-eslint/no-unused-expressions

Invalid application of sizeof to incomplete type with a struct

I think that the problem is that you put #ifdef instead of #ifndef at the top of your header.h file.

Android Open External Storage directory(sdcard) for storing file

I want to open external storage directory path for saving file programatically.I tried but not getting sdcard path. How can i do this?is there any solution for this??

To store your app files in SD card, you should use File[] getExternalFilesDirs (String type) method in Context class. Generally, second returned path would be the storage path for microSD card (if any).

On my phone, second path returned was /storage/sdcard1/Android/data/your.application.package.appname/files after passing null as argument to getExternalFilesDirs (String type). But path may vary on different phones, different Android versions.

Both File getExternalStorageDirectory () and File getExternalStoragePublicDirectory (String type) in Environment class may return SD card directory or internal memory directory depending on your phone's model and Android OS version.

Because According to Official Android Guide external storage can be

removable storage media (such as an SD card) or an internal (non-removable) storage.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

How to encrypt a large file in openssl using public key

Encrypting a very large file using smime is not advised since you might be able to encrypt large files using the -stream option, but not decrypt the resulting file due to hardware limitations see: problem decrypting big files

As mentioned above Public-key crypto is not for encrypting arbitrarily long files. Therefore the following commands will generate a pass phrase, encrypt the file using symmetric encryption and then encrypt the pass phrase using the asymmetric (public key). Note: the smime includes the use of a primary public key and a backup key to encrypt the pass phrase. A backup public/private key pair would be prudent.

Random Password Generation

Set up the RANDFILE value to a file accessible by the current user, generate the passwd.txt file and clean up the settings

export OLD_RANDFILE=$RANDFILE
RANDFILE=~/rand1
openssl rand -base64 2048 > passwd.txt
rm ~/rand1
export RANDFILE=$OLD_RANDFILE

Encryption

Use the commands below to encrypt the file using the passwd.txt contents as the password and AES256 to a base64 (-a option) file. Encrypt the passwd.txt using asymetric encryption into the file XXLarge.crypt.pass using a primary public key and a backup key.

openssl enc -aes-256-cbc -a -salt -in XXLarge.data -out XXLarge.crypt -pass file:passwd.txt
openssl smime -encrypt -binary -in passwd.txt -out XXLarge.crypt.pass -aes256 PublicKey1.pem PublicBackupKey.pem
rm passwd.txt

Decryption

Decryption simply decrypts the XXLarge.crypt.pass to passwd.tmp, decrypts the XXLarge.crypt to XXLarge2.data, and deletes the passwd.tmp file.

openssl smime -decrypt -binary -in XXLarge.crypt.pass -out passwd.tmp -aes256 -recip PublicKey1.pem -inkey PublicKey1.key
openssl enc -d -aes-256-cbc -a -in XXLarge.crypt -out XXLarge2.data -pass file:passwd.tmp
rm passwd.tmp

This has been tested against >5GB files..

5365295400 Nov 17 10:07 XXLarge.data
7265504220 Nov 17 10:03 XXLarge.crypt
      5673 Nov 17 10:03 XXLarge.crypt.pass
5365295400 Nov 17 10:07 XXLarge2.data

SQL Server Configuration Manager not found

From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.

Android: How to set password property in an edit text?

See this link text view android:password

This applies for EditText as well, as it is a known direct subclass of TextView.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Thanks pberkes for your answer. I just modified it to avoid (1) replacement while sampling (2) duplicated instances occurred in both training and testing:

training_idx = np.random.choice(X.shape[0], int(np.round(X.shape[0] * 0.8)),replace=False)
training_idx = np.random.permutation(np.arange(X.shape[0]))[:np.round(X.shape[0] * 0.8)]
    test_idx = np.setdiff1d( np.arange(0,X.shape[0]), training_idx)

How do I make a dotted/dashed line in Android?

Best Solution for Dotted Background working perfect

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <stroke
    android:dashGap="3dp"
    android:dashWidth="2dp"
    android:width="1dp"
    android:color="@color/colorBlack" />
</shape>

Getting an attribute value in xml element

Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."

import com.ximpleware.*;

public class getAttrs{

   public static void main(String[] s) throws VTDException{
         VTDGen vg = new VTDGen();
         if (!vg.parseFile("input.xml",false)) // turn off namespace
              return;
         VTDNav vn = vg.getNav();
         AutoPilot ap =  new AutoPilot(vn);
         ap.selectXPath("/xml/item/@name");
         int i=0;
         while( (i=ap.evalXPath())!=-1){
              System.out.println(" item name is ===>"+vn.toString(i+1)); 
         }
   }
}

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

How to extract IP Address in Spring MVC Controller get call?

See below. This code works with spring-boot and spring-boot + apache CXF/SOAP.

    // in your class RequestUtil
    private static final String[] IP_HEADER_NAMES = { 
                                                        "X-Forwarded-For",
                                                        "Proxy-Client-IP",
                                                        "WL-Proxy-Client-IP",
                                                        "HTTP_X_FORWARDED_FOR",
                                                        "HTTP_X_FORWARDED",
                                                        "HTTP_X_CLUSTER_CLIENT_IP",
                                                        "HTTP_CLIENT_IP",
                                                        "HTTP_FORWARDED_FOR",
                                                        "HTTP_FORWARDED",
                                                        "HTTP_VIA",
                                                        "REMOTE_ADDR"
                                                    };

    public static String getRemoteIP(RequestAttributes requestAttributes)
    {
        if (requestAttributes == null)
        {
            return "0.0.0.0";
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String ip = Arrays.asList(IP_HEADER_NAMES)
            .stream()
            .map(request::getHeader)
            .filter(h -> h != null && h.length() != 0 && !"unknown".equalsIgnoreCase(h))
            .map(h -> h.split(",")[0])
            .reduce("", (h1, h2) -> h1 + ":" + h2);
        return ip + request.getRemoteAddr();
    }

    //... in service class:
    String remoteAddress = RequestUtil.getRemoteIP(RequestContextHolder.currentRequestAttributes());

:)

Blocks and yields in Ruby

Yields, to put it simply, allow the method you create to take and call blocks. The yield keyword specifically is the spot where the 'stuff' in the block will be performed.

How to perform mouseover function in Selenium WebDriver using Java?

Check this example how we could implement this.

enter image description here

public class HoverableDropdownTest {

    private WebDriver driver;
    private Actions action;

    //Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
    Consumer < By > hover = (By by) -> {
        action.moveToElement(driver.findElement(by))
              .perform();
    };

    @Test
    public void hoverTest() {
        driver.get("https://www.bootply.com/render/6FC76YQ4Nh");

        hover.accept(By.linkText("Dropdown"));
        hover.accept(By.linkText("Dropdown Link 5"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
    }

    @BeforeTest
    public void setupDriver() {
        driver = new FirefoxDriver();
        action = new Actions(driver);
    }

    @AfterTest
    public void teardownDriver() {
        driver.quit();
    }

}

For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/

C# Iterating through an enum? (Indexing a System.Array)

What about using a foreach loop, maybe you could work with that?

  int i = 0;
  foreach (var o in values)
  {
    print(names[i], o);
    i++;
  }

something like that perhaps?

How to ORDER BY a SUM() in MySQL?

This is how you do it

SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS 
FROM TABLE 
ORDER BY SUM_COUNTS LIMIT 20

The SUM function will add up all rows, so the order by clause is useless, instead you will have to use the group by clause.

How to hide "Showing 1 of N Entries" with the dataTables.js library

It is Work for me:

language:{"infoEmpty": "No records available",}

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

How can I run a PHP script inside a HTML file?

Simply you cant !! but you have some possbile options :

1- Excute php page as external page.

2- write your html code inside the php page itself.

3- use iframe to include the php within the html page.

to be more specific , unless you wanna edit your htaccess file , you may then consider this:

http://php.about.com/od/advancedphp/p/html_php.htm

Change x axes scale in matplotlib

This is not so much an answer to your original question as to one of the queries you had in the body of your question.

A little preamble, so that my naming doesn't seem strange:

import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )

As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:

ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')

You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:

ax.xaxis.major.formatter._useMathText = True

This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:

rc('text', usetex=True)

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

PowerShell : retrieve JSON object by field value

Hows about this:

$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value

which would select from json structured

{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}

This is based on this accessing values in powershell SO question . Isn't powershell fabulous!

How to import spring-config.xml of one project into spring-config.xml of another project?

Here is the annotation based example:

@SpringBootApplication
@ImportResource({"classpath*:spring-config.xml"})
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

Invalid Host Header when ngrok tries to connect to React dev server

I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser

ngrok http 8080 -host-header="localhost:8080"
ngrok http --host-header=rewrite 8080

obviously replace 8080 with whatever port you're running on

this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost, when this is embedded, it's looking to localhost, which the app is no longer running on

Return multiple values from a function in swift

//By : Dhaval Nimavat
    import UIKit

   func weather_diff(country1:String,temp1:Double,country2:String,temp2:Double)->(c1:String,c2:String,diff:Double)
   {
    let c1 = country1
    let c2 = country2
    let diff = temp1 - temp2
    return(c1,c2,diff)
   }

   let result = 
   weather_diff(country1: "India", temp1: 45.5, country2: "Canada", temp2:    18.5)
   print("Weather difference between \(result.c1) and \(result.c2) is \(result.diff)")

Android: How do I get string from resources using its name?

getResources() works only when you're in Activity or Fragment class.

  • to get access to strings resource everywhere,

use:

Resources.getSystem().getString(android.R.string.somecommonstuff)

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

Java - Check if input is a positive integer, negative integer, natural number and so on.

For integers you can use Integer.signum()

Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

Read text file into string array (and write)

Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func writeLines(lines []string, path string) (err error) {
    var (
        file *os.File
    )

    if file, err = os.Create(path); err != nil {
        return
    }
    defer file.Close()

    //writer := bufio.NewWriter(file)
    for _,item := range lines {
        //fmt.Println(item)
        _, err := file.WriteString(strings.TrimSpace(item) + "\n"); 
        //file.Write([]byte(item)); 
        if err != nil {
            //fmt.Println("debug")
            fmt.Println(err)
            break
        }
    }
    /*content := strings.Join(lines, "\n")
    _, err = writer.WriteString(content)*/
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
    //array := []string{"7.0", "8.5", "9.1"}
    err = writeLines(lines, "foo2.txt")
    fmt.Println(err)
}

Bootstrap 3 Navbar Collapse

Thanks to Seb33300 I got this working. However, an important part seems to be missing. At least in Bootstrap version 3.1.1.

My problem was that the navbar collapsed accordingly at the correct width, but the menu button didn't work. I couldn't expand and collapse the menu.

This is because the collapse.in class is overrided by the !important in .navbar-collapse.collapse, and can be solved by also adding the "collapse.in". Seb33300's example completed below:

@media (max-width: 991px) {
    .navbar-header {
        float: none;
    }
    .navbar-toggle {
        display: block;
    }
    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }
    .navbar-collapse.collapse {
        display: none!important;
    }
    .navbar-collapse.collapse.in {
        display: block!important;
    }
    .navbar-nav {
        float: none!important;
        margin: 7.5px -15px;
    }
    .navbar-nav>li {
        float: none;
    }
    .navbar-nav>li>a {
        padding-top: 10px;
        padding-bottom: 10px;
    }
}

batch/bat to copy folder and content at once

For Folder Copy You can Use

robocopy C:\Source D:\Destination /E

For File Copy

copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y 

Delete file in some folder last modify date more than some day

forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"

And you can Shedule task in windows perform this task automatically in specific time.

Making a cURL call in C#

I know this is a very old question but I post this solution in case it helps somebody. I recently met this problem and google led me here. The answer here helps me to understand the problem but there are still issues due to my parameter combination. What eventually solves my problem is curl to C# converter. It is a very powerful tool and supports most of the parameters for Curl. The code it generates is almost immediately runnable.

What is memoization and how can I use it in Python?

cache = {}
def fib(n):
    if n <= 1:
        return n
    else:
        if n not in cache:
            cache[n] = fib(n-1) + fib(n-2)
        return cache[n]

Need a good hex editor for Linux

Bless is a high quality, full featured hex editor.

It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run.

Bless currently provides the following features:

  • Efficient editing of large data files and block devices.
  • Multilevel undo - redo operations.
  • Customizable data views.
  • Fast data rendering on screen.
  • Multiple tabs.
  • Fast find and replace operations.
  • A data conversion table.
  • Advanced copy/paste capabilities.
  • Highlighting of selection pattern matches in the file.
  • Plugin based architecture.
  • Export of data to text and html (others with plugins).
  • Bitwise operations on data.
  • A comprehensive user manual.

wxHexEditor is another Free Hex Editor, built because there is no good hex editor for Linux system, specially for big files.

  • It uses 64 bit file descriptors (supports files or devices up to 2^64 bytes , means some exabytes but tested only 1 PetaByte file (yet). ).
  • It does NOT copy whole file to your RAM. That make it FAST and can open files (which sizes are Multi Giga < Tera < Peta < Exabytes)
  • Could open your devices on Linux, Windows or MacOSX.
  • Memory Usage : Currently ~10 MegaBytes while opened multiple > ~8GB files.
  • Could operate thru XOR encryption.
  • Written with C++/wxWidgets GUI libs and can be used with other OSes such as Mac OS, Windows as native application.
  • You can copy/edit your Disks, HDD Sectors with it.( Usefull for rescue files/partitions by hand. )
  • You can delete/insert bytes to file, more than once, without creating temp file.

DHEX is a more than just another hex editor: It includes a diff mode, which can be used to easily and conveniently compare two binary files. Since it is based on ncurses and is themeable, it can run on any number of systems and scenarios. With its utilization of search logs, it is possible to track changes in different iterations of files easily. Wikipedia article

You can sort on Linux to find some more here: http://en.wikipedia.org/wiki/Comparison_of_hex_editors

how to remove untracked files in Git?

For deleting untracked files:

git clean -f

For deleting untracked directories as well, use:

git clean -f -d

For preventing any cardiac arrest, use

git clean -n -f -d

How to properly and completely close/reset a TcpClient connection?

Despite having all the appropriate using statements, calling Close, having some exponential back off logic and recreating the TcpClient I've still been seeing issues where the application cannot recover the TCP connection without an application restart. It keeps failing with a System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

But there is an option LingerState on the TcpClient that appears it may have solved the issue (might not know for a few months as my own hardware setup only fails about that often!). See MSDN.

// This discards any pending data and Winsock resets the connection.
LingerOption lingerOption = new LingerOption(true, 0);

using (var tcpClient = new TcpClient 
       {SendTimeout = 2000, ReceiveTimeout = 2000, LingerState = lingerOption })
   ...

Reading Datetime value From Excel sheet

You may want to try out simple function I posted on another thread related to reading date value from excel sheet.

It simply takes text from the cell as input and gives DateTime as output.

I would be happy to see improvement in my sample code provided for benefit of the .Net development community.

Here is the link for the thread C# not reading excel date from spreadsheet

How to simulate a button click using code?

Starting with API15, you can use also callOnClick() that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

How to use mouseover and mouseout in Angular 6

CSS solution works without a glitch!

https://www.w3schools.com/code/tryit.asp?filename=GJ4PCJMVQ4LN https://www.w3schools.com/code/tryit.asp?filename=GJ4PPLCCEBRG

_x000D_
_x000D_
.col-info:hover>.popoverIcon {
    visibility: visible;
  }
}

.popoverIcon {
  visibility: hidden;
}
_x000D_
<div *ngFor="let i of [1,2,3,4]">

  <div class="col-info">
    <span class=" popoverIcon ">Show {{i}}</span>
  </div>

</div>
_x000D_
_x000D_
_x000D_

Is it possible to modify a registry entry via a .bat/.cmd script?

@Franci Penov - modify is possible in the sense of overwrite with /f, eg

reg add "HKCU\Software\etc\etc" /f /v "value" /t REG_SZ /d "Yes"

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

What is the best Java library to use for HTTP POST, GET etc.?

imho: Apache HTTP Client

usage example:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

some highlight features:

  • Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
    • Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • Granular non-standards configuration and tracking.
    • Transparent connections through HTTP proxies.
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • Plug-in mechanism for custom authentication methods.
    • Multi-Part form POST for uploading large files.
    • Pluggable secure sockets implementations, making it easier to use third party solutions
    • Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
    • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
    • Plug-in mechanism for custom cookie policies.
    • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
    • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
    • Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
    • Direct access to the response code and headers sent by the server.
    • The ability to set connection timeouts.
    • HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
    • Source code is freely available under the Apache Software License.

Sending event when AngularJS finished loading

In the docs for angular.Module, there's an entry describing the run function:

Use this method to register work which should be performed when the injector is done loading all modules.

So if you have some module that is your app:

var app = angular.module('app', [/* module dependencies */]);

You can run stuff after the modules have loaded with:

app.run(function() {
  // Do post-load initialization stuff here
});

EDIT: Manual Initialization to the rescue

So it's been pointed out that the run doesn't get called when the DOM is ready and linked up. It gets called when the $injector for the module referenced by ng-app has loaded all its dependencies, which is separate from the DOM compilation step.

I took another look at manual initialization, and it seems that this should do the trick.

I've made a fiddle to illustrate.

The HTML is simple:

<html>
    <body>
        <test-directive>This is a test</test-directive>
    </body>
</html>

Note the lack of an ng-app. And I have a directive that will do some DOM manipulation, so we can make sure of the order and timing of things.

As usual, a module is created:

var app = angular.module('app', []);

And here's the directive:

app.directive('testDirective', function() {
    return {
        restrict: 'E',
        template: '<div class="test-directive"><h1><div ng-transclude></div></h1></div>',
        replace: true,
        transclude: true,
        compile: function() {
            console.log("Compiling test-directive");
            return {
                pre: function() { console.log("Prelink"); },
                post: function() { console.log("Postlink"); }
            };
        }
    };
});

We're going to replace the test-directive tag with a div of class test-directive, and wrap its contents in an h1.

I've added a compile function that returns both pre and post link functions so we can see when these things run.

Here's the rest of the code:

// The bootstrapping process

var body = document.getElementsByTagName('body')[0];

// Check that our directive hasn't been compiled

function howmany(classname) {
    return document.getElementsByClassName(classname).length;
}

Before we've done anything, there should be no elements with a class of test-directive in the DOM, and after we're done there should be 1.

console.log('before (should be 0):', howmany('test-directive'));

angular.element(document).ready(function() {
    // Bootstrap the body, which loades the specified modules
    // and compiled the DOM.
    angular.bootstrap(body, ['app']);

    // Our app is loaded and the DOM is compiled
    console.log('after (should be 1):', howmany('test-directive'));
});

It's pretty straightforward. When the document is ready, call angular.bootstrap with the root element of your app and an array of module names.

In fact, if you attach a run function to the app module, you'll see it gets run before any of the compiling takes place.

If you run the fiddle and watch the console, you'll see the following:

before (should be 0): 0 
Compiling test-directive 
Prelink
Postlink
after (should be 1): 1 <--- success!

ruby 1.9: invalid byte sequence in UTF-8

Before you use scan, make sure that the requested page's Content-Type header is text/html, since there can be links to things like images which are not encoded in UTF-8. The page could also be non-html if you picked up a href in something like a <link> element. How to check this varies on what HTTP library you are using. Then, make sure the result is only ascii with String#ascii_only? (not UTF-8 because HTML is only supposed to be using ascii, entities can be used otherwise). If both of those tests pass, it is safe to use scan.

Javascript: getFullyear() is not a function

Try this...

 var start = new Date(document.getElementById('Stardate').value);
 var y = start.getFullYear();

Statistics: combinations in Python

Here's another alternative. This one was originally written in C++, so it can be backported to C++ for a finite-precision integer (e.g. __int64). The advantage is (1) it involves only integer operations, and (2) it avoids bloating the integer value by doing successive pairs of multiplication and division. I've tested the result with Nas Banov's Pascal triangle, it gets the correct answer:

def choose(n,r):
  """Computes n! / (r! (n-r)!) exactly. Returns a python long int."""
  assert n >= 0
  assert 0 <= r <= n

  c = 1L
  denom = 1
  for (num,denom) in zip(xrange(n,n-r,-1), xrange(1,r+1,1)):
    c = (c * num) // denom
  return c

Rationale: To minimize the # of multiplications and divisions, we rewrite the expression as

    n!      n(n-1)...(n-r+1)
--------- = ----------------
 r!(n-r)!          r!

To avoid multiplication overflow as much as possible, we will evaluate in the following STRICT order, from left to right:

n / 1 * (n-1) / 2 * (n-2) / 3 * ... * (n-r+1) / r

We can show that integer arithmatic operated in this order is exact (i.e. no roundoff error).

Message 'src refspec master does not match any' when pushing commits in Git

If it doesn't recognize that you have a master branch, just create it and commit again.

To create a master branch:

git checkout -b master

How do I run msbuild from the command line using Windows SDK 7.1?

For Visual Studio 2019 (Preview, at least) it is now in:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin\MSBuild.exe

I imagine the process will be similar for the official 2019 release.

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Check if a string contains another string

There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.

Per @rene's answer...

Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")

...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:

Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")

...would return 20 to pos, instead of 6.

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

How to make a DIV not wrap?

None of the above worked for me.

In my case, I needed to add the following to the user control I had created:

display:inline-block;

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same problem with the laravel initiation. The solution was as follows.

1st - I checked the version of my PHP. That it was 5.6 would soon give problem with the laravel.

2nd - I changed the version of my PHP to PHP 7.1.1. ATTENTION, in my case I changed my environment variable that was getting Xampp's PHP version 5.6 I changed to 7.1.1 for laragon.

3rd - I went to the terminal / console and navigated to my folder where my project was and typed the following command: php artisan serves. And it worked! In my case it started at the port: 8000 see example below.

C: \ laragon \ www \ first> php artisan serves Laravel development server started: http://127.0.0.1:8000

I hope I helped someone who has been through the same problem as me.

How can I increase the JVM memory?

When starting the JVM, two parameters can be adjusted to suit your memory needs :

-Xms<size>

specifies the initial Java heap size and

-Xmx<size>

the maximum Java heap size.

http://www.rgagnon.com/javadetails/java-0131.html

How to update the value stored in Dictionary in C#?

Here is a way to update by an index much like foo[x] = 9 where x is a key and 9 is the value

var views = new Dictionary<string, bool>();

foreach (var g in grantMasks)
{
    string m = g.ToString();
    for (int i = 0; i <= m.Length; i++)
    {
        views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
    }
}

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Writing string to a file on a new line every time

You can use:

file.write(your_string + '\n')

Change a Rails application to production

RAILS_ENV=production rails s

OR

rails s -e production

By default environment is developement.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Got it working for a compile file('...') conflict by increasing minSdkVersion to 21 and enabling multidex. Not sure if that is the best solution but the only way I could get it working in my case.

Note: for compile file('...') it appears that you cannot put in an exclude clause so that option was not available.

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

Best Timer for using in a Windows service

I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:

This will:

  • Reduce plumbing code that replicates scheduler behaviour
  • Provide greater flexibility in terms of scheduling behaviour (e.g. only run on weekends) with all scheduling logic abstracted from application code
  • Utilise the command line arguments for parameters without having to setup configuration values in config files etc
  • Far easier to debug/test during development
  • Allow a support user to execute by invoking the console application directly (e.g. useful during support situations)

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Windows 10

Fonts: C:\Windows\Fonts
CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonDesktopDirectory: C:\Users\Public\Desktop
CommonApplicationData: C:\ProgramData
Windows: C:\Windows
System: C:\Windows\system32
ProgramFiles: C:\Program Files (x86)
SystemX86: C:\Windows\SysWOW64
ProgramFilesX86: C:\Program Files (x86)
CommonProgramFiles: C:\Program Files (x86)\Common Files
CommonProgramFilesX86: C:\Program Files (x86)\Common Files
CommonTemplates: C:\ProgramData\Microsoft\Windows\Templates
CommonDocuments: C:\Users\Public\Documents
CommonAdminTools: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonMusic: C:\Users\Public\Music
CommonPictures: C:\Users\Public\Pictures
CommonVideos: C:\Users\Public\Videos
Resources: C:\Windows\resources
LocalizedResources:
CommonOemLinks:

Code Snippet if you want to log your own

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

How to make child element higher z-index than parent?

To achieve what you want without removing any styles you have to make the z-index of the '.parent' class bigger then the '.wholePage' class.

.parent {
    position: relative;
    z-index: 4; /*matters since it's sibling to wholePage*/
}

.child {
    position: relative;
    z-index:1; /*doesn't matter */
    background-color: white;
    padding: 5px;
}

jsFiddle: http://jsfiddle.net/ZjXMR/2/

How do I solve this "Cannot read property 'appendChild' of null" error?

The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.

Programmatically obtain the phone number of the Android phone

TelephonyManager is not the right solution, because in some cases the number is not stored in the SIM. I suggest that you should use the shared preference to store the user's phone number for the first time the application is open and the number will used whenever you need.

Radio buttons and label to display in same line

I use this code and works just fine:

input[type="checkbox"], 
input[type="radio"],
input.radio,
input.checkbox {
    vertical-align:text-top;
    width:13px;
    height:13px;
    padding:0;
    margin:0;
    position:relative;
    overflow:hidden;
    top:2px;
}

You may want to readjust top value (depends on your line-height). If you don't want IE6 compatibility, you just need to put this code into your page. Otherwise, you will must add extra class to your inputs (you can use jQuery - or any other library - for that tho ;) )

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

What is the "right" JSON date format?

From RFC 7493 (The I-JSON Message Format ):

I-JSON stands for either Internet JSON or Interoperable JSON, depending on who you ask.

Protocols often contain data items that are designed to contain timestamps or time durations. It is RECOMMENDED that all such data items be expressed as string values in ISO 8601 format, as specified in RFC 3339, with the additional restrictions that uppercase rather than lowercase letters be used, that the timezone be included not defaulted, and that optional trailing seconds be included even when their value is "00". It is also RECOMMENDED that all data items containing time durations conform to the "duration" production in Appendix A of RFC 3339, with the same additional restrictions.

Namespace not recognized (even though it is there)

In my case i had copied a classlibrary, and not changed the "Assembly Name" in the project properties, so one DLL was overwriting the other...

Format XML string to print friendly XML string

This one, from kristopherjohnson is heaps better:

  1. It doesn't require an XML document header either.
  2. Has clearer exceptions
  3. Adds extra behaviour options: OmitXmlDeclaration = true, NewLineOnAttributes = true
  4. Less lines of code

    static string PrettyXml(string xml)
    {
        var stringBuilder = new StringBuilder();
    
        var element = XElement.Parse(xml);
    
        var settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.Indent = true;
        settings.NewLineOnAttributes = true;
    
        using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
        {
            element.Save(xmlWriter);
        }
    
        return stringBuilder.ToString();
    }
    

How to convert a string Date to long millseconds

It’s about time someone provides the modern answer to this question. In 2012 when the question was asked, the answers also posted back then were good answers. Why the answers posted in 2016 also use the then long outdated classes SimpleDateFormat and Date is a bit more of a mystery to me. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with. You can use it on Android through the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project.

For most purposes I recommend using the milliseconds since the epoch at the start of the day in UTC. To obtain these:

    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
    String stringDate = "12-December-2012";
    long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
            .atStartOfDay(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println(millisecondsSinceEpoch);

This prints:

1355270400000

If you require the time at start of day in some specific time zone, specify that time zone instead of UTC, for example:

            .atStartOfDay(ZoneId.of("Asia/Karachi"))

As expected this gives a slightly different result:

1355252400000

Another point to note, remember to supply a locale to your DateTimeFormatter. I took December to be English, there are other languages where that month is called the same, so please choose the proper locale yourself. If you didn’t provide a locale, the formatter would use the JVM’s locale setting, which may work in many cases, and then unexpectedly fail one day when you run your app on a device with a different locale setting.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

How can I get customer details from an order in WooCommerce?

If you want customer's details that customer had entered while ordering, then you can use the following code:

$order = new WC_Order($order_id);
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address();

// For printing or displaying on the web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // For printing or displaying on web page

Apart from this, $customer = new WC_Customer( $order_id ); can not get you customer details.

First of all, new WC_Customer() doesn't take any arguments.

Secondly, WC_Customer will get customer's details only when the user is logged in and he/she is not on the admin side. Instead he/she should be on website's front-end like the 'My Account', 'Shop', 'Cart', or 'Checkout' page.

static files with express.js

express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.

Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:

By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

Javascript/Jquery to change class onclick?

      <div class="liveChatContainer online">
        <div class="actions" id="change">
         <span class="item title">Need help?</span>
              <a href="/test" onclick="demo()"><i class="fa fa-smile-o"></i>Chat</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Call</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Email</a>
        </div>
              <a href="#" class="liveChatLabel">Contact</a>
     </div>
             <style>
               .actions_one{
               background-color: red;
                      } 
              </style>



           <script>
          function demo(){
      document.getElementById("change").setAttribute("class","actions_one");}
            </script>      

Getting the last element of a list

If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".

The significance of this is:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.

How to uninstall Jenkins?

My Jenkins version: 1.5.39

Execute steps:

Step 1. Go to folder /Library/Application Support/Jenkins

Step 2. Run Uninstall.command jenkins-runner.sh file.

Step 3. Check result.

It work for me.

.Net picking wrong referenced assembly version

My guess is that another assembly you are using is referencing the old dll. Are you familiar with all of the other project references being used and do any of them have a reference to the Telerik dlls?

Can you put in a binding redirect in your web.config file like this?

<dependentAssembly>
 <assemblyIdentity name="Telerik" publicKeyToken="121fae78165ba3d4"/>
 <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>

How to read a value from the Windows registry

The pair RegOpenKey and RegQueryKeyEx will do the trick.

If you use MFC CRegKey class is even more easier solution.

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

We released a package, roperators, to help with this kind of thing. You can read more about it here: https://happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html

install.packages('roperators')
require(roperators)

x <- 1:3
x %+=% 1; x
x %-=% 3; x
y <- c('a', 'b', 'c')
y %+=% 'text'; y
y %-=% 'text'; y

# etc

Iteration over std::vector: unsigned vs signed index variable

A bit of history:

To represent whether a number is negative or not computer use a 'sign' bit. int is a signed data type meaning it can hold positive and negative values (about -2billion to 2billion). Unsigned can only store positive numbers (and since it doesn't waste a bit on metadata it can store more: 0 to about 4billion).

std::vector::size() returns an unsigned, for how could a vector have negative length?

The warning is telling you that the right operand of your inequality statement can hold more data then the left.

Essentially if you have a vector with more then 2 billion entries and you use an integer to index into you'll hit overflow problems (the int will wrap back around to negative 2 billion).

Storing C++ template function definitions in a .CPP file

None of above worked for me, so here is how y solved it, my class have only 1 method templated..

.h

class Model
{
    template <class T>
    void build(T* b, uint32_t number);
};

.cpp

#include "Model.h"
template <class T>
void Model::build(T* b, uint32_t number)
{
    //implementation
}

void TemporaryFunction()
{
    Model m;
    m.build<B1>(new B1(),1);
    m.build<B2>(new B2(), 1);
    m.build<B3>(new B3(), 1);
}

this avoid linker errors, and no need to call TemporaryFunction at all

Output (echo/print) everything from a PHP Array

 //@parram $data-array,$d-if true then die by default it is false
 //@author Your name

 function p($data,$d = false){

     echo "<pre>"; 
         print_r($data);
     echo "</pre>"; 

     if($d == TRUE){
        die();
     } 
} // END OF FUNCTION

Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function

In your case you can use in this way....

while($row = mysql_fetch_array($result)){
    p($row); // Use this function if you use above function in your page.
}

Best way to find os name and version in Unix/Linux platform

I prepared following commands to find concise information about a Linux system:

clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"

Copy and paste in an sh file like info.sh and then run it using command sh info.sh

How to verify CuDNN installation?

I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h, so

cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2

did the trick.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

Expanding on @Renaud idea, cors now provides a very easy way of doing this:

From cors official documentation found here:

" origin: Configures the Access-Control-Allow-Origin CORS header. Possible values: Boolean - set origin to true to reflect the request origin, as defined by req.header('Origin'), or set it to false to disable CORS. "

Hence we simply do the following:

const app = express();
const corsConfig = {
    credentials: true,
    origin: true,
};
app.use(cors(corsConfig));

Lastly I think it is worth mentioning that there are use cases where we would want to allow cross origin requests from anyone; for example, when building a public REST API.

NOTE: I would have liked to leave this as a comment on his answer, but unfortunately I don't have the reputation points.

How to remove the left part of a string?

The pop version wasn't quite right. I think you want:

>>> print('foofoobar'.split('foo', 1).pop())
foobar

How do I check if a cookie exists?

function getCookie(name) {

    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
        else{
            var oneCookie = dc.indexOf(';', begin);
            if(oneCookie == -1){
                var end = dc.length;
            }else{
                var end = oneCookie;
            }
            return dc.substring(begin, end).replace(prefix,'');
        } 

    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        var fixed = dc.substring(begin, end).replace(prefix,'');
    }
    // return decodeURI(dc.substring(begin + prefix.length, end));
    return fixed;
} 

Tried @jac function, got some trouble, here's how I edited his function.

How to run ~/.bash_profile in mac terminal

You would never want to run that, but you may want to source it.

. ~/.bash_profile
source ~/.bash_profile

both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

Replace one substring for another string in shell script

It's better to use bash than sed if strings have RegExp characters.

echo ${first_string/Suzi/$second_string}

It's portable to Windows and works with at least as old as Bash 3.1.

To show you don't need to worry much about escaping let's turn this:

/home/name/foo/bar

Into this:

~/foo/bar

But only if /home/name is in the beginning. We don't need sed!

Given that bash gives us magic variables $PWD and $HOME, we can:

echo "${PWD/#$HOME/\~}"

EDIT: Thanks for Mark Haferkamp in the comments for the note on quoting/escaping ~.*

Note how the variable $HOME contains slashes but this didn't break anything.

Further reading: Advanced Bash-Scripting Guide.
If using sed is a must, be sure to escape every character.

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

Auto logout with Angularjs based on idle user

I would like to expand the answers to whoever might be using this in a bigger project, you could accidentally attach multiple event handlers and the program would behave weirdly.

To get rid of that, I used a singleton function exposed by a factory, from which you would call inactivityTimeoutFactory.switchTimeoutOn() and inactivityTimeoutFactory.switchTimeoutOff() in your angular application to respectively activate and deactivate the logout due to inactivity functionality.

This way you make sure you are only running a single instance of the event handlers, no matter how many times you try to activate the timeout procedure, making it easier to use in applications where the user might login from different routes.

Here is my code:

'use strict';

angular.module('YOURMODULENAME')
  .factory('inactivityTimeoutFactory', inactivityTimeoutFactory);

inactivityTimeoutFactory.$inject = ['$document', '$timeout', '$state'];

function inactivityTimeoutFactory($document, $timeout, $state)  {
  function InactivityTimeout () {
    // singleton
    if (InactivityTimeout.prototype._singletonInstance) {
      return InactivityTimeout.prototype._singletonInstance;
    }
    InactivityTimeout.prototype._singletonInstance = this;

    // Timeout timer value
    const timeToLogoutMs = 15*1000*60; //15 minutes
    const timeToWarnMs = 13*1000*60; //13 minutes

    // variables
    let warningTimer;
    let timeoutTimer;
    let isRunning;

    function switchOn () {
      if (!isRunning) {
        switchEventHandlers("on");
        startTimeout();
        isRunning = true;
      }
    }

    function switchOff()  {
      switchEventHandlers("off");
      cancelTimersAndCloseMessages();
      isRunning = false;
    }

    function resetTimeout() {
      cancelTimersAndCloseMessages();
      // reset timeout threads
      startTimeout();
    }

    function cancelTimersAndCloseMessages () {
      // stop any pending timeout
      $timeout.cancel(timeoutTimer);
      $timeout.cancel(warningTimer);
      // remember to close any messages
    }

    function startTimeout () {
      warningTimer = $timeout(processWarning, timeToWarnMs);
      timeoutTimer = $timeout(processLogout, timeToLogoutMs);
    }

    function processWarning() {
      // show warning using popup modules, toasters etc...
    }

    function processLogout() {
      // go to logout page. The state might differ from project to project
      $state.go('authentication.logout');
    }

    function switchEventHandlers(toNewStatus) {
      const body = angular.element($document);
      const trackedEventsList = [
        'keydown',
        'keyup',
        'click',
        'mousemove',
        'DOMMouseScroll',
        'mousewheel',
        'mousedown',
        'touchstart',
        'touchmove',
        'scroll',
        'focus'
      ];

      trackedEventsList.forEach((eventName) => {
        if (toNewStatus === 'off') {
          body.off(eventName, resetTimeout);
        } else if (toNewStatus === 'on') {
          body.on(eventName, resetTimeout);
        }
      });
    }

    // expose switch methods
    this.switchOff = switchOff;
    this.switchOn = switchOn;
  }

  return {
    switchTimeoutOn () {
      (new InactivityTimeout()).switchOn();
    },
    switchTimeoutOff () {
      (new InactivityTimeout()).switchOff();
    }
  };

}

Google maps API V3 - multiple markers on exact same spot

This is more of a stopgap 'quick and dirty' solution similar to the one Matthew Fox suggests, this time using JavaScript.

In JavaScript you can just offset the lat and long of all of your locations by adding a small random offset to both e.g.

myLocation[i].Latitude+ = (Math.random() / 25000)

(I found that dividing by 25000 gives enough separation but doesn't move the marker significantly from the exact location e.g. a specific address)

This makes a reasonably good job of offsetting them from one another, but only after you've zoomed in closely. When zoomed out, it still won't be clear that there are multiple options for the location.

Check whether there is an Internet connection available on Flutter app

I having some problem with the accepted answer, but it seems it solve answer for others. I would like a solution that can get a response from the url it uses, so I thought http would be great for that functionality, and for that I found this answer really helpful. How do I check Internet Connectivity using HTTP requests(Flutter/Dart)?

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How do I set the value property in AngularJS' ng-options?

For me the answer by Bruno Gomes is the best answer.

But actually, you need not worry about setting the value property of select options. AngularJS will take care of that. Let me explain in detail.

Please consider this fiddle

angular.module('mySettings', []).controller('appSettingsCtrl', function ($scope) {

    $scope.timeFormatTemplates = [{
        label: "Seconds",
        value: 'ss'
    }, {
        label: "Minutes",
        value: 'mm'
    }, {
        label: "Hours",
        value: 'hh'
    }];


    $scope.inactivity_settings = {
        status: false,
        inactive_time: 60 * 5 * 3, // 15 min (default value), that is, 900 seconds
        //time_format: 'ss', // Second (default value)
        time_format: $scope.timeFormatTemplates[0], // Default seconds object
    };

    $scope.activity_settings = {
        status: false,
        active_time: 60 * 5 * 3, // 15 min (default value), that is,  900 seconds
        //time_format: 'ss', // Second (default value)
        time_format: $scope.timeFormatTemplates[0], // Default seconds object
    };

    $scope.changedTimeFormat = function (time_format) {
        'use strict';

        console.log('time changed');
        console.log(time_format);
        var newValue = time_format.value;

        // do your update settings stuffs
    }
});

As you can see in the fiddle output, whatever you choose for select box options, it is your custom value, or the 0, 1, 2 auto generated value by AngularJS, it does not matter in your output unless you are using jQuery or any other library to access the value of that select combo box options and manipulate it accordingly.

Control the dashed border stroke length and distance between strokes

Stroke length depends on stroke width. You can increase length by increasing width and hide part of border by inner element.

EDIT: added pointer-events: none; thanks to benJ.

.thin {
    background: #F4FFF3;
    border: 2px dashed #3FA535;  
    position: relative;
}

.thin:after {
    content: '';
    position: absolute;
    left: -1px;
    top: -1px;
    right: -1px;
    bottom: -1px;
    border: 1px solid #F4FFF3;
    pointer-events: none;
}

https://jsfiddle.net/ksf9zoLh/

How to set auto increment primary key in PostgreSQL?

Auto incrementing primary key in postgresql:

Step 1, create your table:

CREATE TABLE epictable
(
    mytable_key    serial primary key,
    moobars        VARCHAR(40) not null,
    foobars        DATE
);

Step 2, insert values into your table like this, notice that mytable_key is not specified in the first parameter list, this causes the default sequence to autoincrement.

insert into epictable(moobars,foobars) values('delicious moobars','2012-05-01')
insert into epictable(moobars,foobars) values('worldwide interblag','2012-05-02')

Step 3, select * from your table:

el@voyager$ psql -U pgadmin -d kurz_prod -c "select * from epictable"

Step 4, interpret the output:

mytable_key  |        moobars        |  foobars   
-------------+-----------------------+------------
           1 | delicious moobars     | 2012-05-01
           2 | world wide interblags | 2012-05-02
(2 rows)

Observe that mytable_key column has been auto incremented.

ProTip:

You should always be using a primary key on your table because postgresql internally uses hash table structures to increase the speed of inserts, deletes, updates and selects. If a primary key column (which is forced unique and non-null) is available, it can be depended on to provide a unique seed for the hash function. If no primary key column is available, the hash function becomes inefficient as it selects some other set of columns as a key.

Running the new Intel emulator for Android

Not every processor is supporting the virtualization!

To find out your chipset abilities go to http://ark.intel.com/, insert the name of your processor in the search line and check out the resolve.

Advanced Technologies: ...

Intel® Virtualization Technology (VT-x) = ???

If you see "No", you can forget HAXM!

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

C: What is the difference between ++i and i++?

The only difference is the order of operations between the increment of the variable and the value the operator returns.

This code and its output explains the the difference:

#include<stdio.h>

int main(int argc, char* argv[])
{
  unsigned int i=0, a;
  printf("i initial value: %d; ", i);
  a = i++;
  printf("value returned by i++: %d, i after: %d\n", a, i);
  i=0;
  printf("i initial value: %d; ", i);
  a = ++i;
  printf(" value returned by ++i: %d, i after: %d\n",a, i);
}

The output is:

i initial value: 0; value returned by i++: 0, i after: 1
i initial value: 0;  value returned by ++i: 1, i after: 1

So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.

Another example:

#include<stdio.h>

int main ()
  int i=0;
  int a = i++*2;
  printf("i=0, i++*2=%d\n", a);
  i=0;
  a = ++i * 2;
  printf("i=0, ++i*2=%d\n", a);
  i=0;
  a = (++i) * 2;
  printf("i=0, (++i)*2=%d\n", a);
  i=0;
  a = (++i) * 2;
  printf("i=0, (++i)*2=%d\n", a);
  return 0;
}

Output:

i=0, i++*2=0
i=0, ++i*2=2
i=0, (++i)*2=2
i=0, (++i)*2=2

Many times there is no difference

Differences are clear when the returned value is assigned to another variable or when the increment is performed in concatenation with other operations where operations precedence is applied (i++*2 is different from ++i*2, but (i++)*2 and (++i)*2 returns the same value) in many cases they are interchangeable. A classical example is the for loop syntax:

for(int i=0; i<10; i++)

has the same effect of

for(int i=0; i<10; ++i)

Rule to remember

To not make any confusion between the two operators I adopted this rule:

Associate the position of the operator ++ with respect to the variable i to the order of the ++ operation with respect to the assignment

Said in other words:

  • ++ before i means incrementation must be carried out before assignment;
  • ++ after i means incrementation must be carried out after assignment:

how to put focus on TextBox when the form load?

it's worked for me set tabindex to 0 this.yourtextbox.TabIndex = 0;

How to convert minutes to hours/minutes and add various time values together using jQuery?

I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.

function minutesToHHMM (mins, twentyFour = false) {
  let h = Math.floor(mins / 60);
  let m = mins % 60;
  m = m < 10 ? '0' + m : m;

  if (twentyFour) {
    h = h < 10 ? '0' + h : h;
    return `${h}:${m}`;
  } else {
    let a = 'am';
    if (h >= 12) a = 'pm';
    if (h > 12) h = h - 12;
    return `${h}:${m} ${a}`;
  }
}

How to use `replace` of directive definition?

As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.

First result:

<span myd1="">directive template1</span>

Second result:

<div myd2=""><span>directive template2</span></div>

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.

Be careful of the accepted answer, it fails if the time_point is before the epoch.

This line of code:

std::size_t fractional_seconds = ms.count() % 1000;

will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).

How to add external fonts to android application

The easiest way to accomplish this is to package the desired font(s) with your application. To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there.

Then, you need to tell your widgets to use that font. Unfortunately, you can no longer use layout XML for this, since the XML does not know about any fonts you may have tucked away as an application asset. Instead, you need to make the change in Java code, by calling Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”), then taking the created Typeface object and passing it to your TextView via setTypeface().

For more reference here is the tutorial where I got this:

http://www.androidguys.com/2008/08/18/fun-with-fonts/

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

enter image description here

  • Choose the new UI Design >> next
  • Just try to cancel the "Downloading Components" from upper right corner 'X' button.
  • A dialog box will appear then click OK (wait a bit for first time launch)

Docker CE on RHEL - Requires: container-selinux >= 2.9

I followed many links including the official documentation, however it all ended up in this error:

Requires: container-selinux >= 2.9
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest

The only way it worked for me is as follows (yum upgrade worked I guess):

yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

yum upgrade docker-ce

Are dictionaries ordered in Python 3.6+?

I wanted to add to the discussion above but don't have the reputation to comment.

Python 3.8 is not quite released yet, but it will even include the reversed() function on dictionaries (removing another difference from OrderedDict.

Dict and dictviews are now iterable in reversed insertion order using reversed(). (Contributed by Rémi Lapeyre in bpo-33462.) See what's new in python 3.8

I don't see any mention of the equality operator or other features of OrderedDict so they are still not entirely the same.

Upper memory limit?

Not only are you reading the whole of each file into memory, but also you laboriously replicate the information in a table called list_of_lines.

You have a secondary problem: your choices of variable names severely obfuscate what you are doing.

Here is your script rewritten with the readlines() caper removed and with meaningful names:

file_A1_B1 = open("A1_B1_100000.txt", "r")
file_A2_B2 = open("A2_B2_100000.txt", "r")
file_A1_B2 = open("A1_B2_100000.txt", "r")
file_A2_B1 = open("A2_B1_100000.txt", "r")
file_write = open ("average_generations.txt", "w")
mutation_average = open("mutation_average", "w") # not used
files = [file_A2_B2,file_A2_B2,file_A1_B2,file_A2_B1]
for afile in files:
    table = []
    for aline in afile:
        values = aline.split('\t')
        values.remove('\n') # why?
        table.append(values)
    row_count = len(table)
    row0length = len(table[0])
    print_counter = 4
    for column_index in range(row0length):
        column_total = 0
        for row_index in range(row_count):
            number = float(table[row_index][column_index])
            column_total = column_total + number
        column_average = column_total/row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1
file_write.write('\n')

It rapidly becomes apparent that (1) you are calculating column averages (2) the obfuscation led some others to think you were calculating row averages.

As you are calculating column averages, no output is required until the end of each file, and the amount of extra memory actually required is proportional to the number of columns.

Here is a revised version of the outer loop code:

for afile in files:
    for row_count, aline in enumerate(afile, start=1):
        values = aline.split('\t')
        values.remove('\n') # why?
        fvalues = map(float, values)
        if row_count == 1:
            row0length = len(fvalues)
            column_index_range = range(row0length)
            column_totals = fvalues
        else:
            assert len(fvalues) == row0length
            for column_index in column_index_range:
                column_totals[column_index] += fvalues[column_index]
    print_counter = 4
    for column_index in column_index_range:
        column_average = column_totals[column_index] / row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1

Split data frame string column into multiple columns

Since R version 3.4.0 you can use strcapture() from the utils package (included with base R installs), binding the output onto the other column(s).

out <- strcapture(
    "(.*)_and_(.*)",
    as.character(before$type),
    data.frame(type_1 = character(), type_2 = character())
)

cbind(before["attr"], out)
#   attr type_1 type_2
# 1    1    foo    bar
# 2   30    foo  bar_2
# 3    4    foo    bar
# 4    6    foo  bar_2

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

Binding Button click to a method

Click is an event. In your code behind, you need to have a corresponding event handler to whatever you have in the XAML. In this case, you would need to have the following:

private void Command(object sender, RoutedEventArgs e)
{

}

Commands are different. If you need to wire up a command, you'd use the Commmand property of the button and you would either use some pre-built Commands or wire up your own via the CommandManager class (I think).

How to create Select List for Country and States/province in MVC

Thank You All! I am able to to load Select List as per MVC now My Working Code is below:

HTML+MVC Code in View:-

    <tr>
        <th>@Html.Label("Country")</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
    </tr>
    <tr>
        <th>@Html.LabelFor(x=>x.Province)</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
    </tr>

Created a Controller under "UTIL" folder: Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MedAvail.Applications.MedProvision.Web.Util
{
    public class SelectListItemHelper
    {
        public static IEnumerable<SelectListItem> GetProvincesList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "California", Value = "B"},
                new SelectListItem{Text = "Alaska", Value = "B"},
                new SelectListItem{Text = "Illinois", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


        public static IEnumerable<SelectListItem> GetCountryList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "United States", Value = "B"},
                new SelectListItem{Text = "Canada", Value = "B"},
                new SelectListItem{Text = "United Kingdom", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


    }
}

And its working COOL now :-)

Thank you!!

Postgres Error: More than one row returned by a subquery used as an expression

USE LIMIT 1 - so It will return only 1 row. Example

customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)

Include another HTML file in a HTML file

My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:

a.html:

<html> 
  <body>
  <h1>Put your HTML content before insertion of b.js.</h1>
      ...

  <script src="b.js"></script>

      ...

  <p>And whatever content you want afterwards.</p>
  </body>
</html>

b.js:

document.write('\
\
    <h1>Add your HTML code here</h1>\
\
     <p>Notice however, that you have to escape LF's with a '\', just like\
        demonstrated in this code listing.\
    </p>\
\
');

The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.

In order to get the properly escaped JavaScript file without much work, you can use the following sed command:

sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html

Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html to b.js: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.

Alternatively for browsers that support template literals the following also works:

b.js:

document.write(`

    <h1>Add your HTML code here</h1>

     <p>Notice, you do not have to escape LF's with a '\',
        like demonstrated in the above code listing.
    </p>

`);

How can I import Swift code to Objective-C?

#import <TargetName-Swift.h>

you will see when you enter from keyboard #import < and after automaticly Xcode will advice to you.

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

remove empty lines from text file with PowerShell

This removes trailing whitespace and blank lines from file.txt

PS C:\Users\> (gc file.txt) | Foreach {$_.TrimEnd()} | where {$_ -ne ""} | Set-Content file.txt

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Reset identity seed after deleting records in SQL Server

@jacob

DBCC CHECKIDENT ('[TestTable]', RESEED,0)
DBCC CHECKIDENT ('[TestTable]', RESEED)

Worked for me, I just had to clear all entries first from the table, then added the above in a trigger point after delete. Now whenever i delete an entry is taken from there.

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

For many S3 API packages (I recently had this problem the npm s3 package) you can run into issues where the region is assumed to be US Standard, and lookup by name will require you to explicitly define the region if you choose to host a bucket outside of that region.

How to retrieve Jenkins build parameters using the Groovy API?

The following can be used to retreive an environment parameter:

println System.getenv("MY_PARAM") 

In c, in bool, true == 1 and false == 0?

You neglected to say which version of C you are concerned about. Let's assume it's this one:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

As you can see by reading the specification, the standard definitions of true and false are 1 and 0, yes.

If your question is about a different version of C, or about non-standard definitions for true and false, then ask a more specific question.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

If you're running into this error with Windows 8/Windows Server 2012 and .Net 4.5 follow these instructions here: http://www.britishdeveloper.co.uk/2013/01/handler-extensionlessurlhandler.html

Go to "turn Windows features on or off" Then Internet Information Services Then World Wide Web Services Then Application Development Features And then enable ASP.NET 4.5

This worked for me (although the wizard and wording is a little different in Windows Server 2012, but you'll figure it out). With this being said, why this is necessary after installing everything through the Web Platform Installer including all of the dependencies is completely beyond me...

Count number of rows per group and add result to original data frame

Using data.table:

library(data.table)
dt = as.data.table(df)

# or coerce to data.table by reference:
# setDT(df)

dt[ , count := .N, by = .(name, type)]

For pre-data.table 1.8.2 alternative, see edit history.


Using dplyr:

library(dplyr)
df %>%
  group_by(name, type) %>%
  mutate(count = n())

Or simply:

add_count(df, name, type)

Using plyr:

plyr::ddply(df, .(name, type), transform, count = length(num))

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

How do I enable php to work with postgresql?

  • SO: Windows/Linux
  • HTTP Web Server: Apache
  • Programming language: PHP

Enable PHP to work with PostgreSQL in Apache

In Apache I edit the following configuration file: C:\xampp\php.ini

I make sure to have the following lines uncommented:

extension=php_pgsql.dll 
extension=php_pdo_pgsql.dll

Finally restart Apache before attempting a new connection to the database engine.


Also, I leave my code that ensures that the connection is unique:

private static $pdo = null;

public static function provideDataBaseInstance() {
    if (self::$pdo == null) {
        $dsn = "pgsql:host=" . HOST .
               ";port=5432;dbname=" . DATABASE .
               ";user=" . POSTGRESQL_USER .
               ";password=" . POSTGRESQL_PASSWORD;
        try {
            self::$pdo = new PDO($dsn);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            echo $msg . 
                 ". Do not forget to enable in the web server the database 
                  manager for php and in the database instance authorize the 
                  ip of the server instance if they not in the same 
                  instance.";
        }
    }
    return self::$pdo;
}

GL

Split / Explode a column of dictionaries into separate columns with pandas

How do I split a column of dictionaries into separate columns with pandas?

pd.DataFrame(df['val'].tolist()) is the canonical method for exploding a column of dictionaries

Here's your proof using a colorful graph.

enter image description here

Benchmarking code for reference.

Note that I am only timing the explosion since that's the most interesting part of answering this question - other aspects of result construction (such as whether to use pop or drop) are tangential to the discussion and can be ignored (it should be noted however that using pop avoids the followup drop call, so the final solution is a bit more performant, but we are still listifying the column and passing it to pd.DataFrame either way).

Additionally, pop destructively mutates the input DataFrame, making it harder to run in benchmarking code which assumes the input is not changed across test runs.


Critique of other solutions

  • df['val'].apply(pd.Series) is extremely slow for large N as pandas constructs Series objects for each row, then proceeds to construct a DataFrame from them. For larger N the performance dips to the order of minutes or hours.

  • pd.json_normalize(df['val'])) is slower simply because json_normalize is meant to work with a much more complex input data - particularly deeply nested JSON with multiple record paths and metadata. We have a simple flat dict for which pd.DataFrame suffices, so use that if your dicts are flat.

  • Some answers suggest df.pop('val').values.tolist() or df.pop('val').to_numpy().tolist(). I don't think it makes much of a difference whether you listify the series or the numpy array. It's one operation less to listify the series directly and really isn't slower so I'd recommend avoiding generating the numpy array in the intermediate step.

How do I get the object if it exists, or None if it does not exist?

From django docs

get() raises a DoesNotExist exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist

You can catch the exception and assign None to go.

from django.core.exceptions import ObjectDoesNotExist
try:
    go  = Content.objects.get(name="baby")
except ObjectDoesNotExist:
    go = None

How does one convert a HashMap to a List in Java?

Basically you should not mess the question with answer, because it is confusing.

Then you could specify what convert mean and pick one of this solution

List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));

List<String> valueList = Collections.list(Collections.enumeration(map.values()));

Clicking a checkbox with ng-click does not update the model

.task{ng:{repeat:'task in model.tasks'}}
  %input{type:'checkbox',ng:{model:'$parent.model.tasks[$index].enabled'}}

Specifying trust store information in spring boot application.properties

java properties "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" do not correspond to "server.ssl.trust-store" and "server.ssl.trust-store-password" from Spring boot "application.properties" ("application.yml")

so you can not set "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" simply by setting "server.ssl.trust-store" and "server.ssl.trust-store-password" in "application.properties" ("application.yml")

an alternative of setting "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" is by Spring boot Externalized Configuration

below are excerpts of my implementation :

Params class holds the external settings

@Component
@ConfigurationProperties("params")
public class Params{

    //default values, can be override by external settings
    public static String trustStorePath = "config/client-truststore.jks";
    public static String trustStorePassword = "wso2carbon";
    public static String keyStorePath = "config/wso2carbon.jks";
    public static String keyStorePassword = "wso2carbon";
    public static String defaultType = "JKS";
    
    public void setTrustStorePath(String trustStorePath){
        Params.trustStorePath = trustStorePath;
    }
           
    public void settrustStorePassword(String trustStorePassword){
        Params.trustStorePassword=trustStorePassword;
    }

    public void setKeyStorePath(String keyStorePath){
        Params.keyStorePath = keyStorePath;
    }
         
    public void setkeyStorePassword(String keyStorePassword){
        Params.keyStorePassword = keyStorePassword;
    }
    
    public void setDefaultType(String defaultType){
        Params.defaultType = defaultType;
    }

KeyStoreUtil class undertakes the settings of "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword"

public class KeyStoreUtil {
    
    public static void setTrustStoreParams() {
        File filePath = new File( Params.trustStorePath);
        String tsp = filePath.getAbsolutePath();
        System.setProperty("javax.net.ssl.trustStore", tsp);
        System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);

    }

    public static void setKeyStoreParams() {
        File filePath = new File(Params.keyStorePath);
        String ksp = filePath.getAbsolutePath();
        System.setProperty("Security.KeyStore.Location", ksp);
        System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);

    }     
}

you get the setters executed within the startup function

@SpringBootApplication
@ComponentScan("com.myapp.profiles")
public class ProfilesApplication {

    public static void main(String[] args) {
        KeyStoreUtil.setKeyStoreParams();
        KeyStoreUtil.setTrustStoreParams();
        SpringApplication.run(ProfilesApplication.class, args);
    }
}

Edited on 2018-10-03

you may also want to adopt the annotation "PostConstruct" as as an alternative to execute the setters

import javax.annotation.PostConstruct;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.xxx"})
public class GateApplication {

    public static void main(String[] args) {
        SpringApplication.run(GateApplication.class, args);
    }
    
    @PostConstruct
    void postConstruct(){
        setTrustStoreParams();
        setKeyStoreParams();
    }
    
    
    private static void setTrustStoreParams() {
        File filePath = new File( Params.trustStorePath);
        String tsp = filePath.getAbsolutePath();
        System.setProperty("javax.net.ssl.trustStore", tsp);
        System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);

    }

    private static void setKeyStoreParams() {
        File filePath = new File(Params.keyStorePath);
        String ksp = filePath.getAbsolutePath();
        System.setProperty("Security.KeyStore.Location", ksp);
        System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);

    }
}

the application.yml

---
 params: 
   trustStorePath: config/client-truststore.jks
   trustStorePassword: wso2carbon
   keyStorePath: config/wso2carbon.jks
   keyStorePassword: wso2carbon
   defaultType: JKS
---

finally, within the running environment(deployment server), you create a folder named "config" under the same folder where the jar archive is stored .

within the "config" folder, you store "application.yml", "client-truststore.jks", and "wso2carbon.jks". done!

Update on 2018-11-27 about Spring boot 2.x.x

starting from spring boot 2.x.x, static properties are no longer supported, please see here. I personally do not think it a good move, because complex changes have to be made along the reference chain...

anyway, an implementation excerpt might look like this

the 'Params' class

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import lombok.Data;
    
    /**
     * Params class represent all config parameters that can 
     * be external set by spring xml file
     */
    
    @Component
    @ConfigurationProperties("params")
    @Data
    public class Params{
    
        //default values, can be override by external settings
        public String trustStorePath = "config/client-truststore.jks";
        public String trustStorePassword = "wso2carbon";
        public String keyStorePath = "config/wso2carbon.jks";
        public String keyStorePassword = "wso2carbon";
        public String defaultType = "JKS";  
}

the 'Springboot application class' (with 'PostConstruct')

import java.io.File;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.xx.xx"})
public class BillingApplication {
    
    @Autowired
    Params params;
    
    public static void main(String[] args) {
        SpringApplication.run(BillingApplication.class, args);
    }
    
    @PostConstruct
    void postConstruct() {
        
        // set TrustStoreParams
        File trustStoreFilePath = new File(params.trustStorePath);
        String tsp = trustStoreFilePath.getAbsolutePath();
        System.setProperty("javax.net.ssl.trustStore", tsp);
        System.setProperty("javax.net.ssl.trustStorePassword", params.trustStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", params.defaultType);
        // set KeyStoreParams
        File keyStoreFilePath = new File(params.keyStorePath);
        String ksp = keyStoreFilePath.getAbsolutePath();
        System.setProperty("Security.KeyStore.Location", ksp);
        System.setProperty("Security.KeyStore.Password", params.keyStorePassword);
    }
    
}

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MaxWidth="200"/>
    </Grid.ColumnDefinitions>

    <TextBox Background="Azure" Text="Hello" />
</Grid>

Right way to split an std::string into a vector<string>

i made this custom function that will convert the line to vector

#include <iostream>
#include <vector>
#include <ctime>
#include <string>

using namespace std;

int main(){

    string line;
    getline(cin, line);
    int len = line.length();
    vector<string> subArray;

    for (int j = 0, k = 0; j < len; j++) {
        if (line[j] == ' ') {
            string ch = line.substr(k, j - k);
            k = j+1;
            subArray.push_back(ch);
        }
        if (j == len - 1) {
            string ch = line.substr(k, j - k+1);
            subArray.push_back(ch);
        }
    }

    return 0;
}

Resize UIImage and change the size of UIImageView

   if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:@"URL STRING1"]])
   {
       NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:@"URL STRING1"]];

       UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width];
       cell.imgview.image=tempImage;

   }
   else
   {
       [cell.imgview sd_setImageWithURL:[NSURL URLWithString:@"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
        {
            UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width];
            cell.imgview.image=tempImage;
//                [tableView beginUpdates];
//                [tableView endUpdates];

        }];
   }

How to add `style=display:"block"` to an element using jQuery?

$("#YourElementID").css("display","block");

Edit: or as dave thieben points out in his comment below, you can do this as well:

$("#YourElementID").css({ display: "block" });

Confirm button before running deleting routine from website

Call this function onclick of button

/*pass whatever you want instead of id */
function doConfirm(id) {
    var ok = confirm("Are you sure to Delete?");
    if (ok) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                window.location = "create_dealer.php";
            }
        }

        xmlhttp.open("GET", "delete_dealer.php?id=" + id);
        // file name where delete code is written
        xmlhttp.send();
    }
}

Difference between $(this) and event.target?

this is a reference for the DOM element for which the event is being handled (the current target). event.target refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.

You can get a good sense of this by reviewing the jQuery event docs, but in summary:

event.currentTarget

The current DOM element within the event bubbling phase.

event.delegateTarget

The element where the currently-called jQuery event handler was attached.

event.relatedTarget

The other DOM element involved in the event, if any.

event.target

The DOM element that initiated the event.

To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this) or $(evt.target).

The .attr() method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href') or simply evt.target.href will give you what you want.

Disable PHP in directory (including all sub-directories) with .htaccess

On production I prefer to redirect the requests to .php files under the directories where PHP processing should be disabled to a home page or to 404 page. This won't reveal any source code (why search engines should index uploaded malicious code?) and will look more friendly for visitors and even for evil hackers trying to exploit the stuff. Also it can be implemented in mostly in any context - vhost or .htaccess. Something like this:

<DirectoryMatch "^${docroot}/(image|cache|upload)/">
    <FilesMatch "\.php$">
        # use one of the redirections
        #RedirectMatch temp "(.*)" "http://${servername}/404/"
        RedirectMatch temp "(.*)" "http://${servername}"
    </FilesMatch>
</DirectoryMatch>

Adjust the directives as you need.

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

Is it possible to change the radio button icon in an android radio button group

Here's probably a quick approach,

enter image description here

With two icons shown above, you shall have a RadioGroup something like this

enter image description here

  • change the RadioGroup's orientation to horizontal
  • for each RadioButton's Properties, try giving the icon for Button under CompoundButton,
  • adjust the Padding and size,
  • and set the Background attribute when checked.

html <input type="text" /> onchange event not working

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

Using intents to pass data between activities

Try this from your AndroidTabRestaurantDescSearchListView activity

Intent intent  = new Intent(this,RatingDescriptionSearchActivity.class );
intent.putExtras( getIntent().getExtras() );
startActivity( intent );  

And then from RatingDescriptionSearchActivity activity just call

getIntent().getStringExtra("key")

How to change the session timeout in PHP?

Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.

If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.

Convenience in relaxed environments: how and why

If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:

// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);

session_start(); // ready to go!

This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.

  • If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.

    GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime, but the upper bound will be unpredictable.

  • If you don't set session.gc_maxlifetime to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.

Certainty in critical environments

You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.

Do this by saving the upper bound together with the rest of the session data:

session_start(); // ready to go!

$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
    // this session has worn out its welcome; kill it and start a brand new one
    session_unset();
    session_destroy();
    session_start();
}

// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;

Session id persistence

So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id when required.

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

Restore a postgres backup file using the command line?

Follow these 3 steps :

  1. start postgres server - sudo systemctl start postgresql
  2. enable same - sudo systemctl enable postgresql
  3. restore command - pg_restore -h localhost -p 5432 -U postgres -d old_db

assuming that the dump is there in the same directory

Links :

https://www.postgresqltutorial.com/postgresql-restore-database https://askubuntu.com/questions/50621/cannot-connect-to-postgresql-on-port-5432

What is 0x10 in decimal?

The simple version is 0x is a prefix denoting a hexadecimal number, source.

So the value you're computing is after the prefix, in this case 10.

But that is not the number 10. The most significant bit 1 denotes the hex value while 0 denotes the units.

So the simple math you would do is

0x10

1 * 16 + 0 = 16

Note - you use 16 because hex is base 16.

Another example:

0xF7

15 * 16 + 7 = 247

You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.

Display only date and no time

The date/time in the datebase won't be a formatted version at all. It'll just be the date/time itself. How you display that date/time when you extract the value from the database is a different matter. I strongly suspect you really just want:

model.Returndate = DateTime.Now.Date;

or possibly

model.Returndate = DateTime.UtcNow.Date;

Yes, if you look at the database using SQL Server Studio or whatever, you'll now see midnight - but that's irrelevant, and when you fetch the date out of the database and display it to a user, then you can apply the relevant format.

EDIT: In regard to your edited question, the problem isn't with the model - it's how you specify the view. You should use something like:

@Html.EditorFor(model => model.Returndate.Date.ToString("d"))

where d is the standard date and time format specifier for the short date pattern (which means it'll take the current cultural settings into account).

That's the bit I've been saying repeatedly - that when you display the date/time to the user, that's the time to format it as a date without a time.

EDIT: If this doesn't work, there should be a way of decorating the model or view with a format string - or something like that. I'm not really an MVC person, but it feels like there ought to be a good way of doing this declaratively...

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

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

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

You can see this link for a simple hello world servlet

Go build: "Cannot find package" (even though GOPATH is set)

I solved this problem by set my go env GO111MODULE to off

go env -w  GO111MODULE=off

What is the easiest way to parse an INI File in C++?

If you are interested in platform portability, you can also try Boost.PropertyTree. It supports ini as persistancy format, though the property tree my be 1 level deep only.

How to vertically align <li> elements in <ul>?

I had the same problem. Try this.

<nav>
    <ul>
        <li><a href="#">AnaSayfa</a></li>
        <li><a href="#">Hakkimizda</a></li>
        <li><a href="#">Iletisim</a></li>
    </ul>
</nav>
@charset "utf-8";

nav {
    background-color: #9900CC;
    height: 80px;
    width: 400px;
}

ul {
    list-style: none;
    float: right;
    margin: 0;
}

li {
    float: left;
    width: 100px;
    line-height: 80px;
    vertical-align: middle;
    text-align: center;
    margin: 0;
}

nav li a {
    width: 100px;
    text-decoration: none;
    color: #FFFFFF;
}

Cluster analysis in R: determine the optimal number of clusters

A simple solution is the library factoextra. You can change the clustering method and the method for calculate the best number of groups. For example if you want to know the best number of clusters for a k- means:

Data: mtcars

library(factoextra)   
fviz_nbclust(mtcars, kmeans, method = "wss") +
      geom_vline(xintercept = 3, linetype = 2)+
      labs(subtitle = "Elbow method")

Finally, we get a graph like:

enter image description here

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

How can I determine if a variable is 'undefined' or 'null'?

I still think the best/safe way to test these two conditions is to cast the value to a string:

var EmpName = $("div#esd-names div#name").attr('class');

// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
    // Do something with your code
}

// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
    // Do something with your code
}

How to get all values from python enum class?

class enum.Enum is a class that solves all your enumeration needs, so you just need to inherit from it, and add your own fields. Then from then on, all you need to do is to just call it's attributes: name & value:

from enum import Enum

class Letter(Enum):
   A = 1
   B = 2
   C = 3

print({i.name: i.value for i in Letter})
# prints {'A': 1, 'B': 2, 'C': 3}

Difference between using Throwable and Exception in a try catch

I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.

Splitting words into letters in Java

I'm pretty sure he doesn't want the spaces to be output though.

for (char c: s.toCharArray()) {
    if (isAlpha(c)) {
       System.out.println(c);
     }
}

nvarchar(max) still being truncated

I was creating a JSON-LD to create a site review script. **DECLARE @json VARCHAR(MAX);** The actual JSON is about 94K.

I got this to work by using the CAST('' AS VARCHAR(MAX)) + @json, as explained by other contributors:- so **SET @json = CAST('' AS VARCHAR(MAX)) + (SELECT .....**

2/ I also had to change the Query Options:- Query Options -> 'results' -> 'grid' -> 'Maximum Characters received' -> 'non-XML Data' SET to 2000000. (I left the 'results' -> 'text' -> 'Maximum number of characters displayed in each column' as the default)

Finding duplicate rows in SQL Server

select column_name, count(column_name)
from table_name
group by column_name
having count (column_name) > 1;

Src : https://stackoverflow.com/a/59242/1465252

Laravel Password & Password_Confirmation Validation

It should be enough to do:

$this->validate($request, [
    'password' => 'sometimes,min:6,confirmed,required_with:password_confirmed',
]);

Make password optional, but if present requires a password_confirmation that matches, also make password required only if password_confirmed is present

Eclipse: Set maximum line length for auto formatting?

Click Project->preferences. Type format into the search - you should see java->code style->formatter. Click that, then edit - finally, the line wrapping tab - its there :)

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

You can use like the following

string result = null;
object value = cmd.ExecuteScalar();
 if (value != null)
 {
    result = value.ToString();
 }     
 conn.Close();
return result;

Java: get greatest common divisor

I used this method that I created when I was 14 years old.

    public static int gcd (int a, int b) {
        int s = 1;
        int ia = Math.abs(a);//<-- turns to absolute value
        int ib = Math.abs(b);
        if (a == b) {
            s = a;
        }else {
            while (ib != ia) {
                if (ib > ia) {
                    s = ib - ia;
                    ib = s;
                }else { 
                    s = ia - ib;
                    ia = s;
                }
            }
        }
        return s;
    }

The type initializer for 'MyClass' threw an exception

Dictionary keys should be unique !

In my case, I was using a Dictionary, and I found two items in it have accidentally the same key.

Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
            {"KEY1", "V1"},
            {"KEY1", "V2" },
            {"KEY3", "V3"},
        };

Iterate through a C++ Vector using a 'for' loop

 //different declaration type
    vector<int>v;  
    vector<int>v2(5,30); //size is 5 and fill up with 30
    vector<int>v3={10,20,30};
    
    //From C++11 and onwards
    for(auto itr:v2)
        cout<<"\n"<<itr;
     
     //(pre c++11)   
    for(auto itr=v3.begin(); itr !=v3.end(); itr++)
        cout<<"\n"<<*itr;

Adding a css class to select using @Html.DropDownList()

Try this:

@Html.DropDownList(
    "country", 
    new[] {
        new SelectListItem() { Value = "IN", Text = "India" },
        new SelectListItem() { Value = "US", Text = "United States" }
    }, 
    "Country",
    new { @class = "form-control",@selected = Model.Country}
)

Stretch and scale a CSS image in the background - with CSS only

You can use the border-image : yourimage property to scale the image up to the border. Even if you give the background-image, the border image will be drawn over it.

The border-image property is very useful if your style sheet is implemented somewhere which doesn't support CSS 3. If you are using Google Chrome or Firefox, then I recommend the background-size:cover property itself.

How to get the sizes of the tables of a MySQL database?

Heres another way of working this out from using the bash command line.

for i in mysql -NB -e 'show databases'; do echo $i; mysql -e "SELECT table_name AS 'Tables', round(((data_length+index_length)/1024/1024),2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema =\"$i\" ORDER BY (data_length + index_length) DESC" ; done

Connect HTML page with SQL server using javascript

<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;

$.ajax({
      type:"GET",
      url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
      crossDomain:true,
      dataType:'jsonp',
      success: function jsondata(data)
           {

            var parsedata=JSON.parse(JSON.stringify(data));
            var logindata=parsedata["Status"];

            if("sucess"==logindata)
            {   
                alert("success");
            }
            else
            {
                alert("failed");
            }
          }  
    }); 
<script>

You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.

Trying to retrieve first 5 characters from string in bash error?

Works here:

$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=${TESTSTRINGONE:0:5}
$ echo ${NEWTESTSTRING}
MOTES

What shell are you using?

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How to do a subquery in LINQ?

There is no subquery needed with this statement, which is better written as

select u.* 
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId        --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)

or

select u.* 
from Users u inner join CompanyRolesToUsers c
             on u.Id = c.UserId    --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
  and c.CompanyRoleId in (2,3,4)

That being said, in LINQ it would be

from u in Users
from c in CompanyRolesToUsers 
where u.Id == c.UserId &&
      u.LastName.Contains("fra") &&
      selectedRoles.Contains(c.CompanyRoleId)
select u

or

from u in Users
join c in CompanyRolesToUsers 
       on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
      selectedRoles.Contains(c.CompanyRoleId)
select u

Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is...

How to query as GROUP BY in django?

The document says that you can use values to group the queryset .

class Travel(models.Model):
    interest = models.ForeignKey(Interest)
    user = models.ForeignKey(User)
    time = models.DateTimeField(auto_now_add=True)

# Find the travel and group by the interest:

>>> Travel.objects.values('interest').annotate(Count('user'))
<QuerySet [{'interest': 5, 'user__count': 2}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited for 2 times, 
# and the interest(id=6) had only been visited for 1 time.

>>> Travel.objects.values('interest').annotate(Count('user', distinct=True)) 
<QuerySet [{'interest': 5, 'user__count': 1}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited by only one person (but this person had 
#  visited the interest for 2 times

You can find all the books and group them by name using this code:

Book.objects.values('name').annotate(Count('id')).order_by() # ensure you add the order_by()

You can watch some cheet sheet here.

Inverse dictionary lookup in Python

There isn't one as far as I know of, one way however to do it is to create a dict for normal lookup by key and another dict for reverse lookup by value.

There's an example of such an implementation here:

http://code.activestate.com/recipes/415903-two-dict-classes-which-can-lookup-keys-by-value-an/

This does mean that looking up the keys for a value could result in multiple results which can be returned as a simple list.

Flutter position stack widget in center

Remove everything, but this:

Align(
  alignment: Alignment.bottomCenter,
  child: new ButtonBar(
    alignment: MainAxisAlignment.center,
    children: <Widget>[
      new OutlineButton(
        onPressed: () {
          Navigator.push(
            context,
            new MaterialPageRoute(
              builder: (context) => new LoginPage()));
        },
        child: new Text(
          "Login",
          style: new TextStyle(color: Colors.white),
        ),
      ),
      new RaisedButton(
        color: Colors.white,
        onPressed: () {
          Navigator.push(
            context,
            new MaterialPageRoute(
              builder: (context) =>
                new RegistrationPage()));
        },
        child: new Text(
          "Register",
          style: new TextStyle(color: Colors.black),
        ),
      )
    ],
  ),
)

In my theory, the additional Container is destroying it. I would advise you to just surround this by adding Padding:

Padding(
  padding: EdgeInsets.only(bottom: 20.0),
  child: Align...
),

This seems a lot more reasonable to me than the Positioned and also I do not quite understand your Column with a single child only.

How to make a progress bar

I was writing up an answer to a similar question that got deleted, so I'm posting it here in case it's of use to anyone.

The markup can be dropped in anywhere and takes up 50px of vertical real estate even when hidden. (To have it take up no vertical space and instead overlay the top 50px, we can just give the progressContainerDiv absolute positioning (inside any positioned element) and style the display property instead of the visible property.)

The general structure is based on code presented in this Geeks for Geeks article.

_x000D_
_x000D_
const_x000D_
  progressContainerDiv = document.getElementById("progressContainerDiv");_x000D_
  progressShownDiv = document.getElementById("progressShownDiv");_x000D_
let_x000D_
  progress = 0,_x000D_
  percentageIncrease = 10;_x000D_
_x000D_
function animateProgress(){_x000D_
  progressContainerDiv.style.visibility = "visible";_x000D_
  const repeater = setInterval(increaseRepeatedly, 100);_x000D_
  function increaseRepeatedly(){_x000D_
    if(progress >= 100){_x000D_
      clearInterval(repeater);_x000D_
      progressContainerDiv.style.visibility = "hidden";_x000D_
      progressNumberSpan.innerHTML = "";_x000D_
      progress = 1;_x000D_
    }_x000D_
    else{_x000D_
      progress = Math.min(100, progress + percentageIncrease);_x000D_
      progressShownDiv.style.width = progress + "%";_x000D_
      progressNumberSpan.innerHTML = progress + "%";_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#progressContainerDiv{_x000D_
  visibility: hidden;_x000D_
  height: 40px;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#progressBackgroundDiv {_x000D_
  width: 50%;_x000D_
  margin-left: 24%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
  _x000D_
#progressShownDiv {_x000D_
  width: 1%;_x000D_
  height: 20px;_x000D_
  background-color: #4CAF50;_x000D_
}_x000D_
_x000D_
#progressNumberSpan{_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div id="progressContainerDiv">_x000D_
  <div id="progressBackgroundDiv">_x000D_
    <div id="progressShownDiv"></div>_x000D_
  </div>_x000D_
  <div id="progressNumberContainerDiv">_x000D_
    <span id="progressNumberSpan"></span>_x000D_
  </div>_x000D_
</div>_x000D_
<button type="button" onclick="animateProgress()">Go</button>_x000D_
<div id="display"></div>
_x000D_
_x000D_
_x000D_

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

EditText request focus

edittext.requestFocus() works for me in my Activity and Fragment

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

Storing JSON in database vs. having a new column for each key

It seems that you're mainly hesitating whether to use a relational model or not.

As it stands, your example would fit a relational model reasonably well, but the problem may come of course when you need to make this model evolve.

If you only have one (or a few pre-determined) levels of attributes for your main entity (user), you could still use an Entity Attribute Value (EAV) model in a relational database. (This also has its pros and cons.)

If you anticipate that you'll get less structured values that you'll want to search using your application, MySQL might not be the best choice here.

If you were using PostgreSQL, you could potentially get the best of both worlds. (This really depends on the actual structure of the data here... MySQL isn't necessarily the wrong choice either, and the NoSQL options can be of interest, I'm just suggesting alternatives.)

Indeed, PostgreSQL can build index on (immutable) functions (which MySQL can't as far as I know) and in recent versions, you could use PLV8 on the JSON data directly to build indexes on specific JSON elements of interest, which would improve the speed of your queries when searching for that data.

EDIT:

Since there won't be too many columns on which I need to perform search, is it wise to use both the models? Key-per-column for the data I need to search and JSON for others (in the same MySQL database)?

Mixing the two models isn't necessarily wrong (assuming the extra space is negligible), but it may cause problems if you don't make sure the two data sets are kept in sync: your application must never change one without also updating the other.

A good way to achieve this would be to have a trigger perform the automatic update, by running a stored procedure within the database server whenever an update or insert is made. As far as I'm aware, the MySQL stored procedure language probably lack support for any sort of JSON processing. Again PostgreSQL with PLV8 support (and possibly other RDBMS with more flexible stored procedure languages) should be more useful (updating your relational column automatically using a trigger is quite similar to updating an index in the same way).

multiple plot in one figure in Python

The OP states that each plot element overwrites the previous one rather than being combined into a single plot. This can happen even with one of the many suggestions made by other answers. If you select several lines and run them together, say:

plt.plot(<X>, <Y>)
plt.plot(<X>, <Z>)

the plot elements will typically be rendered together, one layer on top of the other. But if you execute the code line-by-line, each plot will overwrite the previous one.

This perhaps is what happened to the OP. It just happened to me: I had set up a new key binding to execute code by a single key press (on spyder), but my key binding was executing only the current line. The solution was to select lines by whole blocks or to run the whole file.

Is there a Python Library that contains a list of all the ascii characters?

You can do this without a module:

    characters = list(map(chr, range(97,123)))

Type characters and it should print ["a","b","c", ... ,"x","y","z"]. For uppercase use:

    characters=list(map(chr,range(65,91)))

Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range() to add more characters to the list.
map() calls chr() every iteration of the range().

What is an Endpoint?

An endpoint is the 'connection point' of a service, tool, or application accessed over a network. In the world of software, any software application that is running and "listening" for connections uses an endpoint as the "front door." When you want to connect to the application/service/tool to exchange data you connect to its endpoint

Unfamiliar symbol in algorithm: what does ? mean?

Can be read, "For all s such that s does not equal s[start]"

Add two numbers and display result in textbox with Javascript

It should be document.getElementById("txtresult").value= result;

You are setting the value of the textbox to the result. The id="txtresult" is not an HTML element.

NTFS performance and large volumes of files and directories

Here's some advice from someone with an environment where we have folders containing tens of millions of files.

  1. A folder stores the index information (links to child files & child folder) in an index file. This file will get very large when you have a lot of children. Note that it doesn't distinguish between a child that's a folder and a child that's a file. The only difference really is the content of that child is either the child's folder index or the child's file data. Note: I am simplifying this somewhat but this gets the point across.
  2. The index file will get fragmented. When it gets too fragmented, you will be unable to add files to that folder. This is because there is a limit on the # of fragments that's allowed. It's by design. I've confirmed it with Microsoft in a support incident call. So although the theoretical limit to the number of files that you can have in a folder is several billions, good luck when you start hitting tens of million of files as you will hit the fragmentation limitation first.
  3. It's not all bad however. You can use the tool: contig.exe to defragment this index. It will not reduce the size of the index (which can reach up to several Gigs for tens of million of files) but you can reduce the # of fragments. Note: The Disk Defragment tool will NOT defrag the folder's index. It will defrag file data. Only the contig.exe tool will defrag the index. FYI: You can also use that to defrag an individual file's data.
  4. If you DO defrag, don't wait until you hit the max # of fragment limit. I have a folder where I cannot defrag because I've waited until it's too late. My next test is to try to move some files out of that folder into another folder to see if I could defrag it then. If this fails, then what I would have to do is 1) create a new folder. 2) move a batch of files to the new folder. 3) defrag the new folder. repeat #2 & #3 until this is done and then 4) remove the old folder and rename the new folder to match the old.

To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:

a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or

b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.

Read below only if you're bored.

The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.

So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().